1 PROJECT
= "poweron_tool"
5 --测试固件版本:LuatOS-SoC_V0003_ESP32C3[_USB].soc
9 ---------------------------------------------------------------------------
11 local wifiName
,wifiPassword
= "wifi", "password"--wifi账号密码
12 local pcIp
= "255.255.255.255"--目标pc ip,广播就255.255.255.255
13 local pcMac
= "112233445566" --写mac的hex值就行
14 --服务器使用介绍详见https://api.luatos.org/#poweron
15 local mqttAddr
= "mqtt://apicn.luatos.org:1883"--这是公共服务器,只允许订阅和推送poweron/request/+、poweron/reply/+两个主题
16 local mqttUser
,mqttPassword
= "13xxxxxxxxx","888888"--你的erp账号和密码,连接mqtt服务器用,默认八个8 erp.openluat.com
17 local subscribeTopic
,subscribePayload
= "poweron/request/chenxuuu","poweron"
18 local replyTopic
,replyPayload
= "poweron/reply/chenxuuu","ok"
19 ---------------------------------------------------------------------------
24 local LED_D4
= gpio
.setup(12, 0)
25 local LED_D5
= gpio
.setup(13, 0)
27 sys
.taskInit(function()
43 log.info("socket", "begin socket")
44 local sock
= socket
.create(socket
.UDP
) -- udp
45 log.info("socket.bind", socket
.bind(sock
, "0.0.0.0", 23333)) --udp必须绑定端口
46 local err
= socket
.connect(sock
, pcIp
, 7)--你电脑ip
47 if err
~= 0 then log.info("socket", err
) return end
50 local msg
= string.rep(string.char(0xff),6)..string.rep(mac
,16)
51 local len
= socket
.send(sock
, msg
)
52 log.info("socket", "sendlen", len
)
54 return len
== #msg
, len
57 sys
.taskInit(function()
58 log.info("wlan", "wlan_init:", wlan
.init())
59 wlan
.setMode(wlan
.STATION
)
60 wlan
.connect(wifiName
,wifiPassword
)
62 local result
, data
= sys
.waitUntil("IP_READY")
63 log.info("wlan", "IP_READY", result
, data
)
66 local mqttc
= espmqtt
.init({
68 client_id
= (esp32
.getmac():toHex()),
70 password
= mqttPassword
,
72 log.info("mqttc", mqttc
)
74 log.info("mqttc", "what happen")
75 local ok
, err
= espmqtt
.start(mqttc
)
76 log.info("mqttc", "start", ok
, err
)
80 log.info("mqttc", "wait ESPMQTT_EVT 30s")
81 local result
, c
, ret
, topic
, data
= sys
.waitUntil("ESPMQTT_EVT", 30000)
82 log.info("mqttc", result
, c
, ret
)
83 if result
== false then
85 log.info("mqttc", "wait timeout")
86 elseif ret
== espmqtt
.EVENT_DISCONNECTED
then--断线了
87 log.info("mqttc", "disconnected!!!")
89 elseif c
== mqttc
then
91 if ret
== espmqtt
.EVENT_CONNECTED
then
92 -- 连接成功, 通常就是定义一些topic
93 espmqtt
.subscribe(mqttc
, subscribeTopic
)
94 elseif ret
== espmqtt
.EVENT_DATA
then
95 -- 服务器来消息了, 如果data很长(超过4kb), 可能会分多次接收, 导致topic为空字符串
96 log.info("mqttc", topic
, data
)
97 if data
== subscribePayload
then--收到payload信息是开机
99 log.info("poweron","发送开机请求啦!")
101 espmqtt
.publish(mqttc
, replyTopic
, replyPayload
)--回一条
105 -- qos > 0 的订阅信息有响应, 会进这个分支
106 -- 默认情况下mqtt是自动重连的, 不需要用户关心
107 log.info("mqttc", "event", ret
)
110 log.info("mqttc", "not this mqttc")
115 log.warn("mqttc", "bad start", err
)
117 espmqtt
.destroy(mqttc
)
118 log.warn("reboot", "device will reboot")