forked from Zontex/UPS-Lite
-
Notifications
You must be signed in to change notification settings - Fork 2
/
UPS_Lite.py
executable file
·106 lines (83 loc) · 3.4 KB
/
UPS_Lite.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
#!/usr/bin/env python3
import os
import struct
import smbus
import sys
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(4,GPIO.IN)
class UPS():
def __init__(self):
# Set the bus port either 1 or 0
self.bus = smbus.SMBus(1)
# set low capacity alert for the battery
self.low_capacity = 20
self.full_capacity = 100
def read_voltage(self):
# This function returns the voltage as float from the UPS-Lite via SMBus object
address = 0x36
read = self.bus.read_word_data(address, 2)
swapped = struct.unpack("<H", struct.pack(">H", read))[0]
voltage = swapped * 1.25 /1000/16
return voltage
def read_capacity(self):
# This function returns the remaining capacitiy in int as precentage of the battery connect to the UPS-Lite
address = 0x36
read = self.bus.read_word_data(address, 4)
swapped = struct.unpack("<H", struct.pack(">H", read))[0]
capacity = int(swapped/256)
# Write capacity to tempfile. Needed to determine state.
tmpfile= open("/tmp/ups_lite_capacity.tmp","w+")
tmpfile.write(str(capacity))
tmpfile.close
return capacity
def read_powermode(self):
#This function returns if the power is plugged or not
if (GPIO.input(4) == GPIO.LOW):
powermode = "Battery"
if (GPIO.input(4) == GPIO.HIGH):
powermode = "Power Adapter"
return powermode
def read_powerstate(self,capacity):
## GPIO.HIGH > Power > CHARGING
### Cap >= full > CHARGED
## GPIO.LOW > Battery > DISCHARGING
### Cap < low > LOW
# This function returns the powersource and state
if (GPIO.input(4) == GPIO.HIGH):
if(capacity >= self.full_capacity):
state = "CHARGED"
else:
state = "CHARGING"
elif (GPIO.input(4) == GPIO.LOW):
if(capacity <= self.low_capacity):
state = "LOW"
else:
state = "DISCHARGING"
return state
def read_temp(self):
import os
stream = os.popen('/opt/vc/bin/vcgencmd measure_temp')
temp = stream.read()
bla, temp = temp.split("=",2)
return temp
def main():
ups_lite = UPS()
voltage = ups_lite.read_voltage()
capacity = ups_lite.read_capacity()
powermode = ups_lite.read_powermode()
state = ups_lite.read_powerstate(capacity)
temp = ups_lite.read_temp()
print ("******************************************")
print ("* UPS-Lite Status *")
print ("* for Raspberry Pi Zero *")
print ("******************************************")
print (" ")
print (" ","- Voltage...........:",voltage)
print (" ","- Capacity..........:",capacity)
print (" ","- Powering Mode.....:",powermode)
print (" ","- State.............:",state)
print (" ","- SOC Temperature...:",temp)
main()