Skip to content

Instantly share code, notes, and snippets.

@oquno
Last active March 5, 2024 08:58
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oquno/d07f6dbf8cc760f2534d9914efe79801 to your computer and use it in GitHub Desktop.
Save oquno/d07f6dbf8cc760f2534d9914efe79801 to your computer and use it in GitHub Desktop.
UD-CO2S にシリアル接続してデータを JSON ファイルに上書きし続けるスクリプト
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")
@oquno
Copy link
Author

oquno commented Mar 10, 2023

注意

  • tempfs とか使わないと書き込み続けるのでRaspberry Pi なんかはSDカードぶっ壊れ加速する可能性あり
  • STP コマンド発動しない気がするので STP ちゃんとしたい場合は別途ちゃんとしてもらう(自分は常時動かすので気にしていない)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment