Merge pull request #16 from JeffCurless/argon40_scriptupdate_01_10_2026

Latest scripts and such from argon40.
This commit is contained in:
Jeff Curless
2026-01-10 19:07:55 -05:00
committed by GitHub
6 changed files with 511 additions and 310 deletions

View File

@@ -98,8 +98,14 @@ then
sudo systemctl stop argonupsrtcd.service sudo systemctl stop argonupsrtcd.service
sudo systemctl disable argonupsrtcd.service sudo systemctl disable argonupsrtcd.service
sudo systemctl --global stop argononeupsduser.service for tmpuser in `awk -F: '{ if ($3 >= 1000) print $1 }' /etc/passwd`
sudo systemctl --global disable argononeupsduser.service do
if [ "$tmpuser" != "nobody" ]
then
sudo -u "$tmpuser" systemctl --user stop argononeupsduser.service
sudo -u "$tmpuser" systemctl --user disable argononeupsduser.service
fi
done
# Remove files # Remove files
sudo rm /lib/systemd/system/argononeupsd.service sudo rm /lib/systemd/system/argononeupsd.service

View File

@@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
VERSIONINFO="2509004" VERSIONINFO="2601003"
echo "Version $VERSIONINFO" echo "Version $VERSIONINFO"
if [ -z "$1" ] if [ -z "$1" ]

View File

