#!/usr/bin/env python3
# Example cron schedule:
# */30 * * * * python3 /usr/local/bin/tuya_temp_hum_update.py

import json
import tinytuya
from time import time
from uuid import uuid4

devices = {
    "sensor1": "xxxxxxxxxxxxxxxxxxID",
    "sensor2": "xxxxxxxxxxxxxxxxxxID"
}

c = tinytuya.Cloud(
    apiRegion="eu",
    apiKey="xxxxxxxxxxxxxxxxxxxx",
    apiSecret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
)

for i in devices:
    try:
        result = c.getstatus(devices[i])
    except:
        t = int(time() * 1000)
        tid = uuid4().hex
        result = (
            """{"result": [{"code": "va_temperature", "value": "unknown"}, {"code": "va_humidity", "value": "unknown"}, {"code": "battery_state", "value": "unknown"}, {"code": "temp_unit_convert", "value": "c"}], "success": false, "t": %d, "tid": "%s"}"""
            % (t, tid)
        )

    with open(f"/tmp/sensors/tuya_temp_hum_{i}.tmp", "w") as fh:
        json.dump(result, fh) if isinstance(result, dict) else fh.write(result)