UD-CO2S にシリアル接続してデータを JSON ファイルに上書きし続けるスクリプト
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
import json, datetime, re, serial, io | |
class UDCO2S: | |
def __init__(self, dev="/dev/ttyACM0"): | |
self.dev = dev | |
def start_logging(self, log_file): | |
regex = re.compile(r'CO2=(?P<co2>\d+),HUM=(?P<hum>\d+\.\d+),TMP=(?P<tmp>-?\d+\.\d+)') | |
with serial.Serial(self.dev, 115200, timeout=6) as conn: | |
conn.write("STA\r\n".encode()) | |
print(conn.readline().decode().strip()) | |
while True: | |
line = conn.readline().decode().strip() | |
m = regex.match(line) | |
if not m is None: | |
obj = { | |
"time": int(datetime.datetime.now().timestamp()), | |
"stat": { | |
"co2ppm": int(m.group("co2")), | |
"humidity": float(m.group("hum")), | |
"temperature": float(m.group("tmp")), | |
} | |
} | |
with open(log_file, "w") as f: | |
f.write(json.dumps(obj)) | |
conn.write("STP\r\n") | |
if __name__ == "__main__": | |
UDCO2S().start_logging("/var/www/html/sensor.json") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
注意