@@ -11,10 +11,8 @@
from evdev import InputDevice, categorize, ecodes, list_devices from evdev import InputDevice, categorize, ecodes, list_devices
from select import select from select import select
import subprocess import subprocess
import sys import sys
import os import os
import time import time
@@ -26,12 +24,22 @@ from queue import Queue
UPS_LOGFILE="/dev/shm/upslog.txt" UPS_LOGFILE="/dev/shm/upslog.txt"
KEYBOARD_LOCKFILE="/dev/shm/argononeupkeyboardlock.txt" KEYBOARD_LOCKFILE="/dev/shm/argononeupkeyboardlock.txt"
KEYCODE_BRIGHTNESSUP = "KEY_BRIGHTNESSUP"
KEYCODE_BRIGHTNESSDOWN = "KEY_BRIGHTNESSDOWN"
KEYCODE_VOLUMEUP = "KEY_VOLUMEUP"
KEYCODE_VOLUMEDOWN = "KEY_VOLUMEDOWN"
KEYCODE_PAUSE = "KEY_PAUSE"
KEYCODE_MUTE = "KEY_MUTE"
################### ###################
# Utilty Functions # Utilty Functions
################### ###################
# Debug Logger # Debug Logger
def debuglog(typestr, logstr): def debuglog(typestr, logstr):
#return
try: try:
DEBUGFILE="/dev/shm/argononeupkeyboarddebuglog.txt" DEBUGFILE="/dev/shm/argononeupkeyboarddebuglog.txt"
tmpstrpadding = " " tmpstrpadding = " "
@@ -43,19 +51,19 @@ def debuglog(typestr, logstr):
def runcmdlist(key, cmdlist): def runcmdlist(key, cmdlist):
try: try:
result = subprocess.run(cmdlist, cmdresult = subprocess.run(cmdlist,
capture_output=True, capture_output=True,
text=True, text=True,
check=True check=True
) )
#debuglog(key+"-result-output",str(result.stdout)) #debuglog(key+"-result-output",str(cmdresult.stdout))
if result.stderr: if cmdresult.stderr:
debuglog(key+"-result-error",str(result.stderr)) debuglog(key+"-result-error",str(cmdresult.stderr))
#debuglog(key+"-result-code",str(result.returncode)) #debuglog(key+"-result-code",str(cmdresult.returncode))
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
debuglog(key+"-error-output",str(e.stdout)) debuglog(key+"-error-output",str(e.stdout))
if result.stderr: if e.stderr:
debuglog(key+"-error-error",str(e.stderr)) debuglog(key+"-error-error",str(e.stderr))
debuglog(key+"-error-code",str(e.returncode)) debuglog(key+"-error-code",str(e.returncode))
except FileNotFoundError: except FileNotFoundError:
@@ -67,32 +75,33 @@ def runcmdlist(key, cmdlist):
debuglog(key+"-error-other", "Other Error") debuglog(key+"-error-other", "Other Error")
def createlockfile(fname): def createlockfile(fname):
try: # try:
if os.path.isfile(fname): # if os.path.isfile(fname):
return True # return True
except Exception as checklockerror: # except Exception as checklockerror:
try: # try:
debuglog("keyboard-lock-error", str(checklockerror)) # debuglog("keyboard-lock-error", str(checklockerror))
except: # except:
debuglog("keyboard-lock-error", "Error Checking Lock File") # debuglog("keyboard-lock-error", "Error Checking Lock File")
try: # try:
with open(fname, "w") as txt_file: # with open(fname, "w") as txt_file:
txt_file.write(time.asctime(time.localtime(time.time()))+"\n") # txt_file.write(time.asctime(time.localtime(time.time()))+"\n")
except Exception as lockerror: # except Exception as lockerror:
try: # try:
debuglog("keyboard-lock-error", str(lockerror)) # debuglog("keyboard-lock-error", str(lockerror))
except: # except:
debuglog("keyboard-lock-error", "Error Creating Lock File") # debuglog("keyboard-lock-error", "Error Creating Lock File")
return False return False
def deletelockfile(fname): def deletelockfile(fname):
try: # try:
os.remove(fname) # os.remove(fname)
except Exception as lockerror: # except Exception as lockerror:
try: # try:
debuglog("keyboard-lock-error", str(lockerror)) # debuglog("keyboard-lock-error", str(lockerror))
except: # except:
debuglog("keyboard-lock-error", "Error Removing Lock File") # debuglog("keyboard-lock-error", "Error Removing Lock File")
return True
# System Notifcation # System Notifcation
@@ -147,9 +156,13 @@ def keyboardevent_getdevicepaths():
# Keyboard has EV_KEY (key) and EV_REP (autorepeat) # Keyboard has EV_KEY (key) and EV_REP (autorepeat)
if ecodes.KEY_BRIGHTNESSDOWN in keyeventlist and ecodes.KEY_BRIGHTNESSDOWN in keyeventlist: if ecodes.KEY_BRIGHTNESSDOWN in keyeventlist and ecodes.KEY_BRIGHTNESSDOWN in keyeventlist:
outlist.append(path) outlist.append(path)
#debuglog("keyboard-device-keys", path)
#debuglog("keyboard-device-keys", str(keyeventlist))
elif ecodes.KEY_F2 in keyeventlist and ecodes.KEY_F3 in keyeventlist: elif ecodes.KEY_F2 in keyeventlist and ecodes.KEY_F3 in keyeventlist:
# Keyboards with FN key sometimes do not include KEY_BRIGHTNESS in declaration # Keyboards with FN key sometimes do not include KEY_BRIGHTNESS in declaration
outlist.append(path) outlist.append(path)
#debuglog("keyboard-device-keys", path)
#debuglog("keyboard-device-keys", str(keyeventlist))
tmpdevice.close() tmpdevice.close()
except: except:
pass pass
@@ -169,11 +182,32 @@ def keyboardevent_devicechanged(curlist, newlist):
pass pass
return False return False
def keyboardevent_getbrigthnessinfo(defaultlevel=50): def keyboardevent_getbrigthnesstoolid():
toolid = 0
try:
output = subprocess.check_output(["ddcutil", "--version"], text=True, stderr=subprocess.DEVNULL)
lines = output.splitlines()
if len(lines) > 0:
tmpline = lines[0].strip()
toolid = int(tmpline.split(" ")[1].split(".")[0])
except Exception as einit:
try:
debuglog("keyboard-brightness-tool-error", str(einit))
except:
debuglog("keyboard-brightness-tool-error", "Error getting tool id value")
debuglog("keyboard-brightness-tool", toolid)
return toolid
def keyboardevent_getbrigthnessinfo(toolid, defaultlevel=50):
level = defaultlevel level = defaultlevel
try: try:
# VCP code x10(Brightness ): current value = 90, max value = 100 # VCP code x10(Brightness ): current value = 90, max value = 100
output = subprocess.check_output(["ddcutil", "getvcp", "10"], text=True, stderr=subprocess.DEVNULL) if toolid > 1:
# Disabled dynamic sleep "--disable-dynamic-sleep", "--sleep-multiplier", "0.1"
output = subprocess.check_output(["ddcutil", "--disable-dynamic-sleep", "--sleep-multiplier", "0.1", "getvcp", "10"], text=True, stderr=subprocess.DEVNULL)
else:
output = subprocess.check_output(["ddcutil", "--sleep-multiplier", "0.1", "getvcp", "10"], text=True, stderr=subprocess.DEVNULL)
debuglog("keyboard-brightness-info", output) debuglog("keyboard-brightness-info", output)
level = int(output.split(":")[-1].split(",")[0].split("=")[-1].strip()) level = int(output.split(":")[-1].split(",")[0].split("=")[-1].strip())
except Exception as einit: except Exception as einit:
@@ -188,24 +222,29 @@ def keyboardevent_getbrigthnessinfo(defaultlevel=50):
} }
def keyboardevent_adjustbrigthness(baselevel, adjustval=5): def keyboardevent_adjustbrigthness(toolid, baselevel, adjustval=5):
curlevel = baselevel curlevel = baselevel
if adjustval == 0: if adjustval == 0:
return { return {
"level": baselevel "level": baselevel
} }
try: # Moved reading because ddcutil has delay
tmpobj = keyboardevent_getbrigthnessinfo(curlevel) # try:
curlevel = tmpobj["level"] # tmpobj = keyboardevent_getbrigthnessinfo(toolid, curlevel)
except Exception: # curlevel = tmpobj["level"]
pass # except Exception:
# pass
tmpval = max(10, min(100, curlevel + adjustval)) tmpval = max(10, min(100, curlevel + adjustval))
if tmpval != curlevel: if tmpval != curlevel:
try: try:
debuglog("keyboard-brightness", str(curlevel)+"% to "+str(tmpval)+"%") debuglog("keyboard-brightness", str(curlevel)+"% to "+str(tmpval)+"%")
runcmdlist("brightness", ["ddcutil", "setvcp", "10", str(tmpval)]) if toolid > 1:
# Disabled dynamic sleep "--disable-dynamic-sleep", "--sleep-multiplier", "0.1"
runcmdlist("brightness", ["ddcutil", "--disable-dynamic-sleep", "--sleep-multiplier", "0.1", "setvcp", "10", str(tmpval)])
else:
runcmdlist("brightness", ["ddcutil", "--sleep-multiplier", "0.1", "setvcp", "10", str(tmpval)])
notifymessage("Brightness: "+str(tmpval)+"%", False) notifymessage("Brightness: "+str(tmpval)+"%", False)
except Exception as adjusterr: except Exception as adjusterr:
try: try:
@@ -217,7 +256,7 @@ def keyboardevent_adjustbrigthness(baselevel, adjustval=5):
} }
# DEBUG: Checking # DEBUG: Checking
#keyboardevent_getbrigthnessinfo(tmpval) #keyboardevent_getbrigthnessinfo(toolid, tmpval)
return { return {
"level": tmpval "level": tmpval
} }
@@ -351,12 +390,12 @@ def keyboardevent_adjustvolume(baselevel, basemuted, adjustval=5):
"muted": basemuted "muted": basemuted
} }
try: # try:
tmpobj = keyboardevent_getvolumeinfo(deviceidstr, curlevel, curmuted) # tmpobj = keyboardevent_getvolumeinfo(deviceidstr, curlevel, curmuted)
curlevel = tmpobj["level"] # curlevel = tmpobj["level"]
curmuted = tmpobj["muted"] # curmuted = tmpobj["muted"]
except Exception: # except Exception:
pass # pass
tmpmuted = curmuted tmpmuted = curmuted
if adjustval == 0: if adjustval == 0:
@@ -413,21 +452,197 @@ def keyboardevent_adjustvolume(baselevel, basemuted, adjustval=5):
"muted": tmpmuted "muted": tmpmuted
} }
def keyboard_getlayoutfieldvalue(tmpval):
debuglog("keyboard-layout-lang", tmpval)
if "us" in tmpval:
debuglog("keyboard-layout-langout", "us")
return "us"
debuglog("keyboard-layout-langout", "gb")
return "gb" # uk, gb, etc
#return tmpval
def keyboard_getdevicefw(kbdevice):
# info: vendor 0x6080=24704, product 0x8062=32866
try:
if kbdevice.info.vendor == 24704 and kbdevice.info.product == 32866:
# Special HID
return "314"
except Exception as infoerr:
pass
return ""
def keyboardevent_check(readq): def keyboardevemt_keyhandler(readq):
ADJUSTTYPE_NONE=0 ADJUSTTYPE_NONE=0
ADJUSTTYPE_BRIGHTNESS=1 ADJUSTTYPE_BRIGHTNESS=1
ADJUSTTYPE_VOLUME=2 ADJUSTTYPE_VOLUME=2
ADJUSTTYPE_MUTE=3 ADJUSTTYPE_MUTE=3
ADJUSTTYPE_BATTERYINFO=4 ADJUSTTYPE_BATTERYINFO=4
DATAREFRESHINTERVALSEC = 10
PRESSWAITINTERVALSEC = 0.5
FIRSTHOLDINTERVALSEC = 0.5
HOLDWAITINTERVALSEC = 0.5
# Get current levels
volumetime = time.time()
curvolumemuted = 0
curvolume = 50
brightnesstime = volumetime
curbrightness = 50
brightnesstoolid = 0
try:
brightnesstoolid = keyboardevent_getbrigthnesstoolid()
except Exception:
brightnesstoolid = 0
pass
try:
tmpobj = keyboardevent_getbrigthnessinfo(brightnesstoolid)
curbrightness = tmpobj["level"]
except Exception:
pass
try:
tmpobj = keyboardevent_getvolumeinfo()
curvolumemuted = tmpobj["muted"]
curvolume = tmpobj["level"]
except Exception:
pass
while True:
try:
tmpkeymode = 0
tmpkeycode = ""
adjustval = 0
adjusttype = ADJUSTTYPE_NONE
tmpcode = readq.get() # Blocking
try:
codeelements = tmpcode.split("+")
if len(codeelements) == 2:
if codeelements[0] == "PRESS":
tmpkeymode = 1
else:
tmpkeymode = 2
tmpkeycode = codeelements[1]
elif tmpcode == "EXIT":
readq.task_done()
return
except Exception:
tmpkeycode = ""
tmpkeymode = 0
pass
tmptime = time.time()
if tmpkeycode in [KEYCODE_BRIGHTNESSDOWN, KEYCODE_BRIGHTNESSUP]:
if tmpkeymode == 1 and tmptime - brightnesstime > DATAREFRESHINTERVALSEC:
# Do not update value during hold
try:
tmpobj = keyboardevent_getbrigthnessinfo(brightnesstoolid)
curbrightness = tmpobj["level"]
except Exception:
pass
adjusttype = ADJUSTTYPE_BRIGHTNESS
if tmpkeycode == KEYCODE_BRIGHTNESSDOWN:
adjustval = -5*tmpkeymode
else:
adjustval = 5*tmpkeymode
brightnesstime = tmptime
elif tmpkeycode in [KEYCODE_MUTE, KEYCODE_VOLUMEDOWN, KEYCODE_VOLUMEUP]:
if tmpkeymode == 1 and tmptime - volumetime > DATAREFRESHINTERVALSEC and tmpkeymode == 1:
# Do not update value during hold
try:
tmpobj = keyboardevent_getvolumeinfo()
curvolumemuted = tmpobj["muted"]
curvolume = tmpobj["level"]
except Exception:
pass
if tmpkeycode == KEYCODE_MUTE:
adjusttype = ADJUSTTYPE_MUTE
adjustval = 0
else:
adjusttype = ADJUSTTYPE_VOLUME
if tmpkeycode == KEYCODE_VOLUMEDOWN:
adjustval = -5*tmpkeymode
else:
adjustval = 5*tmpkeymode
volumetime = tmptime
elif tmpkeycode == KEYCODE_PAUSE:
adjusttype = ADJUSTTYPE_BATTERYINFO
else:
readq.task_done()
continue
try:
tmplockfilea = KEYBOARD_LOCKFILE+".a"
if createlockfile(tmplockfilea) == False:
# Debug ONLY
# if tmpkeymode == 1:
# debuglog("keyboard-event", "Press Key Code: "+str(tmpkeycode))
# else:
# debuglog("keyboard-event", "Hold Key Code: "+str(tmpkeycode))
if adjusttype == ADJUSTTYPE_BRIGHTNESS:
try:
tmpobj = keyboardevent_adjustbrigthness(brightnesstoolid, curbrightness, adjustval)
curbrightness = tmpobj["level"]
except Exception as brightnesserr:
try:
debuglog("keyboard-brightnessother-error", str(brightnesserr))
except:
debuglog("keyboard-brightnessother-error", "Error adjusting value")
pass
elif adjusttype == ADJUSTTYPE_VOLUME or adjusttype == ADJUSTTYPE_MUTE:
try:
tmpobj = keyboardevent_adjustvolume(curvolume, curvolumemuted, adjustval)
curvolumemuted = tmpobj["muted"]
curvolume = tmpobj["level"]
except Exception as volumeerr:
try:
debuglog("keyboard-volumeother-error", str(volumeerr))
except:
debuglog("keyboard-volumeother-error", "Error adjusting value")
pass
elif adjusttype == ADJUSTTYPE_BATTERYINFO:
outobj = battery_loadlogdata()
try:
notifymessage(outobj["power"], False)
except:
pass
deletelockfile(tmplockfilea)
except Exception as keyhandlererr:
try:
debuglog("keyboard-handlererror", str(keyhandleerr))
except:
debuglog("keyboard-handlererror", "Error")
readq.task_done()
except Exception as mainerr:
time.sleep(10)
# While True
def keyboardevent_monitor(writeq):
READTIMEOUTSECS = 1.0 READTIMEOUTSECS = 1.0
PRESSWAITINTERVALSEC = 2 FIRSTHOLDINTERVALSEC = 0.5
HOLDWAITINTERVALSEC = 1 HOLDWAITINTERVALSEC = 0.5
while True: while True:
try: try:
keypresstimestamp = {} keypresstimestamp = {}
@@ -436,6 +651,7 @@ def keyboardevent_check(readq):
devicelist = [] devicelist = []
devicefdlist = [] devicefdlist = []
devicepathlist = keyboardevent_getdevicepaths() devicepathlist = keyboardevent_getdevicepaths()
devicefwlist = []
deviceidx = 0 deviceidx = 0
while deviceidx < len(devicepathlist): while deviceidx < len(devicepathlist):
@@ -443,33 +659,16 @@ def keyboardevent_check(readq):
tmpdevice = InputDevice(devicepathlist[deviceidx]) tmpdevice = InputDevice(devicepathlist[deviceidx])
devicelist.append(tmpdevice) devicelist.append(tmpdevice)
devicefdlist.append(tmpdevice.fd) devicefdlist.append(tmpdevice.fd)
devicefwlist.append(keyboard_getdevicefw(tmpdevice))
#debuglog("keyboard-device-info", devicepathlist[deviceidx])
#debuglog("keyboard-device-info", str(tmpdevice.info))
except Exception as deverr: except Exception as deverr:
try: try:
debuglog("keyboard-deviceerror-", str(deverr)+ " "+ devicepathlist[deviceidx]) debuglog("keyboard-deviceerror", str(deverr)+ " "+ devicepathlist[deviceidx])
except: except:
debuglog("keyboard-deviceerror", "Error "+devicepathlist[deviceidx]) debuglog("keyboard-deviceerror", "Error "+devicepathlist[deviceidx])
deviceidx = deviceidx + 1 deviceidx = deviceidx + 1
# Get current levels
curvolumemuted = 0
curvolume = 50
curbrightness = 50
try:
tmpobj = keyboardevent_getbrigthnessinfo()
curbrightness = tmpobj["level"]
except Exception:
pass
try:
tmpobj = keyboardevent_getvolumeinfo()
curvolumemuted = tmpobj["muted"]
curvolume = tmpobj["level"]
except Exception:
pass
try: try:
debuglog("keyboard-update", str(len(devicefdlist))+" Devices") debuglog("keyboard-update", str(len(devicefdlist))+" Devices")
while len(devicefdlist) > 0: while len(devicefdlist) > 0:
@@ -478,9 +677,11 @@ def keyboardevent_check(readq):
r, w, x = select(devicefdlist, [], [], READTIMEOUTSECS) r, w, x = select(devicefdlist, [], [], READTIMEOUTSECS)
for fd in r: for fd in r:
found = False found = False
curdevicefw = ""
deviceidx = 0 deviceidx = 0
while deviceidx < len(devicefdlist): while deviceidx < len(devicefdlist):
if devicefdlist[deviceidx] == fd: if devicefdlist[deviceidx] == fd:
curdevicefw = devicefwlist[deviceidx]
found = True found = True
break break
deviceidx = deviceidx + 1 deviceidx = deviceidx + 1
@@ -493,131 +694,69 @@ def keyboardevent_check(readq):
if event.type == ecodes.EV_KEY: if event.type == ecodes.EV_KEY:
key_event = categorize(event) key_event = categorize(event)
keycodelist = [] keycodelist = []
if event.value == 1 or event.value == 0: # 2 hold, 0 release, 1 press
#debuglog("keyboard-event", "Mode:"+str(event.value)+" Key Code: "+str(key_event.keycode)) if event.value == 2 or event.value == 1:
debuglog("keyboard-event", "Mode:"+str(event.value)+" Key Code: "+str(key_event.keycode))
if isinstance(key_event.keycode, str): if isinstance(key_event.keycode, str):
keycodelist = [key_event.keycode] keycodelist = [key_event.keycode]
else: else:
keycodelist = key_event.keycode keycodelist = key_event.keycode
else:
continue
keycodelistidx = 0 keycodelistidx = 0
while keycodelistidx < len(keycodelist): while keycodelistidx < len(keycodelist):
tmpkeycode = keycodelist[keycodelistidx] tmpkeycode = keycodelist[keycodelistidx]
if tmpkeycode == "KEY_SYSRQ":
# This gets fired for some devices
tmpkeycode = KEYCODE_PAUSE
elif curdevicefw == "314":
# Remap printscreen event as pause and vice versa for special handling
if tmpkeycode == "KEY_PRINTSCREEN":
tmpkeycode = KEYCODE_PAUSE
elif tmpkeycode == KEYCODE_PAUSE:
# Some other key so it will not fire
tmpkeycode = "KEY_PRINTSCREEN"
debuglog("keyboard-event", "FW:" + curdevicefw+ " Key Code: "+tmpkeycode + " Press:"+keycodelist[keycodelistidx])
keycodelistidx = keycodelistidx + 1 keycodelistidx = keycodelistidx + 1
if tmpkeycode not in ["KEY_BRIGHTNESSDOWN", "KEY_BRIGHTNESSUP", "KEY_VOLUMEDOWN", "KEY_VOLUMEUP"]: if tmpkeycode not in [KEYCODE_BRIGHTNESSDOWN, KEYCODE_BRIGHTNESSUP, KEYCODE_VOLUMEDOWN, KEYCODE_VOLUMEUP]:
if event.value == 0: if event.value == 2:
# Hold for unhandled keys # Skip hold for unhandled keys
continue continue
elif tmpkeycode not in ["KEY_PAUSE", "KEY_MUTE"]: elif tmpkeycode not in [KEYCODE_PAUSE, KEYCODE_MUTE]:
# Press for unhandled keys # Skip press for unhandled keys
continue continue
adjustval = 0 tmptime = time.time()
adjusttype = ADJUSTTYPE_NONE finalmode = event.value
if event.value == 2:
if event.value == 1: # Hold needs checking
# Press
debuglog("keyboard-event", "Press Key Code: "+str(tmpkeycode))
tmptime = time.time()
# Guard time for press
if tmpkeycode not in ["KEY_MUTE"]:
# Buttons w/o guard time
keypresstimestamp[tmpkeycode] = tmptime
elif tmpkeycode in keypresstimestamp:
if (tmptime - keypresstimestamp[tmpkeycode]) >= PRESSWAITINTERVALSEC:
keypresstimestamp[tmpkeycode] = tmptime
else:
continue
else:
# First Press
keypresstimestamp[tmpkeycode] = tmptime
if tmpkeycode == "KEY_BRIGHTNESSDOWN" or tmpkeycode == "KEY_BRIGHTNESSUP":
adjusttype = ADJUSTTYPE_BRIGHTNESS
if tmpkeycode == "KEY_BRIGHTNESSDOWN":
adjustval = -5
else:
adjustval = 5
elif tmpkeycode == "KEY_VOLUMEDOWN" or tmpkeycode == "KEY_VOLUMEUP":
adjusttype = ADJUSTTYPE_VOLUME
if tmpkeycode == "KEY_VOLUMEDOWN":
adjustval = -5
else:
adjustval = 5
elif tmpkeycode == "KEY_PAUSE":
adjusttype = ADJUSTTYPE_BATTERYINFO
elif tmpkeycode == "KEY_MUTE":
adjusttype = ADJUSTTYPE_MUTE
adjustval = 0
elif event.value == 0:
# Hold
debuglog("keyboard-event", "Hold Key Code: "+str(tmpkeycode))
tmptime = time.time()
if tmpkeycode in keypresstimestamp: if tmpkeycode in keypresstimestamp:
# Guard time before first for hold # Guard time before first for hold
if (tmptime - keypresstimestamp[tmpkeycode]) >= PRESSWAITINTERVALSEC: if (tmptime - keypresstimestamp[tmpkeycode]) >= FIRSTHOLDINTERVALSEC:
# Guard time for hold # Guard time for hold
if tmpkeycode in keyholdtimestamp: if tmpkeycode in keyholdtimestamp:
if (tmptime - keyholdtimestamp[tmpkeycode]) >= HOLDWAITINTERVALSEC: if (tmptime - keyholdtimestamp[tmpkeycode]) < HOLDWAITINTERVALSEC:
keyholdtimestamp[tmpkeycode] = tmptime #debuglog("keyboard-event", "Hold Key Code: "+str(tmpkeycode)+" - Skip")
else:
continue continue
else:
# First Hold event
keyholdtimestamp[tmpkeycode] = tmptime
else: else:
#debuglog("keyboard-event", "Hold Key Code: "+str(tmpkeycode)+" - Skip")
continue continue
else: else:
# Should not happen, but treat as if first press # Should not happen, but treat as if first press
keypresstimestamp[tmpkeycode] = tmptime finalmode = 1
if tmpkeycode == "KEY_BRIGHTNESSDOWN" or tmpkeycode == "KEY_BRIGHTNESSUP": #debuglog("keyboard-event", "Mode:"+str(event.value) + " Final:"+str(finalmode)+" " +str(tmpkeycode))
adjusttype = ADJUSTTYPE_BRIGHTNESS
if tmpkeycode == "KEY_BRIGHTNESSDOWN":
adjustval = -10
else:
adjustval = 10
elif tmpkeycode == "KEY_VOLUMEDOWN" or tmpkeycode == "KEY_VOLUMEUP":
adjusttype = ADJUSTTYPE_VOLUME
if tmpkeycode == "KEY_VOLUMEDOWN":
adjustval = -10
else:
adjustval = 10
if finalmode == 1:
keypresstimestamp[tmpkeycode] = tmptime
tmplockfilea = KEYBOARD_LOCKFILE+".a" writeq.put("PRESS+"+tmpkeycode)
if createlockfile(tmplockfilea) == False: else:
# Debug ONLY keyholdtimestamp[tmpkeycode] = tmptime
if event.value == 1: writeq.put("HOLD+"+tmpkeycode)
debuglog("keyboard-event", "Press Key Code: "+str(tmpkeycode)+ " => "+str(adjusttype))
else:
debuglog("keyboard-event", "Hold Key Code: "+str(tmpkeycode)+ " => "+str(adjusttype))
if adjusttype == ADJUSTTYPE_BRIGHTNESS:
try:
tmpobj = keyboardevent_adjustbrigthness(curbrightness, adjustval)
curbrightness = tmpobj["level"]
except Exception:
pass
elif adjusttype == ADJUSTTYPE_VOLUME or adjusttype == ADJUSTTYPE_MUTE:
try:
tmpobj = keyboardevent_adjustvolume(curvolume, curvolumemuted, adjustval)
curvolumemuted = tmpobj["muted"]
curvolume = tmpobj["level"]
except Exception:
pass
elif adjusttype == ADJUSTTYPE_BATTERYINFO:
outobj = battery_loadlogdata()
try:
notifymessage(outobj["power"], False)
except:
pass
deletelockfile(tmplockfilea)
except Exception as keyhandleerr: except Exception as keyhandleerr:
try: try:
@@ -625,9 +764,6 @@ def keyboardevent_check(readq):
except: except:
debuglog("keyboard-keyerror", "Error") debuglog("keyboard-keyerror", "Error")
else:
# No events received within the timeout
pass
newpathlist = keyboardevent_getdevicepaths() newpathlist = keyboardevent_getdevicepaths()
if keyboardevent_devicechanged(devicepathlist, newpathlist): if keyboardevent_devicechanged(devicepathlist, newpathlist):
debuglog("keyboard-update", "Device list changed") debuglog("keyboard-update", "Device list changed")
@@ -650,6 +786,10 @@ def keyboardevent_check(readq):
except Exception as mainerr: except Exception as mainerr:
time.sleep(10) time.sleep(10)
# While True # While True
try:
writeq.put("EXIT")
except Exception:
pass
if len(sys.argv) > 1: if len(sys.argv) > 1:
@@ -660,11 +800,18 @@ if len(sys.argv) > 1:
else: else:
try: try:
debuglog("keyboard-service", "Service Starting") debuglog("keyboard-service", "Service Starting")
keyboardevent_check("") ipcq = Queue()
t1 = Thread(target = keyboardevemt_keyhandler, args =(ipcq, ))
t2 = Thread(target = keyboardevent_monitor, args =(ipcq, ))
t1.start()
t2.start()
ipcq.join()
except Exception as einit: except Exception as einit:
try: try:
debuglog("keyboard-service-error", str(einit)) debuglog("keyboard-service-error", str(einit))
except: except:
debuglog("keyboard-service-error", "Error") debuglog("keyboard-service-error", "Error")
checklockerror(KEYBOARD_LOCKFILE)
debuglog("keyboard-service", "Service Stopped") debuglog("keyboard-service", "Service Stopped")
deletelockfile(KEYBOARD_LOCKFILE)

