--- 孢子仪mqtt联网模块 -- @module -- @author lcg -- @release 2019.08.01 require 'sys' require 'hmi' require 'audio' require "mqtt" require "led" require "utils" require "agps" require "update" require "control" require "sim" require "config" require "nvm" module(..., package.seeall) -- 指示设备状态标志位:开机重启、掉线重连 dev_sta = 0 -- 本地存储文件 local DEVICE_CONF = "/device.conf" local HOST_CONF = "/host.conf" local SERVER_CONF = "/server.conf" local PARAMCONF = "/paramconf.conf" local NETCONF = "/netconf.conf" local TAKEPHOTO = "/photo.conf" --定时拍照开关,0-开,1-关 local photo_sw = 0 -- 上报json数据的基础表 local message = {cmd = "", ext = {}} -- 上报遗言的json表 local willmsg = {cmd = 'offline', ext = {imei = ''}} -- 服务器上报数据间隔时长,间隔期间用于阻塞读取服务器下发的指令 -- hmi.hmiconf.datt 和下面的timeout 功能一样 -- local timeout = 10 * 60 * 1000 -- MQTT服务器配置表 serverconf = { ip = "120.27.222.26",-- 云飞 -- ip = "39.104.94.153",-- 云飞 port = 1883, sub = "/yfkj/bzy/s2c/", pub = "/yfkj/bzy/c2s/", keepalive = 60, lastwill = "/yfkj/bzy/offline/", uid = "", pwd = "", qos = 0, } -- HTTP服务器配置表 hostconf = { url = "http://120.27.222.26/update",-- 云飞 length = 0, username = "", password = "", } -- 上传的数据格式: -- { -- "cmd": "status", -- "ext": { -- "imei": "866262042555598", -- "iccid": "89860411101871387773", -- "csq": 23, -- "alti": 0, -- "lat": "", -- "lng": "", -- "dtype": 7, -- "on_off": 0, -- "dver": "1.0.0", -- "v_bat": "25.3635", -- "bat_sta": 0, -- "usb_sta": 0, -- "imgres": 0, -- "wind_sw": 0, -- "cold_sw": 0, -- "coll_time": ["9-10", "10-10", "10-10"], -- "drop_time": 4, -- "set_temp": 32, -- "pre_temp": 25, -- "at": 0, -- "ah": 0, -- "rps": 0, -- "stamp": "20190802233308", -- "datt": 10, -- "staytime": 0, -- "cul_time": 0 -- } -- } function ToStringEx(value) if type(value)=='table' then return TableToStr(value) elseif type(value)=='string' then return "\'"..value.."\'" else return tostring(value) end end function TableToStr(t) if t == nil then return "" end local retstr= "{" local i = 1 for key,value in pairs(t) do local signal = "," if i==1 then signal = "" end if key == i then retstr = retstr..signal..ToStringEx(value) else if type(key)=='number' or type(key) == 'string' then retstr = retstr..signal..'['..ToStringEx(key).."]="..ToStringEx(value) else if type(key)=='userdata' then retstr = retstr..signal.."*s"..TableToStr(getmetatable(key)).."*e".."="..ToStringEx(value) else retstr = retstr..signal..key.."="..ToStringEx(value) end end end i = i+1 end retstr = retstr.."}" return retstr end --- 上传状态信息 function upStatus() local c, dat -- 设备上报状态表 local status = { work_sta = 0,-- 工作状态:0待机;1收集;2培养;3拍照; imei = "", -- 唯一ID iccid = "",-- SIM卡的iccid号 csq = 0, -- 信号强度 alti = 0,-- 海拔高度 lat = "34.000000",-- 纬度 lng = "113.00000",-- 经度 dtype = 7, -- 设备类型 on_off = 1,-- 设备开关 dver = "2.0.0", -- 设备固件版本 proj = "", -- 设备固件版本 v_bat = 0,-- 电压 bat_sta = 0,-- 电压状态 usb_sta = 0,-- 相机状态 imgres = 0,-- 分辨率 wind_sw = 1,-- 风机开关 0 关闭, 1 开启 cold_sw = 1, -- 制冷机开关 0 关闭, 1 开启 coll_time = '["9-10", "14-15"]',--采集开启和关闭时间 最多有10个 drop_time = 2,-- 滴液次数 set_temp = 25, -- 保温仓设定温度 pre_temp = 30,-- 保温仓当前温度 at = 25,-- 环境温度 ah = 40,-- 环境湿度 box_tem,-- 箱内温度 rps = 0, -- 雨控状态 1雨控,0正常, stamp = "20190801211805", datt = 10,-- 数据上传时间间隔 staytime = 0,-- 已培养时间 cul_time = 0,-- 设定培养时间 } audio.play('/ldata/dataupload.mp3') status.work_sta = hmi.hmista.work_sta status.imei = misc.getimei()-- 唯一ID status.iccid = string.upper(sim.geticcid())-- SIM卡的iccid status.csq = net.getRssi()-- 信号强度 status.alti = 0-- 海拔 local dat = agps.getLBS() log.info("UpData lbs is value:", dat) local cmds, result, err = json.decode(dat) if result then status.lat = cmds.result.lat status.lng = cmds.result.lng end status.dtype = 7 -- 设备类型 status.on_off = hmi.hmiconf.on_off status.dver = VERSION -- 设备固件版本 status.proj = PROJECT -- 设备固件版本 -- status.v_bat = hmi.hmista.vbat -- 电池电压 status.v_bat = string.gsub(hmi.hmista.vbat, '"', '') -- 电池电压 status.bat_sta = hmi.hmista.bat_sta -- 电池状态 status.usb_sta = hmi.hmista.usb_sta -- 相机状态 status.imgres = hmi.hmista.imgres -- 分辨率 status.wind_sw = hmi.hmista.wind_sw -- 抽风风机开关 status.cold_sw = hmi.hmiconf.cold_sw -- 制冷开关 status.coll_time = hmi.hmiconf.coll_time -- 收集时间段 status.drop_time = hmi.hmiconf.drop_time -- 滴液次数 status.set_temp = hmi.hmiconf.set_temp -- 设定的保温温度 status.pre_temp = hmi.hmista.pre_temp -- 当前保温仓温度 status.at = (hmi.hmista.envTem + 5) / 10 -- 环境温度 status.ah = (hmi.hmista.envHum + 5) / 10 -- 环境湿度 status.box_tem = string.gsub(hmi.hmista.box_tem, '"', '') -- 箱内温度 status.rps = hmi.hmista.rainStatus -- 雨控状态 c = misc.getClock() status.stamp = string.format('%04d%02d%02d%02d%02d%02d', c.year, c.month, c.day, c.hour, c.min, c.sec) status.datt = hmi.hmiconf.datt -- 上仓门状态 1打开 0关闭 status.staytime = hmi.hmista.staytime -- 已经培养的时间 status.cul_time = hmi.hmiconf.cul_time -- 加热状态 1加热 0停止 message.cmd = "status" message.ext = status dat = json.encode(message) log.info("upload status:", dat) return dat end --- 上传配置信息 function upNetconf(...) local c, dat -- 设备运行上报下发参数表 local netset = { mqtt = {}, ftp = { ip = "120.27.222.26", port = "8088", uid = "", pwd = "", }, } netset.mqtt = serverconf audio.play('/ldata/dataupload.mp3') netset.cmd = "netconf" dat = json.encode(netset) log.info("upload upNetconf:", dat) return dat end --- 上传配置信息 function upParamConf(...) local c, dat -- 设备运行上报下发参数表 local paramconf = { -- "wind_sw": 0, -- "coll_time": ["7-9", "10-11"], -- "set_temp": 25, -- "imgres": 0, -- "datt": 0, -- "drop_time": 0, -- "cul_time": 24 wind_sw = 0,--风机开关; cold_sw = 0,--制冷开关; coll_time = "", set_temp = 0, imgres = 0, datt = 0, drop_time = 0, cul_time = 0, } audio.play('/ldata/dataupload.mp3') paramconf.wind_sw = hmi.hmiconf.wind_sw--风机开关; paramconf.cold_sw = hmi.hmiconf.cold_sw -- 制冷开关 paramconf.coll_time = hmi.hmiconf.coll_time paramconf.set_temp = hmi.hmiconf.set_temp paramconf.imgres = hmi.hmiconf.imgres paramconf.datt = hmi.hmiconf.datt paramconf.drop_time = hmi.hmiconf.drop_time paramconf.cul_time = hmi.hmiconf.cul_time message.cmd = "paramconf" message.ext = paramconf dat = json.encode(message) log.info("upload paramconf:", dat) return dat end function setNetconf(dat) log.warn("--------setNetconf is running!!!") local cmds, result, err = json.decode(dat) if not result then log.error("setNetconf error!") end local str = json.encode(cmds) log.warn("set netconf is:-----------------:",str) io.writefile(NETCONF, str) audio.play('/ldata/save.mp3') end function ToStringEx(value) if type(value)=='table' then return TableToStr(value) elseif type(value)=='string' then return "\'"..value.."\'" else return tostring(value) end end function TableToStr(t) if t == nil then return "" end local retstr= "{" local i = 1 for key,value in pairs(t) do local signal = "," if i==1 then signal = "" end if key == i then retstr = retstr..signal..ToStringEx(value) else if type(key)=='number' or type(key) == 'string' then retstr = retstr..signal..'['..ToStringEx(key).."]="..ToStringEx(value) else if type(key)=='userdata' then retstr = retstr..signal.."*s"..TableToStr(getmetatable(key)).."*e".."="..ToStringEx(value) else retstr = retstr..signal..key.."="..ToStringEx(value) end end end i = i+1 end retstr = retstr.."}" return retstr end function setParamConf(dat) log.warn("--------setParamConf is running!!!") log.warn("dat:",dat) log.warn("type dat:",type(dat)) local cmds, result, err local status, error = pcall(function () cmds, result, err = json.decode(dat) if not result then log.error("setParamConf error!") end log.info("----------cmds.ext.wind_sw",cmds.ext.wind_sw) log.info("==========cmds.ext.coll_time",cmds.ext.coll_time) log.info("==========cmds.ext.set_temp",cmds.ext.set_temp) log.info("==========cmds.ext.imgres",cmds.ext.imgres) log.info("==========cmds.ext.datt",cmds.ext.datt) log.info("==========cmds.ext.drop_time",cmds.ext.drop_time) log.info("==========cmds.ext.cul_time",cmds.ext.cul_time) -- 参数检查: log.warn("cmds:",cmds) log.warn("type cmds:",type(cmds)) while true do -- for k, v in pairs(cmds) do for k, v in pairs(cmds.ext) do -- if v == nil then -- log.error(k .. "is:" .. v) -- break -- else -- log.warn(cmds.ext.k .. "is:" .. v) -- log.warn(cmds.ext.k .. "is:" .. v) -- end -- log.warn("cmds:",k,v) -- log.warn("cmds.ext:",k,v) log.warn("k is: " .. k .. " ;" .. " type cmds.ext.v: " ,type(v)) -- type(coll_time) is table!! -- if k ~= 'coll_time' and type(v) ~= number then -- error({code=121}) -- end if type(v) ~= "table" and type(v) ~= "string" and type(v) ~= "number" then log.error("k is: " .. k .. " ;" .. " type cmds.ext.v: " ,type(v)) error({code=1}) end -- if type(v) == "table" then -- log.error("k is: " .. k .. " ;" .. " type cmds.ext.v: " ,type(v)) -- -- local table_son = control.lua_string_split(TableToStr(v), "-") -- log.info("TableToStr(v):", TableToStr(v)) -- log.info("type TableToStr(v):", type(TableToStr(v))) -- log.info("string.gsub(TableToStr(v),' []{}'):", string.gsub(TableToStr(v),' {}','')) -- local table_son = control.lua_string_split(string.gsub(TableToStr(v),' {}',''), "-") -- -- string.gsub(coll_time_table[i], ' ', '') -- for i,j in pairs(table_son) do -- log.error("table_son i is: " .. i .. " ;" .. " table_son j: " ,j .. " ;" .. " type table_son j: " ,type(j)) -- -- table_son[k] = tonumber(table_son[k]) -- end -- -- error({code=121}) -- end end break end end) print("setParamConf status:",status) print("setParamConf error:",error) if status == true then log.warn("-----------status is true") hmi.hmiconf.wind_sw = cmds.ext.wind_sw hmi.hmiconf.coll_time = cmds.ext.coll_time hmi.hmiconf.set_temp = cmds.ext.set_temp hmi.hmiconf.imgres = cmds.ext.imgres hmi.hmiconf.datt = cmds.ext.datt hmi.hmiconf.drop_time = cmds.ext.drop_time hmi.hmiconf.cul_time = cmds.ext.cul_time log.info("==========hmi.hmiconf.wind_sw",hmi.hmiconf.wind_sw) log.info("==========hmi.hmiconf.coll_time",hmi.hmiconf.coll_time) log.info("==========hmi.hmiconf.set_temp",hmi.hmiconf.set_temp) log.info("==========hmi.hmiconf.imgres",hmi.hmiconf.imgres) log.info("==========hmi.hmiconf.datt",hmi.hmiconf.datt) log.info("==========hmi.hmiconf.drop_time",hmi.hmiconf.drop_time) log.info("==========hmi.hmiconf.cul_time",hmi.hmiconf.cul_time) -- local str = '{"cul_time":"12","vol":7,"datt":20,"coll_time":["1-2","11-12","12-12"],"drop_time":"1","cold_sw":1,"passWord":8888,"imgres":0,"thsp":300,"wind_sw":0,"set_temp":25}' local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) -- log.info('set paramconf is:',json.encode(dat)) -- log.info('new paramconf+++:',json.encode(hmi.hmiconf)) audio.play('/ldata/save.mp3') elseif status == false then log.warn("status is false") end end --- 下发HTTP服务器配置配置信息 function setHostconf(dat) local cmds, result, err = json.decode(dat) if not result then log.info("setHostconf set the parameter error!") end hostconf = cmds.ext io.writefile(HOST_CONF, dat) audio.play('/ldata/save.mp3') end --- 下发服务器配置信息 function setServerConf(dat) local cmds, result, err = json.decode(dat) if not result then log.info("setServerConf set the parameter error!") end serverconf = cmds.ext io.writefile(NETCONF, dat) audio.play('/ldata/save.mp3') end --- 开机获取用户配置的参数 function getConfig() local netconf, cmds, result, err photo_sw = io.readfile(TAKEPHOTO) if photo_sw == nil then photo_sw = 0 end netconf = io.readfile(NETCONF) log.warn("from NETCONF read netconf:",netconf) cmds, result, err = json.decode(netconf) if result then serverconf = cmds.mqtt end log.warn("from NETCONF read cmds.mqtt:",cmds.mqtt) end -- LED指示灯任务 sys.taskInit(function() pmd.ldoset(7, pmd.LDO_VMMC) local ledpin = pins.setup(pio.P0_10, 1) while true do -- GSM注册中 while not link.isReady() do led.blinkPwm(ledpin, 500, 500) sys.wait(100) end -- 网络附着中 while datalink == 0 do led.blinkPwm(ledpin, 1000, 200) sys.wait(100) end -- 服务器已链接 while datalink ~= 0 do -- 心跳包维持数据链接 if datalink == 1 then led.blinkPwm(ledpin, 200, 1000) -- 发送数据中 elseif datalink == 2 then led.blinkPwm(ledpin, 100, 100) end sys.wait(100) end sys.wait(1000) end end) sys.taskInit(function() sys.wait(3000) nvm.init("config.lua") -- 判断是否在mqtt1中启动喂狗;如果mqtt1连接云飞,则喂狗; if serverconf.ip == "120.27.222.26" or string.find(serverconf.ip, "yfzhwlw") ~= nil then log.error("***************one mqtt task!!!") else log.eror("****************two mqtt task!!!") end -- 开机即置1 dev_sta = 1 local cnt = hmi.hmiconf.datt * 60 getConfig() log.info('MQTT111 Task is start!') while not socket.isReady() do sys.wait(1000) end -- 创建MQTT客户端,客户端ID为IMEI号 willmsg.ext.imei = misc.getimei() local will = {qos = 1, retain = 0, topic = string.format(serverconf.lastwill .. misc.getimei()), payload = json.encode(willmsg)} local mqttc = mqtt.client(misc.getimei(), serverconf.keepalive, serverconf.uid, serverconf.pwd, 1,will) local pub = string.format(serverconf.pub .. misc.getimei()) local sub = string.format(serverconf.sub .. misc.getimei()) while true do while not mqttc:connect(serverconf.ip, serverconf.port) do sys.wait(1000) end -- 初始化订阅主题 datalink = 1 -- 数据指示常亮等待数据 if mqttc:subscribe(sub, serverconf.qos) then if dev_sta == 1 then -- 开机或重启即上传一次 dev_sta 为 'turnon': -- {"cmd":"warn","ext":{"status":"turnon","type":"dev_sta"}} mqttc:publish(pub, upwarn("dev_sta","turnon:" .. rtos.poweron_reason() .. "; mqtt1_disconntct:" .. nvm.get("mqtt1_disconntct")), serverconf.qos) dev_sta = 0 elseif dev_sta == 2 then -- 掉线重连 上传一次 dev_sta 为 'relink': -- {"cmd":"warn","ext":{"status":"relink","type":"dev_sta"}} mqttc:publish(pub, upwarn("dev_sta","relink"), serverconf.qos) dev_sta = 0 end while true do cnt = cnt + 10 if cnt > tonumber(hmi.hmiconf.datt) * 60 then -- 推状态送消息 datalink = 2 -- 数据发送指示快速闪烁 if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end if not mqttc:publish(pub, upParamConf(), serverconf.qos) then break end log.info('upload is done!') cnt = 0 end datalink = 1 -- 数据指示灯常亮等待发送 if update.uptate_ok ~= 0 then audio.play('/ldata/alarm.mp3') log.warn('======================= update is ok!!!') if not mqttc:publish(pub, upwarn("bzy_update",update.uptate_ok), serverconf.qos) then break end update.uptate_ok = 0 end --haikang.photo_flag = 1 if haikang.photo_flag ~= 0 then log.warn('======================= take photo is ok!!!') -- if not mqttc:publish(pub, upwarn("bzy take photo ok!" .. "; photo num:" .. haikang.photo_num .. "; step num:" .. haikang.step,"ok"), serverconf.qos) then break end -- if not mqttc:publish(pub, upwarn("bzy take photo ok!" .. "; photo num:" .. haikang.photo_num .. "; step num:" .. haikang.step,"ok"), serverconf.qos) then break end local message = {cmd = "", ext = {}} local data = { photo_num = haikang.photo_num, step_num = haikang.step, } message.cmd = "photo" message.ext = data log.warn('=======================',json.encode(message)) if not mqttc:publish(pub, json.encode(message), serverconf.qos) then break end haikang.photo_flag = 0 haikang.step = 0 haikang.photo_num = 0 end if control.turn_reset_timeout ~= 0 then if not mqttc:publish(pub, upwarn("turn_reset_timeout:",control.turn_reset_timeout), serverconf.qos) then break end control.turn_reset_timeout = 0 end if control.turn_timeout ~= 0 then if not mqttc:publish(pub, upwarn("turn_timeout:",control.turn_timeout), serverconf.qos) then break end control.turn_timeout = 0 end -- 处理服务器的下发数据请求 local r, packet = mqttc:receive(10000)-- 处理服务器下发指令 if r then -- 这里是有数据下发的处理 datalink = 2 -- 数据接收指示灯快闪 local cnf, result, err = json.decode(packet.payload) if result and cnf.cmd == 'read' then if cnf.type == 'status' then if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end elseif cnf.type == 'netconf' then if not mqttc:publish(pub, upNetconf(), serverconf.qos) then break end -- 此处为兼容老设备,下发时cmd为paramconf 则上传时,需要区别一下:故cmd取param elseif cnf.type == 'param' then if not mqttc:publish(pub, upParamConf(), serverconf.qos) then break end end elseif result and cnf.cmd == 'netset' then setNetconf(packet.payload) -- 此处为兼容老设备,下发时cmd为paramconf 上传时,cmd取param -- elseif result and cnf.cmd == 'paramset' then elseif result and cnf.cmd == 'paramconf' then setParamConf(packet.payload) elseif result and cnf.cmd == 'serverconf' then setServerConf(packet.payload) elseif result and cnf.cmd == "reboot" then if not mqttc:publish(pub, upres("system will restart","ok"), serverconf.qos) then break end sys.restart("Server remote restart.") elseif result and cnf.cmd == "update" then update.run() if not mqttc:publish(pub, upwarn("bzy update is start","ok"), serverconf.qos) then break end log.info("Server remote update done!") elseif result and cnf.cmd == "set_photo_step" then nvm.set("photo_step", cnf.ext) if not mqttc:publish(pub, upwarn("set_photo_step",nvm.get("photo_step")), serverconf.qos) then break end elseif result and cnf.cmd == "get_photo_step" then if not mqttc:publish(pub, upwarn("get_photo_step",nvm.get("photo_step")), serverconf.qos) then break end elseif result and cnf.cmd == "poweroff" then hmi.hmiconf.on_off = 0 local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) if not mqttc:publish(pub, upres("poweroff","ok"), serverconf.qos) then break end if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end elseif result and cnf.cmd == "poweron" then hmi.hmiconf.on_off = 1 local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) if not mqttc:publish(pub, upres("poweron","ok"), serverconf.qos) then break end if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end elseif result and cnf.cmd == "coldoff" then hmi.hmiconf.cold_sw = 0 local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) if not mqttc:publish(pub, upwarn("coldoff","ok"), serverconf.qos) then break end elseif result and cnf.cmd == "coldon" then hmi.hmiconf.cold_sw = 1 local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) if not mqttc:publish(pub, upwarn("coldon","ok"), serverconf.qos) then break end elseif result and cnf.cmd == "photo" then photosw(cnf.ext.ws) if not mqttc:publish(pub, upres("timer photo status",photo_sw), serverconf.qos) then break end -- 远程控制: elseif result and cnf.cmd == "ctrl" then -- 远程拍照: if cnf.ext.type == 'takephoto' then haikang.test_takephoto() if not mqttc:publish(pub, upwarn("bzy test takephoto cmd send","ok"), yfmqtt.qos) then break end -- 远程控制对焦拍照: elseif cnf.ext.type == 'auto_takephoto' then hmi.remote_auto_pic() if not mqttc:publish(pub, upwarn("bzy auto takephoto cmd send","ok"), yfmqtt.qos) then break end -- 转盘操作: elseif cnf.ext.type == 'turn' then control.turn() if not mqttc:publish(pub, upres("turn","ok"), serverconf.qos) then break end end end elseif packet == 'timeout' then -- 服务器下发指令超时处理 datalink = 1 -- 等待数据指示灯常亮 -- 只往云飞平台传数据时,启动喂狗;如果此task为对接到用户的平台,则不喂狗,即保证云飞mqtt任务的连接:即,如果云飞mqtt任务不喂狗,系统会重启; control.wdg() log.info('MqttServer111 recv is timeout') else log.info('The MqttServer111 connection is broken.') break end datalink = 1 -- 数据指示灯常亮等待发送 end end mqttc:disconnect() -- 发布平台mqtt连接断开!如果对接外部平台,则在云飞mqtt任务中,预警mqtt1的断开!! sys.publish("MQTT1_DISCONNECT") -- 断开连接即 设备即将重连网络,即置2,等网络重连成功,则会上报 曾掉线重连网络过。 dev_sta = 2 datalink = 0 -- 服务器断开链接数据指示灯慢闪 sys.wait(1000) end end) --- 上传响应信息 function upres(c_type,c_status) local dat -- 设备上报数据表 local data = { type = c_type, status = c_status, } audio.play('/ldata/dataupload.mp3') message.cmd = "control" message.ext = data dat = json.encode(message) log.info("upload upres:", dat) return dat end --- 上传预警信息 -- t:type -- s:status function upwarn(t,s) -- log.info("------------------------t,:",t) -- log.info("------------------------s,:",s) local dat -- 设备上报数据表 local data = { type = t, status = s, } message.cmd = "warn" message.ext = data dat = json.encode(message) log.info("upload warn:", dat) return dat end function photo() local dat -- 设备上报数据表 local data = { type = t, status = s, } message.cmd = "warn" message.ext = data dat = json.encode(message) log.info("upload warn:", dat) return dat end ----------------------------云飞mqtt上传任务:---------------------------- -- 云飞MQTT服务器配置表 yfmqtt = { ip = "120.27.222.26",-- 云飞 port = 1883, sub = "/yfkj/bzy/s2c/", pub = "/yfkj/bzy/c2s/", keepalive = 60, lastwill = "/yfkj/bzy/offline/", uid = "", pwd = "", qos = 0, } -- mqtt1的连接状态:0正常;1异常; local mqtt1_sta = 0 function mqtt1_disconntct() nvm.set("mqtt1_disconntct",nvm.get("mqtt1_disconntct")+1) if nvm.get("mqtt1_disconntct") >= 100000000 then nvm.set("mqtt1_disconntct",0) end -- 状态置1表示异常; mqtt1_sta = 1 end sys.taskInit(function() sys.wait(3000) sys.subscribe("MQTT1_DISCONNECT",mqtt1_disconntct) -- 开机即置1 dev_sta = 1 -- 判断 serverconf log.info("yunfei mqtt ===================!!!") if serverconf.ip == "120.27.222.26" then log.info("serverconf.ip = 120.27.222.26") else log.info("serverconf.ip ~= 120.27.222.26") end if string.find(serverconf.ip, "yfzhwlw") ~= nil then log.info("serverconf.ip include yfzhwlw") else log.info("serverconf.ip not include yfzhwlw") end if serverconf.ip == "120.27.222.26" or string.find(serverconf.ip, "yfzhwlw") ~= nil then log.info("yunfei mqtt end!!!") return else log.info("yunfei mqtt start running!!!") end local cnt = hmi.hmiconf.datt * 60 getConfig() log.info('MQTT222 Task is start!') while not socket.isReady() do sys.wait(1000) end -- 创建MQTT客户端,客户端ID为IMEI号 willmsg.ext.imei = misc.getimei() local will = {qos = 1, retain = 0, topic = string.format(yfmqtt.lastwill .. misc.getimei()), payload = json.encode(willmsg)} local mqttc = mqtt.client(misc.getimei(), yfmqtt.keepalive, yfmqtt.uid, yfmqtt.pwd, 1,will) local pub = string.format(yfmqtt.pub .. misc.getimei()) local sub = string.format(yfmqtt.sub .. misc.getimei()) while true do while not mqttc:connect(yfmqtt.ip, yfmqtt.port) do sys.wait(1000) end -- 初始化订阅主题 datalink = 1 -- 数据指示常亮等待数据 if mqttc:subscribe(sub, yfmqtt.qos) then if dev_sta == 1 then -- 开机或重启即上传一次 dev_sta 为 'turnon': -- {"cmd":"warn","ext":{"status":"turnon","type":"dev_sta"}} mqttc:publish(pub, upwarn("dev_sta","turnon:" .. rtos.poweron_reason() .. "mqtt1_disconntct:" .. nvm.get("mqtt1_disconntct")), yfmqtt.qos) dev_sta = 0 elseif dev_sta == 2 then -- 掉线重连 上传一次 dev_sta 为 'relink': -- {"cmd":"warn","ext":{"status":"relink","type":"dev_sta"}} mqttc:publish(pub, upwarn("dev_sta","relink"), yfmqtt.qos) dev_sta = 0 end while true do cnt = cnt + 10 if cnt > tonumber(hmi.hmiconf.datt) * 60 then -- 推状态送消息 datalink = 2 -- 数据发送指示快速闪烁 -- audio.play('/ldata/upload.mp3') if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end -- if not mqttc:publish(pub, upData(), yfmqtt.qos) then break end log.info('upload is done!') cnt = 0 end datalink = 1 -- 数据指示灯常亮等待发送 --------- mqtt1连接异常 ---------1表断开连接; if mqtt1_sta ~= 0 then log.warn('======================= mqtt1_sta:',mqtt1_sta) if not mqttc:publish(pub, upwarn("mqtt1_sta",mqtt1_sta), yfmqtt.qos) then break end mqtt1_sta = 0 end if update.uptate_ok ~= 0 then log.warn('======================= update is ok!!!') if not mqttc:publish(pub, upwarn("bzy_update",update.uptate_ok), yfmqtt.qos) then break end update.uptate_ok = 0 end -- 处理服务器的下发数据请求 local r, packet = mqttc:receive(10000)-- 处理服务器下发指令 if r then -- 这里是有数据下发的处理 datalink = 2 -- 数据接收指示灯快闪 local cnf, result, err = json.decode(packet.payload) if result and cnf.cmd == 'read' then if cnf.type == 'status' then if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end elseif cnf.type == 'paramconf' then if not mqttc:publish(pub, upParamConf(), yfmqtt.qos) then break end elseif cnf.type == 'serverconf' then if not mqttc:publish(pub, upServerConf(), yfmqtt.qos) then break end elseif cnf.ext.type == 'hostconf' then if not mqttc:publish(pub, upHostConf(), yfmqtt.qos) then break end end elseif result and cnf.cmd == 'paramconf' then setParamConf(packet.payload) elseif result and cnf.cmd == 'hostconf' then setHostconf(packet.payload) elseif result and cnf.cmd == 'serverconf' then setServerConf(packet.payload) elseif result and cnf.cmd == "set_photo_step" then nvm.set("photo_step", cnf.ext) if not mqttc:publish(pub, upwarn("set_photo_step",nvm.get("photo_step")), yfmqtt.qos) then break end elseif result and cnf.cmd == "get_photo_step" then if not mqttc:publish(pub, upwarn("get_photo_step",nvm.get("photo_step")), yfmqtt.qos) then break end elseif result and cnf.cmd == "poweroff" then hmi.hmiconf.on_off = 0 local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) if not mqttc:publish(pub, upres("poweroff","ok"), yfmqtt.qos) then break end if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end elseif result and cnf.cmd == "poweron" then hmi.hmiconf.on_off = 1 local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) if not mqttc:publish(pub, upres("poweron","ok"), yfmqtt.qos) then break end if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end elseif result and cnf.cmd == "coldoff" then hmi.hmiconf.cold_sw = 0 local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) if not mqttc:publish(pub, upwarn("coldoff","ok"), yfmqtt.qos) then break end if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end elseif result and cnf.cmd == "coldon" then hmi.hmiconf.cold_sw = 1 local str = json.encode(hmi.hmiconf) log.info('will write configfile is:',str) io.writefile(hmi.HMI_FILE, str) if not mqttc:publish(pub, upwarn("coldon","ok"), yfmqtt.qos) then break end if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end elseif result and cnf.cmd == "reboot" then if not mqttc:publish(pub, upres("system will restart","ok"), yfmqtt.qos) then break end sys.restart("Server remote restart.") elseif result and cnf.cmd == "update" then update.run() if not mqttc:publish(pub, upres("update is start","ok"), yfmqtt.qos) then break end log.info("Server remote update done!") elseif result and cnf.cmd == "photo" then photosw(cnf.ext.ws) if not mqttc:publish(pub, upres("timer photo status",photo_sw), yfmqtt.qos) then break end -- 远程控制: elseif result and cnf.cmd == "ctrl" then -- 远程拍照: if cnf.ext.type == 'takephoto' then haikang.test_takephoto() if not mqttc:publish(pub, upwarn("bzy test takephoto cmd send","ok"), yfmqtt.qos) then break end -- 远程控制对焦拍照: elseif cnf.ext.type == 'auto_takephoto' then hmi.remote_auto_pic() if not mqttc:publish(pub, upwarn("bzy auto takephoto cmd send","ok"), yfmqtt.qos) then break end -- 转盘操作: elseif cnf.ext.type == 'turn' then control.turn() if not mqttc:publish(pub, upres("turn","ok"), yfmqtt.qos) then break end end end elseif packet == 'timeout' then -- 服务器下发指令超时处理 datalink = 1 -- 等待数据指示灯常亮 control.wdg() log.info('MqttServer222 recv is timeout') else log.info('The MqttServer222 connection is broken.') break end datalink = 1 -- 数据指示灯常亮等待发送 end end mqttc:disconnect() -- 断开连接即 设备即将重连网络,即置2,等网络重连成功,则会上报 曾掉线重连网络过。 dev_sta = 2 datalink = 0 -- 服务器断开链接数据指示灯慢闪 sys.wait(1000) end end) -- 网络状况监控任务: -- sys.taskInit(function() -- nvm.init("config.lua") -- local err = 0 -- -- 等待设备联网: -- -- 两分钟后启动; -- sys.wait(120000) -- -- sys.wait(40000) -- -- nvm.set("socket_err",0) -- log.error("===config.socket_err",nvm.get("socket_err")) -- -- log.error("===config.wdg_err",nvm.get("wdg_err")) -- log.warn("***************socket monitor task is running!***************") -- while true do -- while not socket.isReady() do -- log.warn('socket is not Ready,','err:',err) -- err = err + 1 -- if err >= 90 then -- -- if err >= 5 then -- --参数+1并赋值,立即写入文件系统, -- nvm.set("socket_err",nvm.get("socket_err")+1) -- -- nvm.set("wdg_err",nvm.get("wdg_err")+1) -- log.error("config.socket_err",nvm.get("socket_err")) -- -- control.stop_all_move() -- -- control.stop_all_move() -- sys.restart("socket connect err overtime:90!!!") -- end -- sys.wait(1000) -- end -- if socket.isReady() then -- log.info('***socket is Ready!!!') -- err = 0 -- end -- sys.wait(5000) -- end -- end) sys.taskInit(function() local cnow while true do cnow = misc.getClock() -- log.warn("time tast print >> now time:" .. os.date("%Y%m%d%H%M%S",os.time(cnow))) if cnow.hour == 9 and cnow.min == 0 and cnow.sec == 0 and photo_sw == 0 then -- if cnow.hour == 14 and cnow.min == 40 and cnow.sec == 01 then log.error("timephoto!!! time is" .. os.date("%Y%m%d%H%M%S",os.time(cnow))) haikang.test_takephoto() sys.wait(15000) haikang.http_chose_photo_task() end -- log.warn("free space is",rtos.get_fs_free_size()) sys.wait(1000) end end) function photosw(sw) if not sw then return end sw = tonumber(sw) if sw < 2 then photo_sw = sw io.writefile(TAKEPHOTO,photo_sw) end end -- sys.taskInit(function() -- while true do -- -- local url = "http://yfzhwlw.com/test" -- local url = "http://yfznscd.com/test" -- local param = { -- imei="", -- } -- while not socket.isReady() do sys.waitUntil('IP_READY_IND') end -- param.imei = misc.getimei()-- 唯一ID -- log.error("#################### type param is:",type(param)) -- local code, head, body = http.request("POST", url, 5000,nil,param) -- log.error("#################### http code is:",code) -- log.error("#################### http body is:",body) -- -- local cnt = 1 -- -- for cnt = 1, 3 do -- -- while not socket.isReady() do sys.waitUntil('IP_READY_IND') end -- -- -- while not socket.isReady() do sys.wait(2000) end -- -- local code, head, body = http.request("GET", url, 5000) -- -- log.error("#################### http code is:",code) -- -- end -- sys.wait(10000) -- end -- end)