-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDexMate.py
More file actions
2017 lines (1676 loc) · 84.2 KB
/
Copy pathDexMate.py
File metadata and controls
2017 lines (1676 loc) · 84.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# MIT License
#
# Copyright (c) 2024-2025 rpimaster
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import tkinter as tk
from tkinter import messagebox, ttk, simpledialog
import json
import datetime
import logging
from pydexcom import Dexcom
from notifypy import Notify
from cryptography.fernet import Fernet
import os
import stat
import requests
import hashlib
import numpy as np
from sklearn.linear_model import LinearRegression
import time
import random
import base64
import tempfile
import threading
import webbrowser
import packaging.version # For version comparison
import subprocess
import sys
import shutil
import platform
import ctypes
from PIL import Image
from sklearn.utils import resample
# Get platform-specific application support directory
def get_app_support_dir():
"""Determine the application support directory with fallbacks for restricted environments."""
# 1. Check custom environment variable first
custom_path = os.environ.get('DEXMATE_DATA_PATH')
if custom_path:
custom_path = os.path.abspath(os.path.expanduser(custom_path))
try:
os.makedirs(custom_path, exist_ok=True)
# Test write permission
test_file = os.path.join(custom_path, 'write_test.tmp')
with open(test_file, 'w') as f:
f.write("test")
os.remove(test_file)
return custom_path
except Exception:
pass # We'll try other locations
# 2. Create dedicated DexMate directory in user's home folder
home_path = os.path.expanduser("~")
dexmate_home_path = os.path.join(home_path, "DexMateData")
try:
os.makedirs(dexmate_home_path, exist_ok=True)
# Test write permission
test_file = os.path.join(dexmate_home_path, 'write_test.tmp')
with open(test_file, 'w') as f:
f.write("test")
os.remove(test_file)
return dexmate_home_path
except Exception as e:
logging.warning(f"Home directory not writable: {e}")
# 3. Platform-specific standard locations (as fallback only)
system = platform.system()
standard_path = None
if system == "Darwin":
standard_path = os.path.join(os.path.expanduser("~"), "Library", "Application Support", "DexMate")
elif system == "Windows":
base_path = os.environ.get("LOCALAPPDATA", os.path.join(os.environ["USERPROFILE"], "AppData", "Local"))
standard_path = os.path.join(base_path, "DexMate")
else: # Linux and other
data_home = os.environ.get("XDG_DATA_HOME", os.path.join(os.path.expanduser("~"), ".local", "share"))
standard_path = os.path.join(data_home, "DexMate")
# 4. Try to use standard location
if standard_path:
try:
os.makedirs(standard_path, exist_ok=True)
# Test write permission
test_file = os.path.join(standard_path, 'write_test.tmp')
with open(test_file, 'w') as f:
f.write("test")
os.remove(test_file)
return standard_path
except Exception as e:
logging.warning(f"Standard directory not writable: {e}")
# 5. Fallback to portable directory in executable location
try:
if getattr(sys, 'frozen', False): # Running as executable
base_path = os.path.dirname(sys.executable)
else: # Running as script
base_path = os.path.dirname(os.path.abspath(__file__))
portable_path = os.path.join(base_path, "DexMateData")
os.makedirs(portable_path, exist_ok=True)
return portable_path
except Exception as e:
logging.warning(f"Portable directory creation failed: {e}")
# 6. Final fallback to temporary directory
temp_path = tempfile.mkdtemp(prefix="DexMate_")
logging.warning(f"Using temporary directory: {temp_path}")
return temp_path
# Initialize application support directory before any usage
app_support_dir = get_app_support_dir()
# Log that we've successfully initialized logging
logging.info("Logging system initialized successfully")
logging.info(f"Application support directory: {app_support_dir}")
# Current app version - update this with each release
VERSION = "2.0.0"
# GitHub API URL for checking latest release
UPDATE_CHECK_URL = "https://api.github.com/repos/rpimaster/DexMate/releases/latest"
class GlucoseWidget:
# Define helper methods first
@staticmethod
def get_file_path(filename):
"""Get full path for a file in application support directory"""
return os.path.join(app_support_dir, filename)
def get_icon_path(self):
"""Get path to application icon, copy if needed."""
# Use the global app_support_dir that's now defined
icon_path = os.path.join(app_support_dir, "logo_png.png")
# Only attempt to copy if the icon doesn't exist
if not os.path.exists(icon_path):
try:
# Determine base path for resources
if getattr(sys, 'frozen', False): # Running as a PyInstaller bundle
base_path = sys._MEIPASS
else: # Running as a script
base_path = os.path.dirname(os.path.abspath(__file__))
source_icon = os.path.join(base_path, "logo_png.png")
if os.path.exists(source_icon):
shutil.copy(source_icon, icon_path)
logging.info(f"Copied application icon to {icon_path}")
else:
logging.warning(f"Source icon not found at {source_icon}")
except Exception as e:
logging.error(f"Error copying icon: {e}")
return icon_path
def __init__(self, root):
"""Initialize the application."""
self.root = root
# Initialize attributes
self.opacity = 0.8 # Default opacity value
# ... other attributes ...
# Initialize the rest of the class
# ... existing code ...
# Initialize attributes early
self.data_source = "Dexcom" # Default data source
self.unit = "mmol" # Default unit (initialize early to avoid AttributeError)
self.prediction_enabled = True # Default value for prediction_enabled
self.prediction_history = [] # Initialize prediction history
self.max_history = 6 # Use last 6 readings for prediction
# Initialize file paths using helper methods
self.key_file_path = self.get_file_path('secret.key')
self.credentials_file_path = self.get_file_path('credentials.json')
self.settings_file_path = self.get_file_path('settings.json')
self.history_file = self.get_file_path('history.json')
# Set DexMate logo path
self.dexmate_icon_path = self.get_icon_path()
# Set DexMate logo as window icon
if self.dexmate_icon_path and os.path.exists(self.dexmate_icon_path):
try:
# Windows needs special handling for .ico files
if platform.system() == "Windows":
# Convert PNG to ICO in temp directory
ico_path = self.convert_png_to_ico(self.dexmate_icon_path)
if ico_path:
self.root.iconbitmap(ico_path)
logging.info("Windows icon set using ICO")
else:
# Fallback to PNG if conversion fails
self.icon_img = tk.PhotoImage(file=self.dexmate_icon_path)
self.root.iconphoto(True, self.icon_img)
logging.info("Windows icon set using PNG fallback")
else:
# Non-Windows platforms can use PNG directly
self.icon_img = tk.PhotoImage(file=self.dexmate_icon_path)
self.root.iconphoto(True, self.icon_img)
logging.info("Main window icon set successfully")
except Exception as e:
logging.error(f"Error setting window icon: {e}")
else:
logging.warning("DexMate icon not available")
self.login_window = None # Initialize login_window as None
self.login_window_created = False # Track whether the login window has been created
self.root.title("DexMate")
self.root.geometry("300x270") # Increased height for prediction label
# Add prediction history before any updates
logging.info(f"Max history initialized: {self.max_history}")
self.label = tk.Label(root, text="Glucose Level:")
self.label.pack(pady=5)
self.glucose_value = tk.StringVar()
self.glucose_label = tk.Label(root, textvariable=self.glucose_value, font=("Helvetica", 22))
self.glucose_label.pack()
self.trend_label = tk.Label(root, text="", font=("Helvetica", 22))
self.trend_label.pack(pady=5)
self.time_label = tk.Label(root, text="", font=("Helvetica", 12))
self.time_label.pack(pady=5)
self.delta_label = tk.Label(root, text="", font=("Helvetica", 12))
self.delta_label.pack(pady=5)
# Add prediction label with delta and trend
self.prediction_label = tk.Label(root, text="Prediction: --", font=("Helvetica", 12))
self.prediction_label.pack(pady=5)
# Default target range in mmol
self.target_range = (3.9, 12.0)
self.last_reading_time = None # Initialize last reading time to NONE
self.dexcom = None # Initialize dexcom object to None
self.previous_glucose = None
self.notifications_snoozed_until = None # To track the snooze status
self.connection_retries = 0 # Track connection retries
self.max_retries = 5 # Max connection retries before giving up
self.last_successful_update = None # Track last successful update time
self.locations = [self.set_top_left, self.set_bottom_left, self.set_bottom_right, self.set_top_right]
self.current_location = 0
# Create a frame for the buttons
self.button_frame = tk.Frame(root)
self.button_frame.pack(pady=5) # Add padding around the frame
# Create a button for changing widget location
self.location_button = tk.Button(self.button_frame, text="Change Location", command=self.change_location)
self.location_button.pack(side="left", padx=10) # Pack left with some padding
# Create a settings button
self.settings_button = tk.Button(self.button_frame, text="Settings", command=self.open_settings)
self.settings_button.pack(side="left", padx=10) # Pack left with some padding
# Load saved settings
self.load_settings()
# Load the last saved position with fallbacks
self.load_last_position()
# Always load prediction history
self.prediction_history = self.load_history() or []
logging.info(f"Loaded prediction history: {len(self.prediction_history)} entries")
# Only show prediction UI if enabled
if self.prediction_enabled:
self.prediction_label.pack(pady=5)
else:
self.prediction_label.pack_forget()
# Check if credentials are already saved, if not, show the login window
self.check_saved_credentials()
# Variable to track the pin state
self.is_pinned = False
# Bind the window close event to save the position
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
# Initial update of labels
self.update_labels()
self.schedule_update() # Schedule periodic updates
# Check for updates in the background
self.check_for_updates()
# Obfuscate sensitive strings in memory
self.OBFUSCATOR = os.urandom(16)
# Register cleanup for secure memory wipe
import atexit
atexit.register(self.secure_cleanup)
# Verify directory permissions at startup
if not self.verify_directory_permissions():
messagebox.showwarning(
"Permission Issue",
f"Couldn't write to data directory:\n{app_support_dir}\n"
"Some features may not work properly."
)
def convert_target_range(self, min_val, max_val, from_unit, to_unit):
"""Convert target range between units"""
if from_unit == to_unit:
return min_val, max_val
if from_unit == "mmol" and to_unit == "mgdl":
return min_val * 18.0, max_val * 18.0
elif from_unit == "mgdl" and to_unit == "mmol":
return min_val / 18.0, max_val / 18.0
return min_val, max_val
def convert_png_to_ico(self, png_path):
"""Convert PNG to ICO format for Windows icons."""
try:
# Save the .ico file in the application support directory
ico_path = os.path.join(app_support_dir, "dexmate.ico")
# Open PNG and convert to ICO
img = Image.open(png_path)
img.save(ico_path, format='ICO')
logging.info(f"Converted PNG to ICO: {ico_path}")
return ico_path
except ImportError:
logging.warning("Pillow not installed, cannot convert PNG to ICO")
except Exception as e:
logging.error(f"Error converting PNG to ICO: {e}")
return None
def convert_png_to_temp_bmp(self, png_path):
"""Convert PNG to temporary BMP for Windows notifications."""
try:
if not png_path or not os.path.exists(png_path):
return None
# Create temp BMP file in application support directory
bmp_path = os.path.join(app_support_dir, "temp_notify_icon.bmp")
# Open PNG and convert to BMP
img = Image.open(png_path)
img.save(bmp_path, format='BMP')
logging.info(f"Converted PNG to BMP: {bmp_path}")
return bmp_path
except Exception as e:
logging.error(f"PNG to BMP conversion failed: {e}")
return None
def toggle_pin_on_top(self):
self.is_pinned = not self.is_pinned
self.root.wm_attributes("-topmost", self.is_pinned)
self.pin_on_top_button.config(text="Unpin" if self.is_pinned else "Pin on Top")
def check_saved_credentials(self):
"""Check saved credentials and authenticate if available."""
config = self.load_config()
if config:
self.data_source = config.get("data_source", "")
self.region = config.get("region", "us")
self.unit = config.get("unit", "mmol")
# ... (rest of existing code) ...
else:
self.data_source = "" # Ensure it's empty if no config
# Show login window if no data source is set
if not self.data_source:
self.show_login_window()
return
# Get credentials from ENCRYPTED storage
all_credentials = self.get_saved_credentials()
if self.data_source == "Dexcom":
credentials = all_credentials.get("Dexcom", {})
if credentials.get("username") and credentials.get("password"):
self.authenticate_dexcom(credentials["username"], credentials["password"])
else:
self.show_login_window()
elif self.data_source == "Nightscout":
credentials = all_credentials.get("Nightscout", {})
if credentials.get("url"):
self.nightscout_url = credentials["url"]
self.nightscout_api_secret = credentials.get("api_secret")
else:
self.show_login_window()
def generate_key(self):
"""Generate a new encryption key with secure permissions."""
key = Fernet.generate_key()
with open(self.key_file_path, 'wb') as key_file:
key_file.write(key)
# Set restrictive file permissions
self.set_file_permissions(self.key_file_path)
return key
def load_key(self):
"""Load encryption key with validation."""
try:
# Verify file exists and has content
if not os.path.exists(self.key_file_path) or os.path.getsize(self.key_file_path) == 0:
return self.generate_key()
with open(self.key_file_path, 'rb') as key_file:
key = key_file.read()
# Validate key format
if len(key) != 44: # Fernet keys are 44 bytes in base64
logging.warning("Invalid key format detected, generating new key")
return self.generate_key()
return key
except Exception as e:
logging.error(f"Key loading error: {e}")
return self.generate_key()
def encrypt_credentials(self, credentials):
"""Encrypt credentials with additional validation."""
key = self.load_key()
fernet = Fernet(key)
# Add timestamp to detect stale credentials
credentials['timestamp'] = datetime.datetime.now().isoformat()
credential_data = json.dumps(credentials).encode()
# Add random padding to obscure data length
padding = os.urandom(random.randint(5, 15))
padded_data = padding + credential_data
return fernet.encrypt(padded_data)
def decrypt_credentials(self, encrypted_credentials):
"""Decrypt credentials with validation checks."""
key = self.load_key()
fernet = Fernet(key)
decrypted = fernet.decrypt(encrypted_credentials)
# Remove random padding
try:
# Find first valid JSON character
start_index = next(i for i, byte in enumerate(decrypted)
if chr(byte) in '{["')
credential_data = decrypted[start_index:]
except (StopIteration, ValueError):
raise ValueError("Invalid credential format")
credentials = json.loads(credential_data.decode())
# Validate timestamp
cred_time = datetime.datetime.fromisoformat(credentials['timestamp'])
if (datetime.datetime.now() - cred_time) > datetime.timedelta(days=365):
logging.warning("Stale credentials detected (>1 year old)")
return credentials
def get_saved_credentials(self):
"""Retrieve saved credentials for all data sources."""
try:
# Decrypt the credentials file
encrypted_credentials = self.load_encrypted_credentials()
if not encrypted_credentials:
return {}
decrypted = self.decrypt_credentials(encrypted_credentials)
# Return credentials for both data sources
return {
"Dexcom": decrypted.get("Dexcom"),
"Nightscout": decrypted.get("Nightscout")
}
except Exception as e:
logging.error(f"Failed to retrieve saved credentials: {e}")
return {}
def save_credentials(self, data_source, credentials):
"""Save credentials for a specific data source."""
# Retrieve existing credentials
all_credentials = self.get_saved_credentials() or {}
# Update credentials for the specified data source
all_credentials[data_source] = credentials
# Encrypt and save all credentials
encrypted = self.encrypt_credentials(all_credentials)
# Use atomic write to prevent corruption
temp_path = self.credentials_file_path + '.tmp'
with open(temp_path, 'wb') as file:
file.write(encrypted)
# Atomic replace
os.replace(temp_path, self.credentials_file_path)
self.set_file_permissions(self.credentials_file_path)
logging.info(f"Saved credentials for {data_source}")
def load_settings(self):
try:
with open(self.settings_file_path, 'r') as settings_file:
settings = json.load(settings_file)
min_value = settings.get("min_value")
max_value = settings.get("max_value")
opacity = settings.get("opacity", 0.8)
self.prediction_enabled = settings.get("prediction_enabled", True)
self.unit = settings.get("unit", "mmol")
# Convert target range to current unit if needed
if min_value is not None and max_value is not None:
if self.unit == "mgdl":
# Convert from stored mmol to mg/dL
self.target_range = (min_value * 18.0, max_value * 18.0)
else:
self.target_range = (min_value, max_value)
if opacity is not None:
self.opacity = opacity
self.root.attributes('-alpha', self.opacity)
return settings
except FileNotFoundError:
# If settings file doesn't exist, keep default values
return None
def load_history(self):
"""Load prediction history from file."""
try:
if os.path.exists(self.history_file):
with open(self.history_file, 'r') as f:
history = json.load(f)
return [(datetime.datetime.fromisoformat(t), g) for t, g in history]
except Exception as e:
logging.error(f"History load error: {e}")
return None
def save_history(self):
"""Save prediction history with robust error handling."""
try:
history_data = [(t.isoformat(), g) for t, g in self.prediction_history]
# Use safe write method with Windows-specific fixes
success = self.safe_write_json(self.history_file, history_data)
if success:
logging.info(f"Saved {len(history_data)} history entries")
else:
logging.error("History save failed after retries")
except Exception as e:
logging.error(f"History save error: {e}")
# Emergency fallback to memory-only operation
self.prediction_history = self.prediction_history[-self.max_history:]
def authenticate_dexcom(self, username, password):
"""Authenticate with Dexcom and initialize session."""
try:
self.dexcom = Dexcom(username=username, password=password, region=self.region)
self.connection_retries = 0 # Reset retry counter on success
self.update_labels()
self.schedule_update()
# Schedule first update immediately
self.root.after(100, self.update_labels)
except Exception as e:
logging.error(f"Dexcom authentication failed: {e}")
messagebox.showerror("Authentication Error", "Failed to authenticate with Dexcom. Please check your credentials.")
def login(self):
if isinstance(self.username_entry, tk.Entry) and isinstance(self.password_entry, tk.Entry):
username = self.username_entry.get()
password = self.password_entry.get()
if username and password:
self.authenticate_dexcom(username, password)
self.save_credentials(username, password)
# Clear the Entry widgets after successful login
self.username_entry.delete(0, 'end')
self.password_entry.delete(0, 'end')
self.login_window.destroy()
else:
messagebox.showerror("Input Error", "Both username and password are required.")
def open_settings(self):
"""Open the settings window."""
# Check for file locks before opening settings
self.check_file_locks()
self.settings_window = tk.Toplevel(self.root)
self.settings_window.title("Settings")
self.settings_window.geometry("300x450") # Increased height for unit selection
# Set window icon
self.set_window_icon(self.settings_window)
# Target Range Settings
target_frame = ttk.LabelFrame(self.settings_window, text="Target Range")
target_frame.pack(padx=10, pady=5, fill="x")
ttk.Label(target_frame, text="Min:").grid(row=0, column=0, padx=5, pady=5)
self.new_min_entry = ttk.Entry(target_frame)
self.new_min_entry.grid(row=0, column=1, padx=5, pady=5)
self.new_min_entry.insert(0, str(self.target_range[0]))
ttk.Label(target_frame, text="Max:").grid(row=1, column=0, padx=5, pady=5)
self.new_max_entry = ttk.Entry(target_frame)
self.new_max_entry.grid(row=1, column=1, padx=5, pady=5)
self.new_max_entry.insert(0, str(self.target_range[1]))
# Unit Settings
unit_frame = ttk.LabelFrame(self.settings_window, text="Glucose Unit")
unit_frame.pack(padx=10, pady=5, fill="x")
self.unit_var = tk.StringVar(value=self.unit)
# Function to handle unit changes
def on_unit_change():
current_unit = self.unit_var.get()
try:
# Get current min/max values in current display units
current_min = float(self.new_min_entry.get())
current_max = float(self.new_max_entry.get())
# Convert to new units
new_min, new_max = self.convert_target_range(
current_min, current_max,
self.settings_window.current_display_unit,
current_unit
)
# Update entry fields with converted values
self.new_min_entry.delete(0, tk.END)
self.new_min_entry.insert(0, f"{new_min:.1f}")
self.new_max_entry.delete(0, tk.END)
self.new_max_entry.insert(0, f"{new_max:.1f}")
# Update current display unit
self.settings_window.current_display_unit = current_unit
except ValueError:
# Ignore if values aren't numbers
pass
# Create radio buttons with command
ttk.Radiobutton(unit_frame, text="mmol/L", variable=self.unit_var, value="mmol",
command=on_unit_change).pack(anchor="w", padx=5)
ttk.Radiobutton(unit_frame, text="mg/dL", variable=self.unit_var, value="mgdl",
command=on_unit_change).pack(anchor="w", padx=5)
# Store current display unit for conversion
self.settings_window.current_display_unit = self.unit
# Opacity Settings
opacity_frame = ttk.LabelFrame(self.settings_window, text="Opacity")
opacity_frame.pack(padx=10, pady=5, fill="x")
ttk.Label(opacity_frame, text="Opacity (0.0-1.0):").grid(row=0, column=0, padx=5, pady=5)
self.opacity_entry = ttk.Entry(opacity_frame)
self.opacity_entry.grid(row=0, column=1, padx=5, pady=5)
self.opacity_entry.insert(0, str(self.opacity))
# Prediction Settings
prediction_frame = ttk.LabelFrame(self.settings_window, text="Predictions")
prediction_frame.pack(padx=10, pady=5, fill="x")
self.prediction_var = tk.BooleanVar(value=self.prediction_enabled)
prediction_check = ttk.Checkbutton(
prediction_frame,
text="Enable Glucose Predictions",
variable=self.prediction_var
)
prediction_check.pack(padx=5, pady=5)
# Buttons Frame
button_frame = ttk.Frame(self.settings_window)
button_frame.pack(pady=10)
# Save Button
save_button = ttk.Button(button_frame, text="Save Settings", command=self.save_settings)
save_button.grid(row=0, column=0, padx=5)
# Manual Update Button
update_button = ttk.Button(button_frame, text="Update Now", command=self.update_labels)
update_button.grid(row=0, column=1, padx=5)
# Pin on Top Button
pin_text = "Unpin" if self.is_pinned else "Pin on Top"
self.pin_on_top_button = ttk.Button(button_frame, text=pin_text, command=self.toggle_pin_on_top)
self.pin_on_top_button.grid(row=1, column=0, padx=5, pady=5)
# Snooze Button
snooze_button = ttk.Button(button_frame, text="Snooze Alerts", command=self.snooze_notifications)
snooze_button.grid(row=1, column=1, padx=5, pady=5)
# Logout Button
logout_button = ttk.Button(button_frame, text="Logout", command=self.logout)
logout_button.grid(row=2, column=0, columnspan=2, pady=10)
# Add "Open Data Folder" button
open_dir_button = ttk.Button(button_frame, text="Open Data Folder", command=self.open_data_directory)
open_dir_button.grid(row=3, column=0, columnspan=2, pady=5)
def logout(self):
"""Log out the user and reset session variables."""
try:
# Delete credentials file
if os.path.exists(self.credentials_file_path):
try:
os.remove(self.credentials_file_path)
except PermissionError as pe:
logging.warning(f"Could not delete credentials file: {pe}")
with open(self.credentials_file_path, 'w') as f:
f.write("")
logging.info("Overwrote credentials file instead")
# Reset data source in config
config = self.load_config() or {}
config["data_source"] = "" # Clear data source
# Save the updated config
self.save_config(config)
# Reset session variables
self.data_source = ""
self.dexcom = None
self.nightscout_url = None
self.nightscout_api_secret = None
self.previous_glucose = None
# Reset UI immediately
self.reset_ui_after_logout()
# Show the login window
self.show_login_window()
except Exception as e:
logging.error(f"Unexpected error during logout: {e}")
self.show_login_window()
def reset_ui_after_logout(self):
"""Reset UI elements to default state after logout."""
self.glucose_value.set("--")
self.trend_label.configure(text="")
self.time_label.configure(text="")
self.delta_label.configure(text="")
self.prediction_label.configure(text="Prediction: --")
self.glucose_label.configure(fg="black")
self.last_reading_time = None
self.previous_glucose = None
self.prediction_history = []
def secure_cleanup(self):
"""Securely wipe sensitive data from memory on exit"""
try:
# Wipe Dexcom session if it exists
if hasattr(self, 'dexcom') and self.dexcom:
try:
# Try to properly log out if possible
if hasattr(self.dexcom, 'logout'):
self.dexcom.logout()
except Exception:
pass
self.dexcom = None
# Wipe Nightscout credentials
if hasattr(self, 'nightscout_api_secret') and self.nightscout_api_secret:
# Overwrite the secret with zeros
if isinstance(self.nightscout_api_secret, str):
# Convert to mutable bytearray to overwrite
secret_bytes = bytearray(self.nightscout_api_secret.encode('utf-8'))
for i in range(len(secret_bytes)):
secret_bytes[i] = 0
self.nightscout_api_secret = None
elif isinstance(self.nightscout_api_secret, bytes):
# Create a mutable copy and overwrite
secret_bytes = bytearray(self.nightscout_api_secret)
for i in range(len(secret_bytes)):
secret_bytes[i] = 0
self.nightscout_api_secret = None
# Wipe other sensitive attributes
sensitive_attrs = ['_credentials', 'OBFUSCATOR']
for attr in sensitive_attrs:
if hasattr(self, attr):
value = getattr(self, attr)
if isinstance(value, str):
# Create mutable version and overwrite
mutable = bytearray(value.encode('utf-8'))
for i in range(len(mutable)):
mutable[i] = 0
setattr(self, attr, None)
elif isinstance(value, bytes):
# Create mutable version and overwrite
mutable = bytearray(value)
for i in range(len(mutable)):
mutable[i] = 0
setattr(self, attr, None)
else:
setattr(self, attr, None)
logging.info("Securely cleaned memory")
except Exception as e:
logging.error(f"Secure cleanup failed: {e}")
def save_settings(self):
"""Save settings and handle unit changes."""
new_min = self.new_min_entry.get()
new_max = self.new_max_entry.get()
new_opacity = self.opacity_entry.get()
new_unit = self.unit_var.get()
try:
new_min = float(new_min)
new_max = float(new_max)
new_opacity = float(new_opacity)
if new_min < new_max and 0.0 <= new_opacity <= 1.0:
# Update current target range with new values (in current unit)
self.target_range = (new_min, new_max)
self.opacity = new_opacity
self.root.attributes('-alpha', self.opacity) # Apply the new opacity
self.is_pinned = self.root.wm_attributes("-topmost")
# Update prediction enabled state
prediction_was_enabled = self.prediction_enabled
self.prediction_enabled = self.prediction_var.get()
# Don't clear history when disabling predictions
# Just show/hide the UI element
if self.prediction_enabled:
self.prediction_label.pack(pady=5)
self.prediction_label.config(text="Prediction: --")
else:
self.prediction_label.pack_forget()
# Handle unit change
new_unit = self.unit_var.get()
if new_unit != self.unit:
self.unit = new_unit
self.prediction_history = [] # Clear prediction history on unit change
logging.info("Unit changed - cleared prediction history")
# Save to config
config = self.load_config() or {}
# Store target range in mmol format regardless of current unit
if new_unit == "mgdl":
stored_min = new_min / 18.0
stored_max = new_max / 18.0
else:
stored_min = new_min
stored_max = new_max
config["min_value"] = stored_min
config["max_value"] = stored_max
config["opacity"] = self.opacity
config["is_pinned"] = self.is_pinned
config["prediction_enabled"] = self.prediction_enabled
config["unit"] = new_unit
self.unit = new_unit # Update current unit
with open(self.settings_file_path, 'w') as settings_file:
json.dump(config, settings_file)
self.set_file_permissions(self.settings_file_path)
# Show or hide prediction label based on new setting
if self.prediction_enabled:
self.prediction_label.pack(pady=5)
self.prediction_label.config(text="Prediction: --")
else:
self.prediction_label.pack_forget()
self.settings_window.destroy()
else:
messagebox.showerror("Invalid Range or Opacity", "Ensure minimum value is less than maximum value and opacity is between 0.0 and 1.0.")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter valid numbers for the target range and opacity.")
def update_labels(self):
"""Update labels with current glucose and prediction data."""
try:
# Skip updates if no data source is set
if not self.data_source:
return
glucose_value = None
bg = None
color = "black"
try:
if self.data_source == "Dexcom" and self.dexcom:
# Add retry logic for connection issues
try:
bg = self.dexcom.get_current_glucose_reading()
self.connection_retries = 0 # Reset on success
except (requests.exceptions.ConnectionError, requests.exceptions.RequestException) as e:
self.connection_retries += 1
if self.connection_retries <= self.max_retries:
logging.warning(f"Connection error (retry {self.connection_retries}/{self.max_retries}): {e}")
time.sleep(2) # Wait before retrying
return self.update_labels() # Retry immediately
else:
logging.error(f"Max connection retries reached: {e}")
self.connection_retries = 0
raise
elif self.data_source == "Nightscout" and self.nightscout_url:
bg = self.get_nightscout_reading()
if bg is not None:
# Use correct attributes based on unit setting
if self.unit == "mgdl":
glucose_value = bg.value # For Dexcom, this is mg_dl
else:
# For mmol units, use mmol_l for Dexcom
if hasattr(bg, 'mmol_l'):
glucose_value = bg.mmol_l
else:
# Convert mg/dL to mmol/L for Nightscout
glucose_value = bg.value / 18.0
bg_datetime = bg.datetime.replace(tzinfo=None)
current_time = datetime.datetime.now()
# Only process if we have a new reading (>= 60 seconds since last)
if self.last_reading_time is None or (bg_datetime - self.last_reading_time).total_seconds() >= 60:
# Calculate delta only when we have a new reading
delta_value = 0.0 # Initialize with default value
if self.previous_glucose is not None:
delta_value = glucose_value - self.previous_glucose
# Format delta to one decimal point - safely
try:
delta_text = f"{delta_value:.1f}"
except (TypeError, ValueError):
delta_text = "N/A"
self.delta_label.configure(text=f"Delta: {delta_text}")
self.previous_glucose = glucose_value # Update previous glucose value
# Format glucose value to one decimal point
self.glucose_value.set(f"{glucose_value:.1f}")
# Check against target range using native units
if self.target_range[0] <= glucose_value <= self.target_range[1]:
color = "green"
elif glucose_value < self.target_range[0]:
color = "red"
self.trigger_notification(glucose_value) # Trigger low glucose notification
elif glucose_value > self.target_range[1]:
color = "orange"
self.trigger_notification(glucose_value) # Trigger high glucose notification
self.glucose_label.configure(fg=color)
if hasattr(bg, 'trend_description') and bg.trend_description is not None:
trend_arrow = self.get_trend_arrow(bg.trend_description)
self.trend_label.configure(text=trend_arrow)
else:
self.trend_label.configure(text="Trend N/A")
# Only update prediction history if prediction is enabled
if self.prediction_enabled:
self.update_prediction_history(bg_datetime, glucose_value)
# Handle predictions
if self.prediction_enabled:
prediction_result = self.predict_glucose()
if prediction_result[0] is not None: # Check if prediction is available
prediction_value, delta, trend, confidence = prediction_result
# Format prediction with delta and trend
prediction_text = f"Prediction (15min): {prediction_value:.1f} ({delta:+.1f} {trend})"
if confidence < 90: # Show confidence if below 90%
prediction_text += f" [{confidence}%]"
self.prediction_label.config(text=prediction_text)
else:
self.prediction_label.config(text="Prediction: --")
# Update last reading time after processing
self.last_reading_time = bg_datetime