-
Notifications
You must be signed in to change notification settings - Fork 4
/
SB6183.py
188 lines (153 loc) · 6.78 KB
/
SB6183.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
import configparser
import os
import sys
import argparse
from influxdb import InfluxDBClient
from influxdb.exceptions import InfluxDBClientError, InfluxDBServerError
import time
from datetime import datetime
from bs4 import BeautifulSoup
import requests
class configManager():
def __init__(self, config):
print('Loading Configuration File {}'.format(config))
self.modem_url = []
config_file = os.path.join(os.getcwd(), config)
if os.path.isfile(config_file):
self.config = configparser.ConfigParser()
self.config.read(config_file)
else:
print('ERROR: Unable To Load Config File: {}'.format(config_file))
sys.exit(1)
self._load_config_values()
print('Configuration Successfully Loaded')
def _load_config_values(self):
# General
self.delay = self.config['GENERAL'].getint('Delay', fallback=2)
self.output = self.config['GENERAL'].getboolean('Output', fallback=True)
# InfluxDB
self.influx_address = self.config['INFLUXDB']['Address']
self.influx_port = self.config['INFLUXDB'].getint('Port', fallback=8086)
self.influx_database = self.config['INFLUXDB'].get('Database', fallback='cable_modem_stats')
self.influx_user = self.config['INFLUXDB'].get('Username', fallback='')
self.influx_password = self.config['INFLUXDB'].get('Password', fallback='')
self.influx_ssl = self.config['INFLUXDB'].getboolean('SSL', fallback=False)
self.influx_verify_ssl = self.config['INFLUXDB'].getboolean('Verify_SSL', fallback=True)
# Cable Modem
self.modem_url = self.config['MODEM'].get('URL', fallback='http://192.168.100.1/RgConnect.asp')
class InfluxdbModem():
def __init__(self, config=None):
self.config = configManager(config=config)
self.output = self.config.output
self.influx_client = InfluxDBClient(
self.config.influx_address,
self.config.influx_port,
username=self.config.influx_user,
password=self.config.influx_password,
database=self.config.influx_database,
ssl=self.config.influx_ssl,
verify_ssl=self.config.influx_verify_ssl
)
self.modem_url = self.config.modem_url
def parse_modem(self):
print('Getting modem stats')
try:
resp = requests.get(self.modem_url)
status_html = resp.content
resp.close()
soup = BeautifulSoup(status_html, 'html.parser')
except Exception as e:
print('ERROR: Failed to get modem stats. Aborting')
print(e)
sys.exit(1)
series = []
current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
# downstream table
for table_row in soup.find_all("table")[2].find_all("tr")[2:]:
if table_row.th:
continue
channel = table_row.find_all('td')[0].text.strip()
channel_id = table_row.find_all('td')[3].text.strip()
frequency = table_row.find_all('td')[4].text.replace(" Hz", "").strip()
power = table_row.find_all('td')[5].text.replace(" dBmV", "").strip()
snr = table_row.find_all('td')[6].text.replace(" dB", "").strip()
corrected = table_row.find_all('td')[7].text.strip()
uncorrectables = table_row.find_all('td')[8].text.strip()
downstream_result_dict = {
'measurement': 'downstream_statistics',
'time': current_time,
'fields': {
'channel_id': int(channel_id),
'frequency': int(frequency),
'power': float(power),
'snr': float(snr),
'corrected': int(corrected),
'uncorrectables': int(uncorrectables)
},
'tags': {
'channel': int(channel)
}
}
series.append(downstream_result_dict)
# if self.output:
# print("channel:{},channel_id:{},frequency:{},power:{},snr:{},corrected:{},uncorrectables:{}".format(channel, channel_id, frequency, power, snr, corrected, uncorrectables))
# upstream table
for table_row in soup.find_all("table")[3].find_all("tr")[2:]:
if table_row.th:
continue
channel = table_row.find_all('td')[0].text.strip()
channel_id = table_row.find_all('td')[3].text.strip()
frequency = table_row.find_all('td')[5].text.replace(" Hz", "").strip()
power = table_row.find_all('td')[6].text.replace(" dBmV", "").strip()
upstream_result_dict = {
'measurement': 'upstream_statistics',
'time': current_time,
'fields': {
'channel_id': int(channel_id),
'frequency': int(frequency),
'power': float(power),
'snr': float(snr)
},
'tags': {
'channel': int(channel)
}
}
series.append(upstream_result_dict)
# if self.output:
# print("channel:{},channel_id:{},frequency:{},snr:{}".format(channel, channel_id, frequency, snr))
self.write_influx_data(series)
def run(self):
while True:
self.parse_modem()
print("sleeping {}s".format(self.config.delay))
sys.stdout.flush()
time.sleep(self.config.delay)
def write_influx_data(self, json_data):
"""
Writes the provided JSON to the database
:param json_data:
:return:
"""
# if self.output:
# print(json_data)
try:
self.influx_client.write_points(json_data)
except (InfluxDBClientError, ConnectionError, InfluxDBServerError) as e:
if hasattr(e, 'code') and e.code == 404:
print('Database {} Does Not Exist. Attempting To Create'.format(self.config.influx_database))
# TODO Grab exception here
self.influx_client.create_database(self.config.influx_database)
self.influx_client.write_points(json_data)
return
print('ERROR: Failed To Write To InfluxDB')
print(e)
if self.output:
print('Written To Influx: {}'.format(json_data))
def main():
parser = argparse.ArgumentParser(description="A tool to send modem stats statistics to InfluxDB")
parser.add_argument('--config', default='config.ini', dest='config', help='Specify a custom location for the config file')
args = parser.parse_args()
collector = InfluxdbModem(config=args.config)
collector.run()
if __name__ == '__main__':
main()