-
Notifications
You must be signed in to change notification settings - Fork 0
/
apcaccess.py
executable file
·163 lines (124 loc) · 3.42 KB
/
apcaccess.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
#!/usr/bin/env python
import argparse
import signal
import socket
import time
from collections import OrderedDict
STATUS_CMD = "\x00\x06status".encode()
EOF = " \n\x00\x00"
SEP = ":"
BUFFER_SIZE = 1024
UNITS = (
"C",
"VA",
"Hz",
"Amps",
"Watts",
"Volts",
"Percent",
"Seconds",
"Minutes",
"Percent Load Capacity"
)
def strip_apc_units(lines):
for line in lines:
for unit in UNITS:
if line.endswith(" %s" % unit):
line = line[:-1-len(unit)]
yield line
def printData(values, data, writer):
if 'all' in values:
for v in data.keys():
writer.write("%s %s" % (v, data[v]))
else:
for v in values:
writer.write("%s %s" % (v, data[v]))
class FileWriter:
def __init__(self, path="/tmp/apcaccess.out"):
self.path = path
self.lines = []
def write(self, data):
self.lines += [data]
def flush(self):
with open(self.path, 'w') as f:
for line in self.lines:
print(line, file=f)
self.lines.clear()
class StdWriter:
def write(self, data):
print(data)
def flush(self):
pass
class ApcAccess:
def __init__(self, host="localhost", port=3551, timeout=30):
"""
Connect to apcupsd port and get data.
"""
self.host = host
self.port = port
self.timeout = timeout
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(self.timeout)
self.sock.connect((self.host, self.port))
def close(self):
self.sock.close()
def _getStatus(self):
self.sock.send(STATUS_CMD)
buffer = ""
while not buffer.endswith(EOF):
buffer += self.sock.recv(BUFFER_SIZE).decode()
return buffer
def getData(self):
buf = self._getStatus()
lines = [x[1:-1] for x in buf[:-len(EOF)].split("\x00") if x]
lines = strip_apc_units(lines)
return OrderedDict([[x.strip() for x in x.split(SEP, 1)] for x in lines])
class Runner:
def __init__(self, args):
self.args = args
if args.output == '-':
self.writer = StdWriter()
else:
self.writer = FileWriter(args.output)
def run(self):
a = ApcAccess(self.args.host, self.args.port)
a.connect()
if self.args.follow != -1:
self.follow = True
f = self.args.follow
while self.follow:
data = a.getData()
printData(self.args.values, data, self.writer)
self.writer.flush()
time.sleep(f)
else:
data = a.getData()
printData(self.args.values, data, self.writer)
self.writer.flush()
a.close()
def sigint(self, signum, frame):
self.follow = False
def main():
parser = argparse.ArgumentParser(
prog='ApcAccess.py',
description='python apc access util')
parser.add_argument('--host',
default='localhost',
help='host to connect to')
parser.add_argument('-p', '--port',
default=3551,
help='port to connect to')
parser.add_argument('-o', '--output',
default='-', type=str,
help='output path or stdout (-)')
parser.add_argument('-f', '--follow',
default=-1,
type=float,
help='continue to pull and update')
parser.add_argument('values', nargs='+')
runner = Runner(parser.parse_args())
signal.signal(signal.SIGINT, runner.sigint)
runner.run()
if __name__ == '__main__':
main()