View File

@@ -185,6 +185,14 @@ daemonconfigfile=/etc/$daemonname.conf
lidconfigscript=$INSTALLATIONFOLDER/${basename}-lidconfig.sh lidconfigscript=$INSTALLATIONFOLDER/${basename}-lidconfig.sh
for TMPDIRECTORY in "/lib/systemd/system"
do
sudo mkdir -p "$TMPDIRECTORY"
sudo chmod 755 $TMPDIRECTORY
sudo chown root:root "$TMPDIRECTORY"
done
echo "Installing/Updating scripts and services ..." echo "Installing/Updating scripts and services ..."
if [ ! -f $daemonconfigfile ]; then if [ ! -f $daemonconfigfile ]; then
@@ -402,18 +410,27 @@ then
sudo systemctl daemon-reload sudo systemctl daemon-reload
sudo systemctl enable argononeupd.service sudo systemctl enable argononeupd.service
sudo systemctl start argononeupd.service sudo systemctl start argononeupd.service
# Enable and Start User Service(s)
sudo systemctl --global enable argononeupduser.service
sudo systemctl --global start argononeupduser.service
else else
sudo systemctl daemon-reload sudo systemctl daemon-reload
sudo systemctl restart argononeupd.service sudo systemctl restart argononeupd.service
sudo systemctl --global restart argononeupduser.service
fi fi
# Enable and Start User Service(s)
for tmpuser in `awk -F: '{ if ($3 >= 1000) print $1 }' /etc/passwd`
do
if [ "$tmpuser" != "nobody" ]
then
if [ "$setupmode" = "Setup" ]
then
sudo -u "$tmpuser" systemctl --user enable argononeupduser.service
sudo -u "$tmpuser" systemctl --user start argononeupduser.service
else
sudo -u "$tmpuser" systemctl --user restart argononeupduser.service
fi
fi
done
if [ "$CHECKPLATFORM" = "Raspbian" ] if [ "$CHECKPLATFORM" = "Raspbian" ]
then then
if [ -f "$eepromrpiscript" ] if [ -f "$eepromrpiscript" ]

