-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBatteryMonitor.py
More file actions
208 lines (169 loc) · 8.24 KB
/
BatteryMonitor.py
File metadata and controls
208 lines (169 loc) · 8.24 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
#!/usr/bin/env python3
import sys, time
from daemon import config, LogginSystem, Daemon
import yaml
import argparse
import datetime
from gpiozero import Button
from gpiozero.pins.rpigpio import RPiGPIOPin
import os
import subprocess
import Adafruit_ADS1x15
import shlex
import psutil
'''
percentage:
100%: 4.09 # 4.09
75%: 3.68 # 3.76
50%: 3.46 # 3.63
25%: 3.35 # 3.5
0%: 3.25 # 3.2
voltage:
4.09: 100 # 4.09
3.68: 75 # 3.76
3.46: 50 # 3.63
3.35: 25 # 3.5
3.25: 0 # 3.2
'''
def arguments_reader():
parser = argparse.ArgumentParser(description='battery-monitor runner')
parser.add_argument('operation',
metavar='OPERATION',
type=str,
help='Operation with BatteryMonitor agent. Accepts any of these values: start, stop, restart, status',
choices=['start', 'stop', 'restart', 'status'])
args = parser.parse_args()
operation = args.operation
return operation
logfile = open('./battery-monitor.log', 'a+')
class BatteryMonitor(Daemon):
def run(self):
#fix this - most liekly implent a python config file allowing for logic - will also fix the voltages dict issue
if 'methods' not in config.keys():
config['methods'] = {'shutdown':self.shutdown, 'monitor':self.display_icon }
if config['ads']['ADS1015']:
if config['ads']['ADS1115']:
print('unable to set up ADS - please have one value true on value false')
sys.exit(0)
self.ads = Adafruit_ADS1x15.ADS1015()
elif config['ads']['ADS1115']:
if config['ads']['ADS1015']:
print('unable to set up ADS - please have one value true on value false')
sys.exit(0)
self.ads = Adafruit_ADS1x15.ADS1115()
else:
print('unable to set up ADS - please have one value true on value false')
sys.exit(0)
self.logger = logfile
self.get_buttons()
while True:
self.battery_percent()
for buttontype, buttons in self.buttons.items():
for button in buttons:
if button[1].hold_time != 1:
button[1].when_held = config['methods'][buttontype]
else:
button[1].when_pressed = config['methods'][buttontype]
def process_spawner(self, subprocess_call):
self.pngprocess = psutil.Process(subprocess_call.pid)
try:
self.pngprocess.wait(timeout=3.0)
except psutil.TimeoutExpired:
self.pngprocess.kill()
self.pngprocess = None
pass #raise
def get_buttons(self):
# shutdown_btn = Button(int(config['button']['shutdown']))#, hold_time=1)
#monitor_btn = Button(int(config['button']['monitor'])) #, hold_time=2)
self.buttons = dict()
for i, ( buttontype, buttonattributes ) in enumerate(config['button'].items()):
buttonname = '{}_{}'.format(buttontype, i)
buttonpin, buttonhold = buttonattributes
if buttontype not in self.buttons.keys():
self.buttons[buttontype] = list()
self.buttons[buttontype].append(tuple([buttonname, Button(buttonpin, hold_time=buttonhold)]))
else:
self.buttons[buttontype].append(tuple([buttonname, Button(buttonpin, hold_time=buttonhold)]))
def read_battery_voltage(self):
total = 0.0
loops = 0.0
start = time.time()
while (time.time() - start) <= config['votage_reading']['seconds']:
# Read the last ADC conversion value and print it out.
try:
value = self.ads.read_adc(0, gain=config['gain'])
except IOError:
print 'ADS IC2 appears not to be working'
return None
total += float(value)
loops += 1.0
time.sleep(config['votage_reading']['sleep'])
value = total/loops
return round(value, 2)
def display_icon(self):
self.logger.write('display_icon')
if not self.percent:
self.percent = battery_percent
command = '{}/pngview -b 0 -l 3000{} -x {} -y {} {}/battery{}.png &'.format(config['png']['path'], self.percent,
config['png']['x'],config['png']['y'],
config['png']['icon'], self.percent)
subprocess_call = subprocess.Popen(shlex.split(command))
self.process_spawner(subprocess_call)
if self.pngprocess:
self.pngprocess.kill()
def battery_percent(self):
raw_voltage = self.read_battery_voltage()
self.logger.write('Raw Votage ' + str(raw_voltage)+ '\n')
if raw_voltage:
self.voltage = round(raw_voltage * config['converstion-ratio'], 2)
self.logger.write('Votage ' + str(self.voltage) + '\n')
for key in config['voltages']:
if not self.voltage:
self.voltage = round(raw_voltage * config['converstion-ratio'], 2)
self.logger.write('Votage ' + str(self.voltage) + '\n')
if self.voltage in key:
self.percent = config['voltages'][key]
break
self.percent = None
else:
#add new state for non configured : create icon
self.percent = 100
self.voltage = 4.1
#display appropriate icon.
def shutdown(self):
command = 'shutdown -h now'
#print(command)
subprocess.Popen(shlex.split(command))
def restart(self):
command = 'reboot'
#print(command)
subprocess.Popen(shlex.split(command))
def reset(self):
command = 'pkill retroarch & retroarch'
#print(command)
subprocess.Popen(shlex.split(command))
if __name__ == "__main__":
action = arguments_reader()
daemon = BatteryMonitor()
if action == 'start':
print("Starting BatteryMonitor agent")
daemon.start()
pid = daemon.get_pid()
if not pid:
print("Unable run BatteryMonitor agent")
else:
print("BatteryMonitor agent is running")
elif action == 'stop':
print("Stoping BatteryMonitor agent")
daemon.stop()
elif action == 'restart':
print("Restarting BatteryMonitor agent")
daemon.restart()
elif action == 'status':
print("Viewing BatteryMonitor agent status")
pid = daemon.get_pid()
if not pid:
print("BatteryMonitor agent isn't running")
else:
print("BatteryMonitor agent is running")
sys.exit(0)