-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
JuiceWatch.py
620 lines (435 loc) · 19.7 KB
/
JuiceWatch.py
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
import os
import sys
import atexit
import subprocess
import psutil
import time
import tkinter as tk
from tkinter import Tk, Label, Button, Entry, ttk, messagebox, PhotoImage, END
import pystray
from pystray import MenuItem as item
from PIL import Image, ImageDraw
import threading
import logging
# logging of anything
logging.basicConfig(filename='JuiceWatch.log', level=logging.DEBUG)
LOCK_FILE_PATH = "JuiceWatch.lock"
app_name = "JuiceWatch.exe"
def acquire_lock():
try:
# the lock file to avoid multiple runs of same program
with open(LOCK_FILE_PATH, "x") as lock_file:
# timestamp to the lock file
lock_file.write(f"{time.time()}\n")
return True
except FileExistsError:
return False
def release_lock():
# Remove the lock file
try:
os.remove(LOCK_FILE_PATH)
except FileNotFoundError:
pass # It's okay if the file is not found when releasing the lock
def update_lock_timestamp():
# write timestamp
with open(LOCK_FILE_PATH, "a") as lock_file:
lock_file.write(f"{time.time()}\n")
def check_lock_expiration():
try:
# Read the timestamp from the lock file
with open(LOCK_FILE_PATH, "r") as lock_file:
timestamp = float(lock_file.readline().strip())
# threshhold check
return time.time() - timestamp > 600 # 10 minutes in seconds
except FileNotFoundError:
return False
def check_if_already_running():
if not acquire_lock():
# logging.info("Another instance of the program is already running. Attempting to take control.")
show_notification(
"Another instance of the program is already running. Taking control.")
# Try to find the process ID of the existing instance
existing_instance_pid = find_existing_instance_pid()
if existing_instance_pid is not None:
try:
# Terminate the existing instance
existing_process = psutil.Process(existing_instance_pid)
existing_process.terminate()
logging.info("Terminated the existing instance.")
except Exception as e:
logging.info(f"Failed to terminate the existing instance: {e}")
# Release the lock since the program is exiting
release_lock()
# Wait for a short time to allow the existing instance to terminate
time.sleep(1)
# Try to acquire the lock again
if not acquire_lock():
logging.info("Could not take control. Exiting.")
sys.exit()
else:
logging.info("Successfully took control.")
show_notification("Successfully took control.")
os.remove(LOCK_FILE_PATH)
restart_program()
def restart_program():
python = sys.executable
script = os.path.abspath(__file__)
subprocess.Popen([python, script] + sys.argv[1:], creationflags=subprocess.CREATE_NEW_CONSOLE)
def find_existing_instance_pid():
current_pid = os.getpid()
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == f'{app_name}' and proc.info['pid'] != current_pid:
return proc.info['pid']
return None
def schedule_updates(func, interval):
while True:
time.sleep(interval)
func()
# Global variable to track the state of the charger connection
charger_connected_prev = None
#NOTIFICATION START
import platform
def show_notification(message):
if platform.system() == 'Windows':
show_windows_notification(message)
elif platform.system() in ['Darwin', 'Linux']:
show_mac_linux_notification(message)
else:
print("Unsupported operating system")
def show_windows_notification(message):
from win10toast import ToastNotifier
toaster = ToastNotifier()
icon_path = 'icon.ico'
if getattr(sys, 'frozen', False): # Check if running as a PyInstaller executable
icon_path = os.path.join(sys._MEIPASS, "icon.ico")
# Check if the icon file exists
if not os.path.exists(icon_path):
logging.info(f"Error: Icon file '{icon_path}' not found.")
return
toaster.show_toast("JuiceWatch 🩺🍂", message, duration=3, icon_path=icon_path)
def show_mac_linux_notification(message):
import notifypy
notification = notifypy.Notify()
icon_path = 'icon.ico' # the path to your .ico file
notification_audio = "notification-ring-2344.wav"
if getattr(sys, 'frozen', False): # Check if running as a PyInstaller executable
icon_path = os.path.join(sys._MEIPASS, "icon.ico")
# Check if the icon file exists
if not os.path.exists(icon_path):
# If the file doesn't exist, provide a default icon or handle the error accordingly
logging.info(f"Error: Icon file '{icon_path}' not found.")
return
notification.title = "JuiceWatch 🩺🍂"
notification.message = message
notification.icon = icon_path
notification.audio = notification_audio
notification.send(block=False)
def check_battery_and_update_gui():
global charger_connected_prev
while True:
percent, power_plugged = check_battery_status()
if percent is not None and power_plugged is not None:
if not power_plugged:
handle_unplugged_scenario(percent, power_plugged)
else:
if charger_connected_prev is not None and not charger_connected_prev:
show_notification("Charger Connected!")
charger_connected_prev = power_plugged
time.sleep(2)
def handle_unplugged_scenario(percent, power_plugged):
show_notification(f"Charger Unplugged! Battery: {percent}%")
elapsed_time = 0
while not power_plugged and elapsed_time < turn_off_delay:
time.sleep(10)
elapsed_time += 10
percent, power_plugged = check_battery_status()
if power_plugged:
show_notification("Charger reconnected. Resetting hibernate timer.")
elapsed_time = 0
if not power_plugged and elapsed_time >= turn_off_delay:
hibernate_with_confirmation()
logging.info("Laptop would be turned off now.")
show_notification("hibernate canceled.")
elapsed_time = 0
def check_battery_status():
try:
battery = psutil.sensors_battery()
if battery is not None:
percent = battery.percent
power_plugged = battery.power_plugged
return percent, power_plugged
else:
logging.info("No battery found.")
return 0, None
except AttributeError as e:
logging.info(f"Error accessing battery attributes: {e}")
return 0, None
except Exception as e:
logging.info(f"Error getting battery status: {e}")
return 0, None
def hibernate_with_confirmation():
show_notification(
"Laptop will hibernate in 1 minute. Click here to Cancel.")
cancel_hibernate = messagebox.askyesno(
"Cancel hibernate", "Do you want to cancel the hibernate?")
if cancel_hibernate:
cancel_hibernate_command()
else:
hibernate_system()
# check platform user is currently on
def cancel_hibernate_command():
platform = sys.platform
if platform.startswith('win'):
os.system("shutdown /a")
elif platform.startswith('linux'):
os.system("sudo systemctl stop sleep.target")
elif platform.startswith('darwin'):
os.system("sudo pmset -c sleep 0")
os.system("sudo pmset -a hibernatemode 0")
def hibernate_system():
platform = sys.platform
if platform.startswith('win'):
os.system("shutdown /h")
elif platform.startswith('linux'):
os.system("systemctl hibernate")
elif platform.startswith('darwin'):
os.system("pmset -a hibernatemode 25 && pmset -a standby 1 && hibernate -h now")
def update_settings():
global notification_entry, turnoff_entry, notification_label, turnoff_label
global notification_interval, turn_off_delay, current_notification_label, current_turnoff_label
try:
notification_interval = int(notification_entry.get()) * 60
turn_off_delay = int(turnoff_entry.get()) * 60
notification_label.config(text=f"Notification Interval: {notification_interval} seconds")
turnoff_label.config(text=f"Turn-off Delay: {turn_off_delay} seconds")
# Update the current labels
current_notification_label.config(text=f"Current Notification Interval: {notification_interval // 60} minutes")
current_turnoff_label.config(text=f"Current Turn-off Delay: {turn_off_delay // 60} minutes")
except Exception as e:
logging.info(f"Error updating settings: {e}")
def create_info_notification():
message = "This Program helps check when laptop charger disconnected🙄,if the user doesn't connect, it shuts down the laptop to save the user's battery."
show_notification(message)
def opening_settings():
message = "Settings..."
show_notification(message)
def opening_about():
message = "About.."
show_notification(message)
notification_entry = None
turnoff_entry = None
about_tab = None
current_notification_label = None
current_turnoff_label = None
menu_icon = None
def open_settings_window():
global notification_entry, turnoff_entry, notification_label, turnoff_label, current_notification_label, current_turnoff_label
settings_window = tk.Tk()
settings_window.title("Juice Watch Settings")
if os.path.exists(icon_path):
settings_window.iconbitmap(icon_path)
# notebook to hold the tabs
notebook = ttk.Notebook(settings_window)
notebook.grid(row=0, column=0, padx=10, pady=10, sticky="ew")
# first tab for settings
settings_tab = ttk.Frame(notebook)
notebook.add(settings_tab, text="Settings")
# Additional label for the message
message_label = ttk.Label(settings_tab, text="Enter The time in minutes")
message_label.grid(row=0, column=0, pady=(10, 5), sticky="w")
notification_frame = ttk.Frame(settings_tab, padding="10 5 10 5")
notification_frame.grid(row=1, column=0, sticky="ew")
notification_label = ttk.Label(notification_frame, text="Notification Interval:")
notification_label.grid(row=0, column=0, pady=10, sticky="e")
notification_entry = ttk.Entry(notification_frame)
notification_entry.insert(tk.END, "1")
notification_entry.grid(row=0, column=1, padx=(0, 10), sticky="ew")
# Label to display the current notification interval
current_notification_label = ttk.Label(notification_frame, text="")
current_notification_label.grid(row=1, column=1, padx=(0, 10), sticky="ew")
turnoff_frame = ttk.Frame(settings_tab, padding="10 5 10 5")
turnoff_frame.grid(row=2, column=0, sticky="ew")
turnoff_label = ttk.Label(turnoff_frame, text="Turn-off Delay(mins):")
turnoff_label.grid(row=0, column=0, sticky="w")
turnoff_entry = ttk.Entry(turnoff_frame)
turnoff_entry.insert(tk.END, "2")
turnoff_entry.grid(row=0, column=1, padx=(0, 10), sticky="ew")
# Label to display the current turn-off delay
current_turnoff_label = ttk.Label(turnoff_frame, text="")
current_turnoff_label.grid(row=1, column=1, padx=(0, 10), sticky="ew")
button_frame = ttk.Frame(settings_tab, padding="10 5 10 5")
button_frame.grid(row=3, column=0, sticky="ew")
update_button = ttk.Button(button_frame, text="Update Settings", command=update_settings)
update_button.grid(row=0, column=0, padx=15)
hibernate_button = ttk.Button(button_frame, text="Hibernate", command=hibernate_with_confirmation)
hibernate_button.grid(row=0, column=1, padx=10)
close_button = ttk.Button(button_frame, text="Close program", command=lambda: exit_program(menu_icon, root))
close_button.grid(row=0, column=2, padx=15)
# Display current settings values
display_current_settings_values()
# second tab for program information
about_tab = ttk.Frame(notebook)
notebook.add(about_tab, text="About Program")
about_label = ttk.Label(
about_tab, text="JuiceWatch\nVersion 1.0\n© 2024 Trakexcel Agency\n@Uzitrake | inboxsgk")
about_label.pack(padx=20, pady=14)
explanation_text = (
"JuiceWatch is a battery monitoring program designed to provide real-time insights\n"
"into your laptop's battery status. Here's how you can use JuiceWatch:\n\n"
"Usage:\n"
"1. Launch JuiceWatch .You can start it from system tray 👨💻\n"
"2. The program will continuously monitor your laptop's battery status.\n"
"3. Receive notifications for charger connection and disconnection events.\n"
"4. Customize notification intervals and turn-off delays to suit your preferences.\n"
"5. Optionally, manually initiate a hibernate using the 'hibernate' button.\n\n"
"JuiceWatch helps you conserve battery life by taking proactive actions when your\n"
"laptop is not connected to the charger. Stay informed and in control of your power usage!"
)
explanation_label = ttk.Label(
about_tab, text=explanation_text, anchor="w", justify="left")
explanation_label.pack(padx=20, pady=20, fill="both")
# Handle window closure event
settings_window.protocol("WM_DELETE_WINDOW", lambda: on_settings_window_close(settings_window))
def display_current_settings_values():
# Get the current values from the entry fields
current_notification_value = notification_entry.get()
current_turnoff_value = turnoff_entry.get()
# Update the labels to display the current values
current_notification_label.config(text=f"Current Notification Interval: {current_notification_value} minutes")
current_turnoff_label.config(text=f"Current Turn-off Delay: {current_turnoff_value} minutes")
# settings_window.geometry("400x200")
def on_settings_window_close(settings_window):
settings_window.iconify() # Minimize to the taskbar
settings_window.withdraw() # Hide the window from the taskbar
release_lock()
if os.path.exists(LOCK_FILE_PATH):
try:
os.remove(LOCK_FILE_PATH)
except Exception as e:
logging.info(f"Error while removing lock file: {e}")
restart_program()
def minimize_to_tray(settings_window, menu_icon):
settings_window.iconify() # Minimize to the system tray
settings_window.withdraw()
menu_icon.visible = True
def maximize_from_tray(root, menu_icon):
# root.deiconify()
menu_icon.visible = False
def on_exit(icon, item):
root.iconify()
icon.stop()
def on_minimize(root, icon, event):
root.iconify() # Minimize the window
root.withdraw() # Hide the window from the taskbar
icon.visible = True # Make the system tray icon visible
def exit_smooth(icon, item):
response = messagebox.askyesno(
"Exit Program", "Are you sure you want to exit?")
if response:
icon.stop()
release_lock()
root.destroy()
os._exit(0)
from PIL import ImageTk
def exit_program(icon, root):
#custom messagebox
messagebox_window = tk.Toplevel(root)
messagebox_window.title("Exit Program")
icon_filename = "icon.png"
# Check if running as a PyInstaller executable or using a compiled package
if getattr(sys, 'frozen', False):
# If frozen, get the path to the resource using the MEIPASS attribute
icon_path = os.path.join(sys._MEIPASS, icon_filename)
else:
# If running the Python script directly, assume the icon is in the same directory
icon_path = icon_filename
logo_image = Image.open(icon_path)
logo_image = logo_image.resize((60, 60), Image.BILINEAR)
logo_photo = ImageTk.PhotoImage(logo_image)
logo_label = ttk.Label(messagebox_window, image=logo_photo)
logo_label.image = logo_photo # Keep a reference to prevent garbage collection
logo_label.pack(pady=10)
# Add the message and Yes/No buttons
message_label = ttk.Label(messagebox_window, text="Are you sure you want to exit?")
message_label.pack(pady=5)
yes_button = ttk.Button(messagebox_window, text="Yes", command=lambda: handle_exit(icon, root))
yes_button.pack(side="left", padx=10)
no_button = ttk.Button(messagebox_window, text="No", command=messagebox_window.destroy)
no_button.pack(side="right", padx=10)
def handle_exit(icon, root):
icon.stop()
release_lock()
root.destroy()
os._exit(0)
def show_notification_thread(message):
notification_thread = threading.Thread(
target=show_notification, args=(message,))
notification_thread.start()
def show_initial_notification():
show_notification_thread("JuiceWatch is running. Click the icon in the system tray to access the program.")
def release_lock_at_exit():
# Attempt to acquire the lock
acquired = acquire_lock()
if acquired:
# Release the lock only if it was successfully acquired
release_lock()
else:
logging.info("Lock was not acquired. Another instance is already running.")
def initialize_icons():
global notification_icon, turnoff_icon, icon_path
turnoff_icon = 'turnoff.png' # the path to your .ico file
if getattr(sys, 'frozen', False): # Check if running as a PyInstaller executable
turnoff_icon = os.path.join(sys._MEIPASS, "turnoff.png")
notification_icon = 'notify.png' # the path to your .ico file
if getattr(sys, 'frozen', False): # Check if running as a PyInstaller executable
notification_icon = os.path.join(sys._MEIPASS, "notify.png")
icon_path = 'icon.ico' # the path to your .ico file
if getattr(sys, 'frozen', False): # Check if running as a PyInstaller executable
icon_path = os.path.join(sys._MEIPASS, "icon.ico")
if __name__ == "__main__":
check_if_already_running()
# Check if the lock has expired
if check_lock_expiration():
logging.info("Lock has expired. Exiting.")
# show_notification("Lock has expired. Exiting.")
sys.exit()
notification_interval = 0.5 * 60
turn_off_delay = 1 * 60
# Initialize charger_connected_prev based on the initial battery status
_, charger_connected_prev = check_battery_status()
battery_thread = threading.Thread(
target=check_battery_and_update_gui, daemon=True)
battery_thread.start()
root = Tk()
root.withdraw()
root.resizable(False, False) # Disable resizing in both x and y directions
initialize_icons()
menu = [
item('Settings', lambda icon, item: (
opening_settings(), open_settings_window())),
item('Mini info', lambda icon, item: show_notification_thread(
"This Program helps check when laptop charger disconnected🪫🩺, if the user doesn't connect, it shuts down the laptop to save the user's battery.")),
item('Program Info', lambda icon, item: (opening_about(), open_settings_window())),
item('Exit Program', lambda icon, item: exit_smooth(menu_icon, item)),
]
icon_path = 'icon.ico' # the path to your .ico file
if getattr(sys, 'frozen', False): # Check if running as a PyInstaller executable
icon_path = os.path.join(sys._MEIPASS, "icon.ico")
image = Image.open(icon_path)
menu_icon = pystray.Icon("Juice Watch",
image, "Juice Watch", menu)
menu_icon.visible = False
#show notification its in the notification panel
show_initial_notification()
root.protocol("WM_DELETE_WINDOW",
lambda: minimize_to_tray(root, menu_icon))
root.bind("<Unmap>", lambda event: on_minimize(root, menu_icon, event))
atexit.register(release_lock_at_exit)
# thread to update the lock timestamp every 10 minutes
lock_update_thread = threading.Thread(
target=lambda: schedule_updates(update_lock_timestamp, 600), daemon=True)
lock_update_thread.start()
menu_icon.run()
root.mainloop()
release_lock()
## The start