iot.lua 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. --- 孢子仪mqtt联网模块
  2. -- @module
  3. -- @author lcg
  4. -- @release 2019.08.01
  5. require 'sys'
  6. require 'hmi'
  7. require 'audio'
  8. require "mqtt"
  9. require "led"
  10. require "utils"
  11. require "agps"
  12. require "update"
  13. require "control"
  14. require "sim"
  15. require "config"
  16. require "nvm"
  17. module(..., package.seeall)
  18. -- 指示设备状态标志位:开机重启、掉线重连
  19. dev_sta = 0
  20. -- 本地存储文件
  21. local DEVICE_CONF = "/device.conf"
  22. local HOST_CONF = "/host.conf"
  23. local SERVER_CONF = "/server.conf"
  24. local PARAMCONF = "/paramconf.conf"
  25. local NETCONF = "/netconf.conf"
  26. local TAKEPHOTO = "/photo.conf"
  27. --定时拍照开关,0-开,1-关
  28. local photo_sw = 0
  29. -- 上报json数据的基础表
  30. local message = {cmd = "", ext = {}}
  31. -- 上报遗言的json表
  32. local willmsg = {cmd = 'offline', ext = {imei = ''}}
  33. -- 服务器上报数据间隔时长,间隔期间用于阻塞读取服务器下发的指令
  34. -- hmi.hmiconf.datt 和下面的timeout 功能一样
  35. -- local timeout = 10 * 60 * 1000
  36. -- MQTT服务器配置表
  37. serverconf = {
  38. ip = "120.27.222.26",-- 云飞
  39. -- ip = "39.104.94.153",-- 云飞
  40. port = 1883,
  41. sub = "/yfkj/bzy/s2c/",
  42. pub = "/yfkj/bzy/c2s/",
  43. keepalive = 60,
  44. lastwill = "/yfkj/bzy/offline/",
  45. uid = "",
  46. pwd = "",
  47. qos = 0,
  48. }
  49. -- HTTP服务器配置表
  50. hostconf = {
  51. url = "http://120.27.222.26/update",-- 云飞
  52. length = 0,
  53. username = "",
  54. password = "",
  55. }
  56. -- 上传的数据格式:
  57. -- {
  58. -- "cmd": "status",
  59. -- "ext": {
  60. -- "imei": "866262042555598",
  61. -- "iccid": "89860411101871387773",
  62. -- "csq": 23,
  63. -- "alti": 0,
  64. -- "lat": "",
  65. -- "lng": "",
  66. -- "dtype": 7,
  67. -- "on_off": 0,
  68. -- "dver": "1.0.0",
  69. -- "v_bat": "25.3635",
  70. -- "bat_sta": 0,
  71. -- "usb_sta": 0,
  72. -- "imgres": 0,
  73. -- "wind_sw": 0,
  74. -- "cold_sw": 0,
  75. -- "coll_time": ["9-10", "10-10", "10-10"],
  76. -- "drop_time": 4,
  77. -- "set_temp": 32,
  78. -- "pre_temp": 25,
  79. -- "at": 0,
  80. -- "ah": 0,
  81. -- "rps": 0,
  82. -- "stamp": "20190802233308",
  83. -- "datt": 10,
  84. -- "staytime": 0,
  85. -- "cul_time": 0
  86. -- }
  87. -- }
  88. function ToStringEx(value)
  89. if type(value)=='table' then
  90. return TableToStr(value)
  91. elseif type(value)=='string' then
  92. return "\'"..value.."\'"
  93. else
  94. return tostring(value)
  95. end
  96. end
  97. function TableToStr(t)
  98. if t == nil then return "" end
  99. local retstr= "{"
  100. local i = 1
  101. for key,value in pairs(t) do
  102. local signal = ","
  103. if i==1 then
  104. signal = ""
  105. end
  106. if key == i then
  107. retstr = retstr..signal..ToStringEx(value)
  108. else
  109. if type(key)=='number' or type(key) == 'string' then
  110. retstr = retstr..signal..'['..ToStringEx(key).."]="..ToStringEx(value)
  111. else
  112. if type(key)=='userdata' then
  113. retstr = retstr..signal.."*s"..TableToStr(getmetatable(key)).."*e".."="..ToStringEx(value)
  114. else
  115. retstr = retstr..signal..key.."="..ToStringEx(value)
  116. end
  117. end
  118. end
  119. i = i+1
  120. end
  121. retstr = retstr.."}"
  122. return retstr
  123. end
  124. --- 上传状态信息
  125. function upStatus()
  126. local c, dat
  127. -- 设备上报状态表
  128. local status = {
  129. work_sta = 0,-- 工作状态:0待机;1收集;2培养;3拍照;
  130. imei = "", -- 唯一ID
  131. iccid = "",-- SIM卡的iccid号
  132. csq = 0, -- 信号强度
  133. alti = 0,-- 海拔高度
  134. lat = "34.000000",-- 纬度
  135. lng = "113.00000",-- 经度
  136. dtype = 7, -- 设备类型
  137. on_off = 1,-- 设备开关
  138. dver = "2.0.0", -- 设备固件版本
  139. proj = "", -- 设备固件版本
  140. v_bat = 0,-- 电压
  141. bat_sta = 0,-- 电压状态
  142. usb_sta = 0,-- 相机状态
  143. imgres = 0,-- 分辨率
  144. wind_sw = 1,-- 风机开关 0 关闭, 1 开启
  145. cold_sw = 1, -- 制冷机开关 0 关闭, 1 开启
  146. coll_time = '["9-10", "14-15"]',--采集开启和关闭时间 最多有10个
  147. drop_time = 2,-- 滴液次数
  148. set_temp = 25, -- 保温仓设定温度
  149. pre_temp = 30,-- 保温仓当前温度
  150. at = 25,-- 环境温度
  151. ah = 40,-- 环境湿度
  152. box_tem,-- 箱内温度
  153. rps = 0, -- 雨控状态 1雨控,0正常,
  154. stamp = "20190801211805",
  155. datt = 10,-- 数据上传时间间隔
  156. staytime = 0,-- 已培养时间
  157. cul_time = 0,-- 设定培养时间
  158. }
  159. audio.play('/ldata/dataupload.mp3')
  160. status.work_sta = hmi.hmista.work_sta
  161. status.imei = misc.getimei()-- 唯一ID
  162. status.iccid = string.upper(sim.geticcid())-- SIM卡的iccid
  163. status.csq = net.getRssi()-- 信号强度
  164. status.alti = 0-- 海拔
  165. local dat = agps.getLBS()
  166. log.info("UpData lbs is value:", dat)
  167. local cmds, result, err = json.decode(dat)
  168. if result then
  169. status.lat = cmds.result.lat
  170. status.lng = cmds.result.lng
  171. end
  172. status.dtype = 7 -- 设备类型
  173. status.on_off = hmi.hmiconf.on_off
  174. status.dver = VERSION -- 设备固件版本
  175. status.proj = PROJECT -- 设备固件版本
  176. -- status.v_bat = hmi.hmista.vbat -- 电池电压
  177. status.v_bat = string.gsub(hmi.hmista.vbat, '"', '') -- 电池电压
  178. status.bat_sta = hmi.hmista.bat_sta -- 电池状态
  179. status.usb_sta = hmi.hmista.usb_sta -- 相机状态
  180. status.imgres = hmi.hmista.imgres -- 分辨率
  181. status.wind_sw = hmi.hmista.wind_sw -- 抽风风机开关
  182. status.cold_sw = hmi.hmiconf.cold_sw -- 制冷开关
  183. status.coll_time = hmi.hmiconf.coll_time -- 收集时间段
  184. status.drop_time = hmi.hmiconf.drop_time -- 滴液次数
  185. status.set_temp = hmi.hmiconf.set_temp -- 设定的保温温度
  186. status.pre_temp = hmi.hmista.pre_temp -- 当前保温仓温度
  187. status.at = (hmi.hmista.envTem + 5) / 10 -- 环境温度
  188. status.ah = (hmi.hmista.envHum + 5) / 10 -- 环境湿度
  189. status.box_tem = string.gsub(hmi.hmista.box_tem, '"', '') -- 箱内温度
  190. status.rps = hmi.hmista.rainStatus -- 雨控状态
  191. c = misc.getClock()
  192. status.stamp = string.format('%04d%02d%02d%02d%02d%02d', c.year, c.month, c.day, c.hour, c.min, c.sec)
  193. status.datt = hmi.hmiconf.datt -- 上仓门状态 1打开 0关闭
  194. status.staytime = hmi.hmista.staytime -- 已经培养的时间
  195. status.cul_time = hmi.hmiconf.cul_time -- 加热状态 1加热 0停止
  196. message.cmd = "status"
  197. message.ext = status
  198. dat = json.encode(message)
  199. log.info("upload status:", dat)
  200. return dat
  201. end
  202. --- 上传配置信息
  203. function upNetconf(...)
  204. local c, dat
  205. -- 设备运行上报下发参数表
  206. local netset = {
  207. mqtt = {},
  208. ftp = {
  209. ip = "120.27.222.26",
  210. port = "8088",
  211. uid = "",
  212. pwd = "",
  213. },
  214. }
  215. netset.mqtt = serverconf
  216. audio.play('/ldata/dataupload.mp3')
  217. netset.cmd = "netconf"
  218. dat = json.encode(netset)
  219. log.info("upload upNetconf:", dat)
  220. return dat
  221. end
  222. --- 上传配置信息
  223. function upParamConf(...)
  224. local c, dat
  225. -- 设备运行上报下发参数表
  226. local paramconf = {
  227. -- "wind_sw": 0,
  228. -- "coll_time": ["7-9", "10-11"],
  229. -- "set_temp": 25,
  230. -- "imgres": 0,
  231. -- "datt": 0,
  232. -- "drop_time": 0,
  233. -- "cul_time": 24
  234. wind_sw = 0,--风机开关;
  235. cold_sw = 0,--制冷开关;
  236. coll_time = "",
  237. set_temp = 0,
  238. imgres = 0,
  239. datt = 0,
  240. drop_time = 0,
  241. cul_time = 0,
  242. }
  243. audio.play('/ldata/dataupload.mp3')
  244. paramconf.wind_sw = hmi.hmiconf.wind_sw--风机开关;
  245. paramconf.cold_sw = hmi.hmiconf.cold_sw -- 制冷开关
  246. paramconf.coll_time = hmi.hmiconf.coll_time
  247. paramconf.set_temp = hmi.hmiconf.set_temp
  248. paramconf.imgres = hmi.hmiconf.imgres
  249. paramconf.datt = hmi.hmiconf.datt
  250. paramconf.drop_time = hmi.hmiconf.drop_time
  251. paramconf.cul_time = hmi.hmiconf.cul_time
  252. message.cmd = "paramconf"
  253. message.ext = paramconf
  254. dat = json.encode(message)
  255. log.info("upload paramconf:", dat)
  256. return dat
  257. end
  258. function setNetconf(dat)
  259. log.warn("--------setNetconf is running!!!")
  260. local cmds, result, err = json.decode(dat)
  261. if not result then log.error("setNetconf error!") end
  262. local str = json.encode(cmds)
  263. log.warn("set netconf is:-----------------:",str)
  264. io.writefile(NETCONF, str)
  265. audio.play('/ldata/save.mp3')
  266. end
  267. function ToStringEx(value)
  268. if type(value)=='table' then
  269. return TableToStr(value)
  270. elseif type(value)=='string' then
  271. return "\'"..value.."\'"
  272. else
  273. return tostring(value)
  274. end
  275. end
  276. function TableToStr(t)
  277. if t == nil then return "" end
  278. local retstr= "{"
  279. local i = 1
  280. for key,value in pairs(t) do
  281. local signal = ","
  282. if i==1 then
  283. signal = ""
  284. end
  285. if key == i then
  286. retstr = retstr..signal..ToStringEx(value)
  287. else
  288. if type(key)=='number' or type(key) == 'string' then
  289. retstr = retstr..signal..'['..ToStringEx(key).."]="..ToStringEx(value)
  290. else
  291. if type(key)=='userdata' then
  292. retstr = retstr..signal.."*s"..TableToStr(getmetatable(key)).."*e".."="..ToStringEx(value)
  293. else
  294. retstr = retstr..signal..key.."="..ToStringEx(value)
  295. end
  296. end
  297. end
  298. i = i+1
  299. end
  300. retstr = retstr.."}"
  301. return retstr
  302. end
  303. function setParamConf(dat)
  304. log.warn("--------setParamConf is running!!!")
  305. log.warn("dat:",dat)
  306. log.warn("type dat:",type(dat))
  307. local cmds, result, err
  308. local status, error = pcall(function ()
  309. cmds, result, err = json.decode(dat)
  310. if not result then log.error("setParamConf error!") end
  311. log.info("----------cmds.ext.wind_sw",cmds.ext.wind_sw)
  312. log.info("==========cmds.ext.coll_time",cmds.ext.coll_time)
  313. log.info("==========cmds.ext.set_temp",cmds.ext.set_temp)
  314. log.info("==========cmds.ext.imgres",cmds.ext.imgres)
  315. log.info("==========cmds.ext.datt",cmds.ext.datt)
  316. log.info("==========cmds.ext.drop_time",cmds.ext.drop_time)
  317. log.info("==========cmds.ext.cul_time",cmds.ext.cul_time)
  318. -- 参数检查:
  319. log.warn("cmds:",cmds)
  320. log.warn("type cmds:",type(cmds))
  321. while true do
  322. -- for k, v in pairs(cmds) do
  323. for k, v in pairs(cmds.ext) do
  324. -- if v == nil then
  325. -- log.error(k .. "is:" .. v)
  326. -- break
  327. -- else
  328. -- log.warn(cmds.ext.k .. "is:" .. v)
  329. -- log.warn(cmds.ext.k .. "is:" .. v)
  330. -- end
  331. -- log.warn("cmds:",k,v)
  332. -- log.warn("cmds.ext:",k,v)
  333. log.warn("k is: " .. k .. " ;" .. " type cmds.ext.v: " ,type(v))
  334. -- type(coll_time) is table!!
  335. -- if k ~= 'coll_time' and type(v) ~= number then
  336. -- error({code=121})
  337. -- end
  338. if type(v) ~= "table" and type(v) ~= "string" and type(v) ~= "number" then
  339. log.error("k is: " .. k .. " ;" .. " type cmds.ext.v: " ,type(v))
  340. error({code=1})
  341. end
  342. -- if type(v) == "table" then
  343. -- log.error("k is: " .. k .. " ;" .. " type cmds.ext.v: " ,type(v))
  344. -- -- local table_son = control.lua_string_split(TableToStr(v), "-")
  345. -- log.info("TableToStr(v):", TableToStr(v))
  346. -- log.info("type TableToStr(v):", type(TableToStr(v)))
  347. -- log.info("string.gsub(TableToStr(v),' []{}'):", string.gsub(TableToStr(v),' {}',''))
  348. -- local table_son = control.lua_string_split(string.gsub(TableToStr(v),' {}',''), "-")
  349. -- -- string.gsub(coll_time_table[i], ' ', '')
  350. -- for i,j in pairs(table_son) do
  351. -- log.error("table_son i is: " .. i .. " ;" .. " table_son j: " ,j .. " ;" .. " type table_son j: " ,type(j))
  352. -- -- table_son[k] = tonumber(table_son[k])
  353. -- end
  354. -- -- error({code=121})
  355. -- end
  356. end
  357. break
  358. end
  359. end)
  360. print("setParamConf status:",status)
  361. print("setParamConf error:",error)
  362. if status == true then
  363. log.warn("-----------status is true")
  364. hmi.hmiconf.wind_sw = cmds.ext.wind_sw
  365. hmi.hmiconf.coll_time = cmds.ext.coll_time
  366. hmi.hmiconf.set_temp = cmds.ext.set_temp
  367. hmi.hmiconf.imgres = cmds.ext.imgres
  368. hmi.hmiconf.datt = cmds.ext.datt
  369. hmi.hmiconf.drop_time = cmds.ext.drop_time
  370. hmi.hmiconf.cul_time = cmds.ext.cul_time
  371. log.info("==========hmi.hmiconf.wind_sw",hmi.hmiconf.wind_sw)
  372. log.info("==========hmi.hmiconf.coll_time",hmi.hmiconf.coll_time)
  373. log.info("==========hmi.hmiconf.set_temp",hmi.hmiconf.set_temp)
  374. log.info("==========hmi.hmiconf.imgres",hmi.hmiconf.imgres)
  375. log.info("==========hmi.hmiconf.datt",hmi.hmiconf.datt)
  376. log.info("==========hmi.hmiconf.drop_time",hmi.hmiconf.drop_time)
  377. log.info("==========hmi.hmiconf.cul_time",hmi.hmiconf.cul_time)
  378. -- 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}'
  379. local str = json.encode(hmi.hmiconf)
  380. log.info('will write configfile is:',str)
  381. io.writefile(hmi.HMI_FILE, str)
  382. -- log.info('set paramconf is:',json.encode(dat))
  383. -- log.info('new paramconf+++:',json.encode(hmi.hmiconf))
  384. audio.play('/ldata/save.mp3')
  385. elseif status == false then
  386. log.warn("status is false")
  387. end
  388. end
  389. --- 下发HTTP服务器配置配置信息
  390. function setHostconf(dat)
  391. local cmds, result, err = json.decode(dat)
  392. if not result then log.info("setHostconf set the parameter error!") end
  393. hostconf = cmds.ext
  394. io.writefile(HOST_CONF, dat)
  395. audio.play('/ldata/save.mp3')
  396. end
  397. --- 下发服务器配置信息
  398. function setServerConf(dat)
  399. local cmds, result, err = json.decode(dat)
  400. if not result then log.info("setServerConf set the parameter error!") end
  401. serverconf = cmds.ext
  402. io.writefile(NETCONF, dat)
  403. audio.play('/ldata/save.mp3')
  404. end
  405. --- 开机获取用户配置的参数
  406. function getConfig()
  407. local netconf, cmds, result, err
  408. photo_sw = io.readfile(TAKEPHOTO)
  409. if photo_sw == nil then photo_sw = 0 end
  410. netconf = io.readfile(NETCONF)
  411. log.warn("from NETCONF read netconf:",netconf)
  412. cmds, result, err = json.decode(netconf)
  413. if result then serverconf = cmds.mqtt end
  414. log.warn("from NETCONF read cmds.mqtt:",cmds.mqtt)
  415. end
  416. -- LED指示灯任务
  417. sys.taskInit(function()
  418. pmd.ldoset(7, pmd.LDO_VMMC)
  419. local ledpin = pins.setup(pio.P0_10, 1)
  420. while true do
  421. -- GSM注册中
  422. while not link.isReady() do
  423. led.blinkPwm(ledpin, 500, 500)
  424. sys.wait(100)
  425. end
  426. -- 网络附着中
  427. while datalink == 0 do
  428. led.blinkPwm(ledpin, 1000, 200)
  429. sys.wait(100)
  430. end
  431. -- 服务器已链接
  432. while datalink ~= 0 do
  433. -- 心跳包维持数据链接
  434. if datalink == 1 then
  435. led.blinkPwm(ledpin, 200, 1000)
  436. -- 发送数据中
  437. elseif datalink == 2 then
  438. led.blinkPwm(ledpin, 100, 100)
  439. end
  440. sys.wait(100)
  441. end
  442. sys.wait(1000)
  443. end
  444. end)
  445. sys.taskInit(function()
  446. sys.wait(3000)
  447. nvm.init("config.lua")
  448. -- 判断是否在mqtt1中启动喂狗;如果mqtt1连接云飞,则喂狗;
  449. if serverconf.ip == "120.27.222.26" or string.find(serverconf.ip, "yfzhwlw") ~= nil then
  450. log.error("***************one mqtt task!!!")
  451. else
  452. log.eror("****************two mqtt task!!!")
  453. end
  454. -- 开机即置1
  455. dev_sta = 1
  456. local cnt = hmi.hmiconf.datt * 60
  457. getConfig()
  458. log.info('MQTT111 Task is start!')
  459. while not socket.isReady() do sys.wait(1000) end
  460. -- 创建MQTT客户端,客户端ID为IMEI号
  461. willmsg.ext.imei = misc.getimei()
  462. local will = {qos = 1, retain = 0, topic = string.format(serverconf.lastwill .. misc.getimei()), payload = json.encode(willmsg)}
  463. local mqttc = mqtt.client(misc.getimei(), serverconf.keepalive, serverconf.uid, serverconf.pwd, 1,will)
  464. local pub = string.format(serverconf.pub .. misc.getimei())
  465. local sub = string.format(serverconf.sub .. misc.getimei())
  466. while true do
  467. while not mqttc:connect(serverconf.ip, serverconf.port) do sys.wait(1000) end
  468. -- 初始化订阅主题
  469. datalink = 1 -- 数据指示常亮等待数据
  470. if mqttc:subscribe(sub, serverconf.qos) then
  471. if dev_sta == 1 then
  472. -- 开机或重启即上传一次 dev_sta 为 'turnon':
  473. -- {"cmd":"warn","ext":{"status":"turnon","type":"dev_sta"}}
  474. mqttc:publish(pub, upwarn("dev_sta","turnon:" .. rtos.poweron_reason() .. "; mqtt1_disconntct:" .. nvm.get("mqtt1_disconntct")), serverconf.qos)
  475. dev_sta = 0
  476. elseif dev_sta == 2 then
  477. -- 掉线重连 上传一次 dev_sta 为 'relink':
  478. -- {"cmd":"warn","ext":{"status":"relink","type":"dev_sta"}}
  479. mqttc:publish(pub, upwarn("dev_sta","relink"), serverconf.qos)
  480. dev_sta = 0
  481. end
  482. while true do
  483. cnt = cnt + 10
  484. if cnt > tonumber(hmi.hmiconf.datt) * 60 then
  485. -- 推状态送消息
  486. datalink = 2 -- 数据发送指示快速闪烁
  487. if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end
  488. if not mqttc:publish(pub, upParamConf(), serverconf.qos) then break end
  489. log.info('upload is done!')
  490. cnt = 0
  491. end
  492. datalink = 1 -- 数据指示灯常亮等待发送
  493. if update.uptate_ok ~= 0 then
  494. audio.play('/ldata/alarm.mp3')
  495. log.warn('======================= update is ok!!!')
  496. if not mqttc:publish(pub, upwarn("bzy_update",update.uptate_ok), serverconf.qos) then break end
  497. update.uptate_ok = 0
  498. end
  499. --haikang.photo_flag = 1
  500. if haikang.photo_flag ~= 0 then
  501. log.warn('======================= take photo is ok!!!')
  502. -- 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
  503. -- 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
  504. local message = {cmd = "", ext = {}}
  505. local data = {
  506. photo_num = haikang.photo_num,
  507. step_num = haikang.step,
  508. }
  509. message.cmd = "photo"
  510. message.ext = data
  511. log.warn('=======================',json.encode(message))
  512. if not mqttc:publish(pub, json.encode(message), serverconf.qos) then break end
  513. haikang.photo_flag = 0
  514. haikang.step = 0
  515. haikang.photo_num = 0
  516. end
  517. if control.turn_reset_timeout ~= 0 then
  518. if not mqttc:publish(pub, upwarn("turn_reset_timeout:",control.turn_reset_timeout), serverconf.qos) then break end
  519. control.turn_reset_timeout = 0
  520. end
  521. if control.turn_timeout ~= 0 then
  522. if not mqttc:publish(pub, upwarn("turn_timeout:",control.turn_timeout), serverconf.qos) then break end
  523. control.turn_timeout = 0
  524. end
  525. -- 处理服务器的下发数据请求
  526. local r, packet = mqttc:receive(10000)-- 处理服务器下发指令
  527. if r then -- 这里是有数据下发的处理
  528. datalink = 2 -- 数据接收指示灯快闪
  529. local cnf, result, err = json.decode(packet.payload)
  530. if result and cnf.cmd == 'read' then
  531. if cnf.type == 'status' then
  532. if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end
  533. elseif cnf.type == 'netconf' then
  534. if not mqttc:publish(pub, upNetconf(), serverconf.qos) then break end
  535. -- 此处为兼容老设备,下发时cmd为paramconf 则上传时,需要区别一下:故cmd取param
  536. elseif cnf.type == 'param' then
  537. if not mqttc:publish(pub, upParamConf(), serverconf.qos) then break end
  538. end
  539. elseif result and cnf.cmd == 'netset' then
  540. setNetconf(packet.payload)
  541. -- 此处为兼容老设备,下发时cmd为paramconf 上传时,cmd取param
  542. -- elseif result and cnf.cmd == 'paramset' then
  543. elseif result and cnf.cmd == 'paramconf' then
  544. setParamConf(packet.payload)
  545. elseif result and cnf.cmd == 'serverconf' then
  546. setServerConf(packet.payload)
  547. elseif result and cnf.cmd == "reboot" then
  548. if not mqttc:publish(pub, upres("system will restart","ok"), serverconf.qos) then break end
  549. sys.restart("Server remote restart.")
  550. elseif result and cnf.cmd == "update" then
  551. update.run()
  552. if not mqttc:publish(pub, upwarn("bzy update is start","ok"), serverconf.qos) then break end
  553. log.info("Server remote update done!")
  554. elseif result and cnf.cmd == "set_photo_step" then
  555. nvm.set("photo_step", cnf.ext)
  556. if not mqttc:publish(pub, upwarn("set_photo_step",nvm.get("photo_step")), serverconf.qos) then break end
  557. elseif result and cnf.cmd == "get_photo_step" then
  558. if not mqttc:publish(pub, upwarn("get_photo_step",nvm.get("photo_step")), serverconf.qos) then break end
  559. elseif result and cnf.cmd == "poweroff" then
  560. hmi.hmiconf.on_off = 0
  561. local str = json.encode(hmi.hmiconf)
  562. log.info('will write configfile is:',str)
  563. io.writefile(hmi.HMI_FILE, str)
  564. if not mqttc:publish(pub, upres("poweroff","ok"), serverconf.qos) then break end
  565. if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end
  566. elseif result and cnf.cmd == "poweron" then
  567. hmi.hmiconf.on_off = 1
  568. local str = json.encode(hmi.hmiconf)
  569. log.info('will write configfile is:',str)
  570. io.writefile(hmi.HMI_FILE, str)
  571. if not mqttc:publish(pub, upres("poweron","ok"), serverconf.qos) then break end
  572. if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end
  573. elseif result and cnf.cmd == "coldoff" then
  574. hmi.hmiconf.cold_sw = 0
  575. local str = json.encode(hmi.hmiconf)
  576. log.info('will write configfile is:',str)
  577. io.writefile(hmi.HMI_FILE, str)
  578. if not mqttc:publish(pub, upwarn("coldoff","ok"), serverconf.qos) then break end
  579. elseif result and cnf.cmd == "coldon" then
  580. hmi.hmiconf.cold_sw = 1
  581. local str = json.encode(hmi.hmiconf)
  582. log.info('will write configfile is:',str)
  583. io.writefile(hmi.HMI_FILE, str)
  584. if not mqttc:publish(pub, upwarn("coldon","ok"), serverconf.qos) then break end
  585. elseif result and cnf.cmd == "photo" then
  586. photosw(cnf.ext.ws)
  587. if not mqttc:publish(pub, upres("timer photo status",photo_sw), serverconf.qos) then break end
  588. -- 远程控制:
  589. elseif result and cnf.cmd == "ctrl" then
  590. -- 远程拍照:
  591. if cnf.ext.type == 'takephoto' then
  592. haikang.test_takephoto()
  593. if not mqttc:publish(pub, upwarn("bzy test takephoto cmd send","ok"), yfmqtt.qos) then break end
  594. -- 远程控制对焦拍照:
  595. elseif cnf.ext.type == 'auto_takephoto' then
  596. hmi.remote_auto_pic()
  597. if not mqttc:publish(pub, upwarn("bzy auto takephoto cmd send","ok"), yfmqtt.qos) then break end
  598. -- 转盘操作:
  599. elseif cnf.ext.type == 'turn' then
  600. control.turn()
  601. if not mqttc:publish(pub, upres("turn","ok"), serverconf.qos) then break end
  602. end
  603. end
  604. elseif packet == 'timeout' then -- 服务器下发指令超时处理
  605. datalink = 1 -- 等待数据指示灯常亮
  606. -- 只往云飞平台传数据时,启动喂狗;如果此task为对接到用户的平台,则不喂狗,即保证云飞mqtt任务的连接:即,如果云飞mqtt任务不喂狗,系统会重启;
  607. control.wdg()
  608. log.info('MqttServer111 recv is timeout')
  609. else
  610. log.info('The MqttServer111 connection is broken.')
  611. break
  612. end
  613. datalink = 1 -- 数据指示灯常亮等待发送
  614. end
  615. end
  616. mqttc:disconnect()
  617. -- 发布平台mqtt连接断开!如果对接外部平台,则在云飞mqtt任务中,预警mqtt1的断开!!
  618. sys.publish("MQTT1_DISCONNECT")
  619. -- 断开连接即 设备即将重连网络,即置2,等网络重连成功,则会上报 曾掉线重连网络过。
  620. dev_sta = 2
  621. datalink = 0 -- 服务器断开链接数据指示灯慢闪
  622. sys.wait(1000)
  623. end
  624. end)
  625. --- 上传响应信息
  626. function upres(c_type,c_status)
  627. local dat
  628. -- 设备上报数据表
  629. local data = {
  630. type = c_type,
  631. status = c_status,
  632. }
  633. audio.play('/ldata/dataupload.mp3')
  634. message.cmd = "control"
  635. message.ext = data
  636. dat = json.encode(message)
  637. log.info("upload upres:", dat)
  638. return dat
  639. end
  640. --- 上传预警信息
  641. -- t:type
  642. -- s:status
  643. function upwarn(t,s)
  644. -- log.info("------------------------t,:",t)
  645. -- log.info("------------------------s,:",s)
  646. local dat
  647. -- 设备上报数据表
  648. local data = {
  649. type = t,
  650. status = s,
  651. }
  652. message.cmd = "warn"
  653. message.ext = data
  654. dat = json.encode(message)
  655. log.info("upload warn:", dat)
  656. return dat
  657. end
  658. function photo()
  659. local dat
  660. -- 设备上报数据表
  661. local data = {
  662. type = t,
  663. status = s,
  664. }
  665. message.cmd = "warn"
  666. message.ext = data
  667. dat = json.encode(message)
  668. log.info("upload warn:", dat)
  669. return dat
  670. end
  671. ----------------------------云飞mqtt上传任务:----------------------------
  672. -- 云飞MQTT服务器配置表
  673. yfmqtt = {
  674. ip = "120.27.222.26",-- 云飞
  675. port = 1883,
  676. sub = "/yfkj/bzy/s2c/",
  677. pub = "/yfkj/bzy/c2s/",
  678. keepalive = 60,
  679. lastwill = "/yfkj/bzy/offline/",
  680. uid = "",
  681. pwd = "",
  682. qos = 0,
  683. }
  684. -- mqtt1的连接状态:0正常;1异常;
  685. local mqtt1_sta = 0
  686. function mqtt1_disconntct()
  687. nvm.set("mqtt1_disconntct",nvm.get("mqtt1_disconntct")+1)
  688. if nvm.get("mqtt1_disconntct") >= 100000000 then nvm.set("mqtt1_disconntct",0) end
  689. -- 状态置1表示异常;
  690. mqtt1_sta = 1
  691. end
  692. sys.taskInit(function()
  693. sys.wait(3000)
  694. sys.subscribe("MQTT1_DISCONNECT",mqtt1_disconntct)
  695. -- 开机即置1
  696. dev_sta = 1
  697. -- 判断 serverconf
  698. log.info("yunfei mqtt ===================!!!")
  699. if serverconf.ip == "120.27.222.26" then
  700. log.info("serverconf.ip = 120.27.222.26")
  701. else
  702. log.info("serverconf.ip ~= 120.27.222.26")
  703. end
  704. if string.find(serverconf.ip, "yfzhwlw") ~= nil then
  705. log.info("serverconf.ip include yfzhwlw")
  706. else
  707. log.info("serverconf.ip not include yfzhwlw")
  708. end
  709. if serverconf.ip == "120.27.222.26" or string.find(serverconf.ip, "yfzhwlw") ~= nil then
  710. log.info("yunfei mqtt end!!!")
  711. return
  712. else
  713. log.info("yunfei mqtt start running!!!")
  714. end
  715. local cnt = hmi.hmiconf.datt * 60
  716. getConfig()
  717. log.info('MQTT222 Task is start!')
  718. while not socket.isReady() do sys.wait(1000) end
  719. -- 创建MQTT客户端,客户端ID为IMEI号
  720. willmsg.ext.imei = misc.getimei()
  721. local will = {qos = 1, retain = 0, topic = string.format(yfmqtt.lastwill .. misc.getimei()), payload = json.encode(willmsg)}
  722. local mqttc = mqtt.client(misc.getimei(), yfmqtt.keepalive, yfmqtt.uid, yfmqtt.pwd, 1,will)
  723. local pub = string.format(yfmqtt.pub .. misc.getimei())
  724. local sub = string.format(yfmqtt.sub .. misc.getimei())
  725. while true do
  726. while not mqttc:connect(yfmqtt.ip, yfmqtt.port) do sys.wait(1000) end
  727. -- 初始化订阅主题
  728. datalink = 1 -- 数据指示常亮等待数据
  729. if mqttc:subscribe(sub, yfmqtt.qos) then
  730. if dev_sta == 1 then
  731. -- 开机或重启即上传一次 dev_sta 为 'turnon':
  732. -- {"cmd":"warn","ext":{"status":"turnon","type":"dev_sta"}}
  733. mqttc:publish(pub, upwarn("dev_sta","turnon:" .. rtos.poweron_reason() .. "mqtt1_disconntct:" .. nvm.get("mqtt1_disconntct")), yfmqtt.qos)
  734. dev_sta = 0
  735. elseif dev_sta == 2 then
  736. -- 掉线重连 上传一次 dev_sta 为 'relink':
  737. -- {"cmd":"warn","ext":{"status":"relink","type":"dev_sta"}}
  738. mqttc:publish(pub, upwarn("dev_sta","relink"), yfmqtt.qos)
  739. dev_sta = 0
  740. end
  741. while true do
  742. cnt = cnt + 10
  743. if cnt > tonumber(hmi.hmiconf.datt) * 60 then
  744. -- 推状态送消息
  745. datalink = 2 -- 数据发送指示快速闪烁
  746. -- audio.play('/ldata/upload.mp3')
  747. if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end
  748. -- if not mqttc:publish(pub, upData(), yfmqtt.qos) then break end
  749. log.info('upload is done!')
  750. cnt = 0
  751. end
  752. datalink = 1 -- 数据指示灯常亮等待发送
  753. --------- mqtt1连接异常 ---------1表断开连接;
  754. if mqtt1_sta ~= 0 then
  755. log.warn('======================= mqtt1_sta:',mqtt1_sta)
  756. if not mqttc:publish(pub, upwarn("mqtt1_sta",mqtt1_sta), yfmqtt.qos) then break end
  757. mqtt1_sta = 0
  758. end
  759. if update.uptate_ok ~= 0 then
  760. log.warn('======================= update is ok!!!')
  761. if not mqttc:publish(pub, upwarn("bzy_update",update.uptate_ok), yfmqtt.qos) then break end
  762. update.uptate_ok = 0
  763. end
  764. -- 处理服务器的下发数据请求
  765. local r, packet = mqttc:receive(10000)-- 处理服务器下发指令
  766. if r then -- 这里是有数据下发的处理
  767. datalink = 2 -- 数据接收指示灯快闪
  768. local cnf, result, err = json.decode(packet.payload)
  769. if result and cnf.cmd == 'read' then
  770. if cnf.type == 'status' then
  771. if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end
  772. elseif cnf.type == 'paramconf' then
  773. if not mqttc:publish(pub, upParamConf(), yfmqtt.qos) then break end
  774. elseif cnf.type == 'serverconf' then
  775. if not mqttc:publish(pub, upServerConf(), yfmqtt.qos) then break end
  776. elseif cnf.ext.type == 'hostconf' then
  777. if not mqttc:publish(pub, upHostConf(), yfmqtt.qos) then break end
  778. end
  779. elseif result and cnf.cmd == 'paramconf' then
  780. setParamConf(packet.payload)
  781. elseif result and cnf.cmd == 'hostconf' then
  782. setHostconf(packet.payload)
  783. elseif result and cnf.cmd == 'serverconf' then
  784. setServerConf(packet.payload)
  785. elseif result and cnf.cmd == "set_photo_step" then
  786. nvm.set("photo_step", cnf.ext)
  787. if not mqttc:publish(pub, upwarn("set_photo_step",nvm.get("photo_step")), yfmqtt.qos) then break end
  788. elseif result and cnf.cmd == "get_photo_step" then
  789. if not mqttc:publish(pub, upwarn("get_photo_step",nvm.get("photo_step")), yfmqtt.qos) then break end
  790. elseif result and cnf.cmd == "poweroff" then
  791. hmi.hmiconf.on_off = 0
  792. local str = json.encode(hmi.hmiconf)
  793. log.info('will write configfile is:',str)
  794. io.writefile(hmi.HMI_FILE, str)
  795. if not mqttc:publish(pub, upres("poweroff","ok"), yfmqtt.qos) then break end
  796. if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end
  797. elseif result and cnf.cmd == "poweron" then
  798. hmi.hmiconf.on_off = 1
  799. local str = json.encode(hmi.hmiconf)
  800. log.info('will write configfile is:',str)
  801. io.writefile(hmi.HMI_FILE, str)
  802. if not mqttc:publish(pub, upres("poweron","ok"), yfmqtt.qos) then break end
  803. if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end
  804. elseif result and cnf.cmd == "coldoff" then
  805. hmi.hmiconf.cold_sw = 0
  806. local str = json.encode(hmi.hmiconf)
  807. log.info('will write configfile is:',str)
  808. io.writefile(hmi.HMI_FILE, str)
  809. if not mqttc:publish(pub, upwarn("coldoff","ok"), yfmqtt.qos) then break end
  810. if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end
  811. elseif result and cnf.cmd == "coldon" then
  812. hmi.hmiconf.cold_sw = 1
  813. local str = json.encode(hmi.hmiconf)
  814. log.info('will write configfile is:',str)
  815. io.writefile(hmi.HMI_FILE, str)
  816. if not mqttc:publish(pub, upwarn("coldon","ok"), yfmqtt.qos) then break end
  817. if not mqttc:publish(pub, upStatus(), yfmqtt.qos) then break end
  818. elseif result and cnf.cmd == "reboot" then
  819. if not mqttc:publish(pub, upres("system will restart","ok"), yfmqtt.qos) then break end
  820. sys.restart("Server remote restart.")
  821. elseif result and cnf.cmd == "update" then
  822. update.run()
  823. if not mqttc:publish(pub, upres("update is start","ok"), yfmqtt.qos) then break end
  824. log.info("Server remote update done!")
  825. elseif result and cnf.cmd == "photo" then
  826. photosw(cnf.ext.ws)
  827. if not mqttc:publish(pub, upres("timer photo status",photo_sw), yfmqtt.qos) then break end
  828. -- 远程控制:
  829. elseif result and cnf.cmd == "ctrl" then
  830. -- 远程拍照:
  831. if cnf.ext.type == 'takephoto' then
  832. haikang.test_takephoto()
  833. if not mqttc:publish(pub, upwarn("bzy test takephoto cmd send","ok"), yfmqtt.qos) then break end
  834. -- 远程控制对焦拍照:
  835. elseif cnf.ext.type == 'auto_takephoto' then
  836. hmi.remote_auto_pic()
  837. if not mqttc:publish(pub, upwarn("bzy auto takephoto cmd send","ok"), yfmqtt.qos) then break end
  838. -- 转盘操作:
  839. elseif cnf.ext.type == 'turn' then
  840. control.turn()
  841. if not mqttc:publish(pub, upres("turn","ok"), yfmqtt.qos) then break end
  842. end
  843. end
  844. elseif packet == 'timeout' then -- 服务器下发指令超时处理
  845. datalink = 1 -- 等待数据指示灯常亮
  846. control.wdg()
  847. log.info('MqttServer222 recv is timeout')
  848. else
  849. log.info('The MqttServer222 connection is broken.')
  850. break
  851. end
  852. datalink = 1 -- 数据指示灯常亮等待发送
  853. end
  854. end
  855. mqttc:disconnect()
  856. -- 断开连接即 设备即将重连网络,即置2,等网络重连成功,则会上报 曾掉线重连网络过。
  857. dev_sta = 2
  858. datalink = 0 -- 服务器断开链接数据指示灯慢闪
  859. sys.wait(1000)
  860. end
  861. end)
  862. -- 网络状况监控任务:
  863. -- sys.taskInit(function()
  864. -- nvm.init("config.lua")
  865. -- local err = 0
  866. -- -- 等待设备联网:
  867. -- -- 两分钟后启动;
  868. -- sys.wait(120000)
  869. -- -- sys.wait(40000)
  870. -- -- nvm.set("socket_err",0)
  871. -- log.error("===config.socket_err",nvm.get("socket_err"))
  872. -- -- log.error("===config.wdg_err",nvm.get("wdg_err"))
  873. -- log.warn("***************socket monitor task is running!***************")
  874. -- while true do
  875. -- while not socket.isReady() do
  876. -- log.warn('socket is not Ready,','err:',err)
  877. -- err = err + 1
  878. -- if err >= 90 then
  879. -- -- if err >= 5 then
  880. -- --参数+1并赋值,立即写入文件系统,
  881. -- nvm.set("socket_err",nvm.get("socket_err")+1)
  882. -- -- nvm.set("wdg_err",nvm.get("wdg_err")+1)
  883. -- log.error("config.socket_err",nvm.get("socket_err"))
  884. -- -- control.stop_all_move()
  885. -- -- control.stop_all_move()
  886. -- sys.restart("socket connect err overtime:90!!!")
  887. -- end
  888. -- sys.wait(1000)
  889. -- end
  890. -- if socket.isReady() then
  891. -- log.info('***socket is Ready!!!')
  892. -- err = 0
  893. -- end
  894. -- sys.wait(5000)
  895. -- end
  896. -- end)
  897. sys.taskInit(function()
  898. local cnow
  899. while true do
  900. cnow = misc.getClock()
  901. -- log.warn("time tast print >> now time:" .. os.date("%Y%m%d%H%M%S",os.time(cnow)))
  902. if cnow.hour == 9 and cnow.min == 0 and cnow.sec == 0 and photo_sw == 0 then
  903. -- if cnow.hour == 14 and cnow.min == 40 and cnow.sec == 01 then
  904. log.error("timephoto!!! time is" .. os.date("%Y%m%d%H%M%S",os.time(cnow)))
  905. haikang.test_takephoto()
  906. sys.wait(15000)
  907. haikang.http_chose_photo_task()
  908. end
  909. -- log.warn("free space is",rtos.get_fs_free_size())
  910. sys.wait(1000)
  911. end
  912. end)
  913. function photosw(sw)
  914. if not sw then return end
  915. sw = tonumber(sw)
  916. if sw < 2 then
  917. photo_sw = sw
  918. io.writefile(TAKEPHOTO,photo_sw)
  919. end
  920. end
  921. -- sys.taskInit(function()
  922. -- while true do
  923. -- -- local url = "http://yfzhwlw.com/test"
  924. -- local url = "http://yfznscd.com/test"
  925. -- local param = {
  926. -- imei="",
  927. -- }
  928. -- while not socket.isReady() do sys.waitUntil('IP_READY_IND') end
  929. -- param.imei = misc.getimei()-- 唯一ID
  930. -- log.error("#################### type param is:",type(param))
  931. -- local code, head, body = http.request("POST", url, 5000,nil,param)
  932. -- log.error("#################### http code is:",code)
  933. -- log.error("#################### http body is:",body)
  934. -- -- local cnt = 1
  935. -- -- for cnt = 1, 3 do
  936. -- -- while not socket.isReady() do sys.waitUntil('IP_READY_IND') end
  937. -- -- -- while not socket.isReady() do sys.wait(2000) end
  938. -- -- local code, head, body = http.request("GET", url, 5000)
  939. -- -- log.error("#################### http code is:",code)
  940. -- -- end
  941. -- sys.wait(10000)
  942. -- end
  943. -- end)