#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
device_basic.py - 贺简云物联 IoT 设备接入示例（Python）

演示：心跳上线 -> 属性上报 -> 指令拉取。
运行：把 hjyiot.py 与本脚本放在同一目录（或把 hjyiot.py 放入 site-packages），
     然后 python3 device_basic.py
协议参考：docs/设备接入与公开应用.md §1
"""

import time

from hjyiot import HjyIotDevice, HjyIotError

# ===== 1. 配置区（替换为真实值） =====
BASE_URL = "https://www.hjyiot.cn/api.php"   # 生产以平台公网地址为准
DEVICE_ID = "<your_device_id>"
DEVICE_TOKEN = "<your_device_token>"


def simulate_temperature() -> float:
    """模拟传感器返回 15~40°C 之间的值（演示用）。"""
    return 20.0 + ((time.time() * 37) % 100) / 10.0 - 2.5


def main() -> None:
    dev = HjyIotDevice(BASE_URL, DEVICE_ID, DEVICE_TOKEN)

    # 1) 心跳上线
    try:
        data = dev.heartbeat()
        print("[heartbeat]", data)
    except HjyIotError as exc:
        print("[heartbeat] 失败:", exc)
        return

    # 2) 属性上报（props 值须为标量；推荐带外层 ts）
    try:
        data = dev.report(props={"temperature": round(simulate_temperature(), 1),
                                 "humidity": 55},
                          ts=int(time.time()))
        print("[report] accepted, props:", data.get("props"), "online:", data.get("online"))
    except HjyIotError as exc:
        print("[report] 失败:", exc)

    # 3) 指令拉取（拉取即 sent；执行结果需再 report 回写）
    try:
        data = dev.pull_commands()
        cmds = data.get("commands", [])
        print("[command] 拉取到", len(cmds), "条指令")
        for c in cmds:
            print("  -", c)
            # 生产固件：解析 c["id"] / c["payload"] 后驱动执行器，
            # 并把实际执行结果经 dev.report(props={"xxx": 结果}) 回写平台。
    except HjyIotError as exc:
        print("[command] 失败:", exc)

    # 注意：连续多轮调用受平台限流保护（IP 600 次/分、设备 120 次/分），
    # 业务轮询间隔建议 >= 5 秒；生产请使用长连接轮询或 MQTT 通道。
    time.sleep(5)


if __name__ == "__main__":
    main()