View File

@@ -131,7 +131,7 @@ def battery_checkupdateprofile():
try: try:
REG_GPIOCONFIG = 0x0A REG_GPIOCONFIG = 0x0A
PROFILE_DATALIST = [0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xA8,0xAA,0xBE,0xC6,0xB8,0xAE,0xC2,0x98,0x82,0xFF,0xFF,0xCA,0x98,0x75,0x63,0x55,0x4E,0x4C,0x49,0x98,0x88,0xDC,0x34,0xDB,0xD3,0xD4,0xD3,0xD0,0xCE,0xCB,0xBB,0xE7,0xA2,0xC2,0xC4,0xAE,0x96,0x89,0x80,0x74,0x67,0x63,0x71,0x8E,0x9F,0x85,0x6F,0x3B,0x20,0x00,0xAB,0x10,0x00,0xB0,0x73,0x00,0x00,0x00,0x64,0x08,0xD3,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xAC] PROFILE_DATALIST = [0x32,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xA8,0xAA,0xBE,0xC6,0xB8,0xAE,0xC2,0x98,0x82,0xFF,0xFF,0xCA,0x98,0x75,0x63,0x55,0x4E,0x4C,0x49,0x98,0x88,0xDC,0x34,0xDB,0xD3,0xD4,0xD3,0xD0,0xCE,0xCB,0xBB,0xE7,0xA2,0xC2,0xC4,0xAE,0x96,0x89,0x80,0x74,0x67,0x63,0x71,0x8E,0x9F,0x85,0x6F,0x3B,0x20,0x00,0xAB,0x10,0xFF,0xB0,0x73,0x00,0x00,0x00,0x64,0x08,0xD3,0x77,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFA]
PROFILE_LEN = len(PROFILE_DATALIST) PROFILE_LEN = len(PROFILE_DATALIST)
@@ -351,10 +351,17 @@ def battery_check(readq):
curnotifycritical = False curnotifycritical = False
if device_charging == 0: if device_charging == 0:
if device_battery>99: if "Shutting Down" in prevnotifymsg:
statusstr = "Charged" os.system("shutdown -c ""Charging, shutdown cancelled.""")
else: debuglog("battery-shutdown", "Abort")
statusstr = "Charging"
if device_battery>99:
# Prevents switching issue
statusstr = "Charged"
curnotifymsg = statusstr
tmpiconfile = tmpiconfile+"charge_"+str(device_battery)
elif device_charging == 0:
statusstr = "Charging"
curnotifymsg = statusstr curnotifymsg = statusstr
tmpiconfile = tmpiconfile+"charge_"+str(device_battery) tmpiconfile = tmpiconfile+"charge_"+str(device_battery)
else: else:
@@ -367,8 +374,12 @@ def battery_check(readq):
curnotifymsg="50%% Battery" curnotifymsg="50%% Battery"
elif device_battery > 10: elif device_battery > 10:
curnotifymsg="20%% Battery" curnotifymsg="20%% Battery"
elif device_battery > 5:
#curnotifymsg="Low Battery"
curnotifymsg="Low Battery: The device may power off automatically soon."
curnotifycritical=True
else: else:
curnotifymsg="Low Battery" curnotifymsg="CRITICAL BATTERY: Shutting Down in 1 minute"
curnotifycritical=True curnotifycritical=True
tmpiconfile = tmpiconfile + ".png" tmpiconfile = tmpiconfile + ".png"
@@ -382,7 +393,9 @@ def battery_check(readq):
# Send notification if necessary # Send notification if necessary
if prevnotifymsg != curnotifymsg: if prevnotifymsg != curnotifymsg:
notifymessage(curnotifymsg, curnotifycritical) notifymessage(curnotifymsg, curnotifycritical)
if device_battery <= 5 and device_charging != 0:
os.system("shutdown +1 """+curnotifymsg+".""")
debuglog("battery-shutdown", "Shutdown in 1 minute")
prevnotifymsg = curnotifymsg prevnotifymsg = curnotifymsg

