Last active
January 18, 2019 17:01
-
-
Save gdugas/5099d1b0df9c842ddb6a4d6aaee83c89 to your computer and use it in GitHub Desktop.
From sensors -u commandline to json output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import json | |
import sys | |
import yaml | |
class Device: | |
def __init__(self, device_id, adapter, *args): | |
self.device_id = device_id | |
self.adapter = adapter.split(': ', 1)[1].strip() | |
self.sensors = self.parse_sensors(*args) | |
def parse_sensors(self, *args): | |
sensors = {} | |
datas = yaml.load("\n".join(args)) | |
for sensor_id, sensor_params in datas.items(): | |
sensors[sensor_id] = self.parse_sensor(sensor_params) | |
return sensors | |
def parse_sensor(self, params): | |
sensor = {} | |
sensor['tags'] = [] | |
for k, sensor_value in params.items(): | |
[sensor_type, sensor_name] = k.split('_', 1) | |
for t in ['temp', 'power']: | |
if sensor_type.startswith(t): | |
sensor_type = t | |
if not t in sensor['tags']: | |
sensor['tags'].append(t) | |
sensor[sensor_name] = sensor_value | |
return sensor | |
def push_device(devices, buffer): | |
devices.append(Device(buffer.pop(0), buffer.pop(0), *buffer)) | |
devices = [] | |
buffer = [] | |
for row in sys.stdin: | |
line = row.rstrip() | |
if len(line) > 0: | |
buffer.append(line) | |
else: | |
push_device(devices, buffer) | |
buffer = [] | |
if len(buffer) > 0: | |
push_device(devices, buffer) | |
export = {} | |
for d in devices: | |
export[d.device_id] = { | |
'device_id': d.device_id, | |
'adapter': d.adapter, | |
'sensors': d.sensors | |
} | |
print(json.dumps(export)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment