1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| require "mqtt" module(..., package.seeall)
local host, port = "49.4.93.24", 8883
local device = "355d812e-ad55-47a5-b811-760f760b63a1" local secret = "10f0a44d66a582b3ddee"
require"ntp" local function ntbcb(r) if r then sys.publish("NTP_OK") else ntp.timeSync(nil,ntbcb) end end ntp.timeSync(nil,ntbcb)
local function keyGenerate(key) local clk = os.date("*t",os.time()-3600*8) local timeStr = string.format("%02d%02d%02d%02d",clk.year,clk.month,clk.day,clk.hour) local result = crypto.hmac_sha256(key,timeStr):lower() log.info("keyGenerate",timeStr,key,result) if crypto.hmac_sha256 then return result else log.error("crypto.hmac_sha256","please update your lod version, higher than 0034!") rtos.poweroff() end end
socket.setSendMode(1)
sys.taskInit(function() sys.waitUntil("NTP_OK") while true do while not socket.isReady() do sys.wait(1000) end local clk = os.date("*t",os.time()-3600*8) local mqttc = mqtt.client( device.."_0_1_"..string.format("%02d%02d%02d%02d",clk.year,clk.month,clk.day,clk.hour), 300, device, keyGenerate(secret)) while not mqttc:connect(host, port, "tcp_ssl",{caCert="hw.crt"}) do sys.wait(2000) end if mqttc:subscribe("/huawei/v1/devices/"..device.."/command/json") then while true do local r, data, param = mqttc:receive(120000, "pub_msg") if r then log.info("这是收到了服务器下发的消息:", data.payload or "nil") sys.publish("rev_msg",data.payload) elseif data == "pub_msg" then log.info("这是收到了订阅的消息和参数显示:", param) mqttc:publish("/huawei/v1/devices/"..device.."/data/json", param) elseif data == "timeout" then else break end end end mqttc:disconnect() end end)
sys.subscribe("rev_msg",function(data) local t,r,e = json.decode(data) if r and type(t)=="table" then log.info("receive.msgType",t.msgType) log.info("receive.serviceId",t.serviceId) log.info("receive.cmd",t.cmd) log.info("receive.mid",t.mid)
if t.cmd == "testcmd" then log.info("receive.paras.testControl",t.paras.testControl)
local clk = os.date("*t",os.time()-3600*8)
local reply = { msgType = "deviceRsp", mid = t.mid, errcode = 0, body = { testReply = "done", } } sys.publish("pub_msg",json.encode(reply))
local upload = { msgType = "deviceReq", data = { { serviceId = "testServer", serviceData = { testProperty = t.paras.testControl, }, eventTime = string.format("%02d%02d%02d%02d%02d%02dZ", clk.year,clk.month,clk.day,clk.hour,clk.min,clk.sec) }, } } sys.publish("pub_msg",json.encode(upload)) end else log.info("json.decode error",e) end end)
|