View File

@@ -17,6 +17,79 @@ def argonpowerbutton_debuglog(typestr, logstr):
except: except:
pass pass
def argonpowerbutton_getvalue(lineobj,lineid):
if lineid is not None:
tmpval = lineobj.get_value(lineid) != gpiod.line.Value.INACTIVE
if tmpval == False:
return 0
return 1
return lineobj.get_value()
def argonpowerbutton_watchline(debugname, dataq, lineid, callback):
monitormode = True
argonpowerbutton_debuglog(debugname, "Starting")
# Pi5 mapping, 0 for older
chippath = '/dev/gpiochip4'
try:
chip = gpiod.Chip(chippath)
except Exception as gpioerr:
try:
# Old mapping
chippath = '/dev/gpiochip0'
chip = gpiod.Chip(chippath)
except Exception as gpioolderr:
chippath = ""
if len(chippath) == 0:
argonpowerbutton_debuglog(debugname+"-error", "Unable to initialize GPIO")
try:
dataq.put("ERROR")
except:
pass
return
# Monitoring starts
try:
try:
# Reference https://github.com/brgl/libgpiod/blob/master/bindings/python/examples/gpiomon.py
lineobj = chip.get_line(lineid)
if lineid == 27:
lineobj.request(consumer="argon", type=gpiod.LINE_REQ_EV_BOTH_EDGES, flags=gpiod.LINE_REQ_FLAG_BIAS_PULL_UP)
else:
lineobj.request(consumer="argon", type=gpiod.LINE_REQ_EV_BOTH_EDGES)
while monitormode == True:
hasevent = lineobj.event_wait(10)
if hasevent:
eventdata = lineobj.event_read()
monitormode = callback(eventdata.type == gpiod.LineEvent.RISING_EDGE, lineobj, dataq, None)
lineobj.release()
chip.close()
except Exception:
# https://github.com/brgl/libgpiod/blob/master/bindings/python/examples/watch_line_rising.py
configobj = {lineid: gpiod.LineSettings(direction=gpiod.line.Direction.INPUT, edge_detection=gpiod.line.Edge.BOTH)}
if lineid == 27:
configobj = {lineid: gpiod.LineSettings(direction=gpiod.line.Direction.INPUT, edge_detection=gpiod.line.Edge.BOTH, bias=gpiod.line.Bias.PULL_UP )}
with gpiod.request_lines(
chippath,
consumer="argon",
config=configobj,
) as request:
while monitormode:
# Blocks until at least one event is available
for event in request.read_edge_events():
monitormode = callback(event.event_type == event.Type.RISING_EDGE, request, dataq, event.line_offset)
except Exception as monitorerror:
try:
argonpowerbutton_debuglog(debugname+"-error", str(monitorerror))
except:
argonpowerbutton_debuglog(debugname+"-error", "Error aborting")
try:
dataq.put("ERROR")
except:
pass
# This function is the thread that monitors activity in our shutdown pin # This function is the thread that monitors activity in our shutdown pin
# The pulse width is measured, and the corresponding shell command will be issued # The pulse width is measured, and the corresponding shell command will be issued
@@ -58,131 +131,76 @@ def argonpowerbutton_getconfigval(keyname, datatype="int"):
return -1 return -1
return "" return ""
def argonpowerbutton_monitorlid(writeq): def argonpowerbutton_monitorlidevent(isrising, lineobj, writeq, lineid):
try: if isrising == False:
argonpowerbutton_debuglog("lid-monitor", "Starting") targetsecs = argonpowerbutton_getconfigval("lidshutdownsecs")
monitormode = True if targetsecs > 0:
argonpowerbutton_debuglog("lid-monitor", "Close Detect; Wait for :"+str(targetsecs))
else:
argonpowerbutton_debuglog("lid-monitor", "Close Detected; Do nothing")
# Time pulse data
time.sleep(1)
pulsetimesec = 1
# 0 - Lid is closed, 1 - Lid is open # 0 - Lid is closed, 1 - Lid is open
# Pin Assignments while argonpowerbutton_getvalue(lineobj, lineid) == 0:
LINE_LIDMONITOR=27 if targetsecs > 0:
try: if pulsetimesec >= targetsecs:
# Pi5 mapping argonpowerbutton_debuglog("lid-monitor", "Target Reached, shutting down")
chip = gpiod.Chip('4') monitormode = False
except Exception as gpioerr: os.system("shutdown now -h")
# Old mapping return False
chip = gpiod.Chip('0')
lineobj = chip.get_line(LINE_LIDMONITOR) time.sleep(1)
lineobj.request(consumer="argon", type=gpiod.LINE_REQ_EV_BOTH_EDGES, flags=gpiod.LINE_REQ_FLAG_BIAS_PULL_UP) pulsetimesec += 1
while monitormode == True: argonpowerbutton_debuglog("lid-monitor", "Open Detected")
hasevent = lineobj.event_wait(10) return True
if hasevent:
eventdata = lineobj.event_read()
if eventdata.type == gpiod.LineEvent.FALLING_EDGE:
targetsecs = argonpowerbutton_getconfigval("lidshutdownsecs")
if targetsecs > 0:
argonpowerbutton_debuglog("lid-monitor", "Close Detect; Wait for :"+str(targetsecs))
else:
argonpowerbutton_debuglog("lid-monitor", "Close Detected; Do nothing")
# Time pulse data
time.sleep(1)
pulsetimesec = 1
while lineobj.get_value() == 0:
if targetsecs > 0:
if pulsetimesec >= targetsecs:
argonpowerbutton_debuglog("lid-monitor", "Target Reached, shutting down")
monitormode = False
os.system("shutdown now -h")
break
time.sleep(1) def argonpowerbutton_monitorlid(writeq):
pulsetimesec += 1 LINE_LIDMONITOR=27
argonpowerbutton_debuglog("lid-monitor", "Open Detected") argonpowerbutton_watchline("lid-monitor", writeq, LINE_LIDMONITOR, argonpowerbutton_monitorlidevent)
lineobj.release() def argonpowerbutton_monitorevent(isrising, lineobj, writeq, lineid):
chip.close() pulsetime = 0
except Exception as liderror: if isrising == True:
try: # Time pulse data
argonpowerbutton_debuglog("lid-monitor-error", str(liderror)) while argonpowerbutton_getvalue(lineobj, lineid) == 1:
except: time.sleep(0.01)
argonpowerbutton_debuglog("lid-monitor-error", "Error aborting") pulsetime += 1
#pass
if pulsetime >=2 and pulsetime <=3:
# Testing
#writeq.put("OLEDSWITCH")
writeq.put("OLEDSTOP")
os.system("reboot")
return False
elif pulsetime >=4 and pulsetime <=5:
writeq.put("OLEDSTOP")
os.system("shutdown now -h")
return False
elif pulsetime >=6 and pulsetime <=7:
writeq.put("OLEDSWITCH")
return True
def argonpowerbutton_monitor(writeq): def argonpowerbutton_monitor(writeq):
LINE_SHUTDOWN=4
argonpowerbutton_watchline("button", writeq, LINE_SHUTDOWN, argonpowerbutton_monitorevent)
try:
# Reference https://github.com/brgl/libgpiod/blob/master/bindings/python/examples/gpiomon.py
# Pin Assignments def argonpowerbutton_monitorswitchevent(isrising, lineobj, writeq, lineid):
LINE_SHUTDOWN=4 pulsetime = 0
try: if isrising == True:
# Pi5 mapping # Time pulse data
chip = gpiod.Chip('4') while argonpowerbutton_getvalue(lineobj, lineid) == 1:
except Exception as gpioerr: time.sleep(0.01)
# Old mapping pulsetime += 1
chip = gpiod.Chip('0')
lineobj = chip.get_line(LINE_SHUTDOWN)
lineobj.request(consumer="argon", type=gpiod.LINE_REQ_EV_BOTH_EDGES)
while True:
hasevent = lineobj.event_wait(10)
if hasevent:
pulsetime = 0
eventdata = lineobj.event_read()
if eventdata.type == gpiod.LineEvent.RISING_EDGE:
# Time pulse data
while lineobj.get_value() == 1:
time.sleep(0.01)
pulsetime += 1
if pulsetime >=2 and pulsetime <=3:
# Testing
#writeq.put("OLEDSWITCH")
writeq.put("OLEDSTOP")
os.system("reboot")
break
elif pulsetime >=4 and pulsetime <=5:
writeq.put("OLEDSTOP")
os.system("shutdown now -h")
break
elif pulsetime >=6 and pulsetime <=7:
writeq.put("OLEDSWITCH")
lineobj.release()
chip.close()
except Exception:
writeq.put("ERROR")
if pulsetime >= 10:
writeq.put("OLEDSWITCH")
return True
def argonpowerbutton_monitorswitch(writeq): def argonpowerbutton_monitorswitch(writeq):
LINE_SHUTDOWN=4
argonpowerbutton_watchline("button-switch", writeq, LINE_SHUTDOWN, argonpowerbutton_monitorswitchevent)
try: # Testing
# Reference https://github.com/brgl/libgpiod/blob/master/bindings/python/examples/gpiomon.py #argonpowerbutton_monitor(None)
# Pin Assignments
LINE_SHUTDOWN=4
try:
# Pi5 mapping
chip = gpiod.Chip('4')
except Exception as gpioerr:
# Old mapping
chip = gpiod.Chip('0')
lineobj = chip.get_line(LINE_SHUTDOWN)
lineobj.request(consumer="argon", type=gpiod.LINE_REQ_EV_BOTH_EDGES)
while True:
hasevent = lineobj.event_wait(10)
if hasevent:
pulsetime = 0
eventdata = lineobj.event_read()
if eventdata.type == gpiod.LineEvent.RISING_EDGE:
# Time pulse data
while lineobj.get_value() == 1:
time.sleep(0.01)
pulsetime += 1
if pulsetime >= 10:
writeq.put("OLEDSWITCH")
lineobj.release()
chip.close()
except Exception:
writeq.put("ERROR")