scd.lua 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  1. ---scd--@module testSocket--@author 稀饭放姜--@license MIT--@copyright hnyfkj.com--@release 2017.9.27
  2. require "socket"
  3. require "misc"
  4. require "led"
  5. require "mqtt"
  6. require "lbsLoc"
  7. require "pins"
  8. require "autoGPS" -- utoGPS功能模块只能配合Air820使用;如果不是这款模块,不要打开agps功能
  9. require "ril"
  10. require "Update"
  11. require "sim"
  12. ------------------------------
  13. require "config" --默认参数保存
  14. require "nvm"
  15. module(..., package.seeall)
  16. -- 本地存储文件
  17. local DEVICE_CONF = "/device.conf"
  18. local SERVER_CONF = "/server.conf"
  19. local DATTIM_CONF = "/dat_f.conf"
  20. local DEV_REBOOT = "/rebootmes.txt"
  21. local PRARM_CONF = "/prarm.conf"
  22. local CONTROL_CONF = "/control.txt"
  23. local THIRD_CONF = "/thirdconf.conf" --第三方服务器数据保存
  24. local SHT30_DATA = "/sht30data.conf" --温湿度参数保存
  25. local GPS_CONF = "/gps.conf" --保存GPS定位数据
  26. -- 上报json数据的基础表
  27. local message = {cmd = "", ext = {}}
  28. -- 上报遗言的json表
  29. local willmsg = {cmd = "offline", ext = {imei = ""}}
  30. -- 温湿度天气接口的值
  31. local temp, hum
  32. -- GPIO 输入检测
  33. pmd.ldoset(2, pmd.LDO_VLCD)
  34. -------红外计数------
  35. local infrared_count = 0
  36. --------------------------MQTT定时数据上报----------------------------
  37. local mqtt_status = "true"
  38. local mqtt_status_num = 0
  39. local timeout = 1
  40. local updata_freq = 0
  41. ---------------------------------------------------------------------
  42. --------------------------物联网模块重启--------------------------
  43. -- 重启标志
  44. local rebootstate
  45. -- 重启次数
  46. local rebootcnt
  47. -- 重启信息
  48. local rebootinfo = 1 --1:正常 2:socket重连 3:MQTT重连
  49. ----------------------------------------------------------------
  50. -- 清虫时间间隔
  51. local dat_f = 10
  52. -- 上报数据时间间隔
  53. local clt_t = 30
  54. local wsflag = 0
  55. local worktim = 0
  56. -- 光控模式状态标志位
  57. local clps = 0
  58. --雨控即时上报标志位
  59. local rps_x = 0
  60. local rps_y = 0
  61. ----------------------主板远程升级交互参数----------
  62. --置位BootLoader交互下发标志位 --全局变量定义参数
  63. updateflag = 0 --BootLoader进入升级模式标志位
  64. BootLoader_flag = 0 --BootLoader交互下发标志位
  65. upgrade_again =0 --STM32固件升级再次升级标志位
  66. bootend = 0 --STM32固件升级完成标志位
  67. local uart_flag = 0 --串口通讯交互心跳标志位
  68. stm8_update_sw = 0 --主板升级一键测试防误触
  69. -------------------------------------------------
  70. ---------------------MQTT1----------------------
  71. -- 检测是否分配到ip次数
  72. local err_num = 0
  73. -- TCP重连次数
  74. local tcp_cont = 0
  75. -- TCP连接正常的情况下,MQTT重订阅次数
  76. local sub_cont = 0
  77. -- mqtt1协程守护变量
  78. local mqtt1_cont = 1 * 60 * 60 -- 超时时间1小时
  79. ----------------------MQTT2---------------------
  80. -- 检测是否分配到ip次数
  81. local err2_num = 0
  82. -- TCP重连次数
  83. local tcp2_cont = 0
  84. -- mqtt2协程守护变量
  85. local mqtt2_cont = 1 * 60 * 60 -- 超时时间1小时
  86. ----------------------------------------------
  87. -- 时控参数配置
  88. local timcontrl = {
  89. type = "",
  90. timctrl = 0, --时控开关 0-关 1开 默认:时控关闭
  91. st = 20, --时控开始时间 默认:时间控制从半夜20点开始
  92. et = 2 --时控结束时间 默认:时间控制到次日2点结束
  93. }
  94. -- 配置参数保存基础表
  95. local paramtable = {
  96. cmd = "paramconf",
  97. ext = {
  98. power = {ds = 1}, -- 配置开关机状态
  99. work_tim = {timctrl = 0, st = 20, et = 2}, -- 配置定时控制模式
  100. data_tim = {dat_f = 10}, -- 配置数据上报时间间隔
  101. clt_tim = {clt_t = 30}, -- 配置清虫时间间隔
  102. }
  103. }
  104. -- -------------------------定位-------------------------
  105. -- LBS经纬度
  106. local lbs_loc_lat
  107. local lbs_loc_lng
  108. -- GPS经纬度
  109. local gps_loc_lat
  110. local gps_loc_lng
  111. -- 定位状态
  112. local gps_status = 0 -- 初始值0
  113. local locat_cnt = 0
  114. local gps,agps
  115. local uartId=3
  116. -- GPS定位次数(处理GPS模块返回数据次数)
  117. local gps_cont = 0
  118. -- 手动定位数据调度基础表 BD-09(百度坐标)-->不用坐标转换
  119. local manual_location = {lat = "0", lng = "0", type = "0"}
  120. -- ------------------------------------------------------
  121. -- MQTT1服务器配置表
  122. serverconf = {
  123. imei = "", -- 唯一ID
  124. ip = "8.136.98.49",
  125. port = 61883, -- MQTT服务端口
  126. sub = "/yfkj/xycb/s2c/", -- 服务器到客户端 -- 注意pub和sub后带" /" ,以便设备自动拼接imei
  127. pub = "/yfkj/xycb/c2s/", -- 客户端到服务器
  128. lastwill = "/yfkj/xycb/offline/", -- 离线消息主题(部分)-->设备异常中断时用于mqtt服务器发布该设备的遗愿消息,个人网站客户端需订阅
  129. sub1 = "yfkj/xycb/s2c/",
  130. pub1 = "yfkj/xycb/c2s/",
  131. lastwill1 = "yfkj/xycb/offline/",
  132. keepalive = 60, -- 心跳保持时间
  133. uid = "user", -- 用户名
  134. pwd = "f335bf402c655ee5fd2b5300905124e", -- 密码
  135. qos = 0
  136. }
  137. -- MQTT2服务配置表,用于设备对接
  138. thirdserverconf = {
  139. imei = "", -- 唯一ID
  140. ip = "",
  141. port = 1883,
  142. sub = "/yfkj/xycb/s2c/",
  143. pub = "/yfkj/xycb/c2s/",
  144. keepalive = 60,
  145. lastwill = "/yfkj/xycb/offline/",
  146. uid = "",
  147. pwd = "",
  148. qos = 0
  149. }
  150. -- 设备运行上报下发参数表
  151. local paramconf = {
  152. imei = "", -- 唯一ID
  153. tt = 0, -- 默认光控定时模式下定时时常0小时
  154. vsunrise = 6000, -- 日出电压
  155. vsunset = 1500, -- 日落电压
  156. lcm = 0, -- 光控类型 0太阳能板光控 1光敏二极管光控
  157. vstart = 12000, -- 首次启动电压
  158. uvon = 11500, -- 电池欠压锁定电压
  159. uvoff = 12500, -- 电池欠压解锁电压
  160. vrecharge = 12800, -- 再次启动充电动作的电压
  161. vfloat = 13600, -- 电池浮充电压
  162. vcutof = 14400, -- 电池充电截至电压
  163. overtemp = 700, -- 高温保护阀值
  164. lowtemp = 100, -- 低温保护阀值
  165. unovert = 500, -- 高温解锁阀值
  166. unlowt = 150, -- 低温解锁阀值
  167. stamp = "20180301211805" -- 时间戳
  168. }
  169. --主板参数配置
  170. scdParam = {
  171. cmd = "Set_scdparam",
  172. ext = {
  173. lcm = 0, -- 光控类型 0太阳能板光控 1光敏二极管光控
  174. vsunrise = 1500, --日落电压
  175. vsunset = 6000, --日出电压
  176. vcutof = 14400, --最高充电电压
  177. vfloat = 13600, --恒压触发电压(浮充/恒压)
  178. vrecharge = 12800, --充电回滞电压
  179. uvstart = 12000, --开机电压
  180. uvoff = 12500, --放电迟滞电压
  181. uvon = 11500, --过放保护电压
  182. overtemp = 700, --高温保护电压
  183. lowtemp = 100, --低温保护电压
  184. unovert = 500, --高温解除电压
  185. unlowt = 150 --低温解除电压
  186. }
  187. }
  188. --串口接收检验
  189. result_crc = {
  190. ds = 1, --设备开启状态 1:开 0:关
  191. tt=4, -- 光控定时模式下定时时常(1--7)小时
  192. ws = 0, -- 工作状态 0 待机,1工作,2充电
  193. lps = 0, --光控状态 1:0
  194. rps = 0, --雨控保护状态 1:0
  195. tps = 0, --温度保护状态 1:0
  196. dps = 0, --倾倒保护状态 1:0
  197. bt = 0, --主板温度
  198. kcnt = 0, -- 风机状态
  199. cv = 0, --充电电压 xx.x
  200. ci = 0, --充电电流 x.xx
  201. bv = 12000, --电池电压 xx.x
  202. wv = 12, --工作电压 xx.x
  203. wi = 0, --工作电流 x.xx
  204. ver = "0", --e2prom版本
  205. cycle_off = 0, --未放电时检测到的频率
  206. clear_on = 0, --自清虫标志位
  207. cleartim = 30,--清虫定时时间
  208. Lamp = 0,--灯管故障检测
  209. Infrared = 0--红外传感器
  210. }
  211. --串口接收缓存
  212. result = {
  213. ds = 1, --设备开启状态 1:开 0:关
  214. tt=4, -- 光控定时模式下定时时常(1--7)小时
  215. ws = 0, -- 工作状态 0 待机,1工作,2充电
  216. lps = 0, --光控状态 1:0
  217. rps = 0, --雨控保护状态 1:0
  218. tps = 0, --温度保护状态 1:0
  219. dps = 0, --倾倒保护状态 1:0
  220. bt = 0, --主板温度
  221. kcnt = 0, -- 风机状态
  222. cv = 0, --充电电压 xx.x
  223. ci = 0, --充电电流 x.xx
  224. bv = 12000, --电池电压 xx.x
  225. wv = 12, --工作电压 xx.x
  226. wi = 0, --工作电流 x.xx
  227. cycle_off = 0, --未放电时检测到的频率
  228. clear_on = 0, --自清虫标志位
  229. ver = "0",
  230. cleartim = 30,--清虫定时时间
  231. Lamp = 0,--灯管故障检测
  232. Infrared = 0--红外传感器
  233. }
  234. local function packAndSend(fid, value, multiplier)
  235. local scaledValue = (multiplier or 1) * value
  236. local highByte = bit.rshift(scaledValue, 8)
  237. local lowByte = bit.band(scaledValue, 0xFF)
  238. local command = string.char(0xDD, fid, highByte, lowByte)
  239. uart.write(1, command)
  240. sys.wait(400)
  241. end
  242. local function SetStatus()
  243. packAndSend(fid.vsunrise, scdParam.vsunrise)
  244. packAndSend(fid.vsunset, scdParam.vsunset)
  245. packAndSend(fid.vcutof, scdParam.vcutof)
  246. packAndSend(fid.vfloat, scdParam.vfloat)
  247. packAndSend(fid.vrecharge, scdParam.vrecharge)
  248. packAndSend(fid.uvstart, scdParam.uvstart)
  249. packAndSend(fid.uvoff, scdParam.uvoff)
  250. packAndSend(fid.uvon, scdParam.uvon)
  251. packAndSend(fid.overtemp, scdParam.overtemp, 10)
  252. packAndSend(fid.lowtemp, scdParam.lowtemp, 10)
  253. packAndSend(fid.unovert, scdParam.unovert, 10)
  254. packAndSend(fid.unlowt, scdParam.unlowt, 10)
  255. end
  256. --- 上传预警信息
  257. -- t:type
  258. -- s:status
  259. function upwarn(t,s)
  260. log.warn("------------------------t,:",t)
  261. log.warn("------------------------s,:",s)
  262. local dat
  263. -- 设备上报数据表
  264. local data = {
  265. type = t,
  266. status = s,
  267. }
  268. message.cmd = "warn"
  269. message.ext = data
  270. dat = json.encode(message)
  271. log.info("upload warn:", dat)
  272. return dat
  273. end
  274. ------------------------------------------------------------------------------------------------------
  275. --- 打印数据信息
  276. function PrintData()
  277. sys.wait(1000)
  278. if result.ds == 4 then result.ds = 1 end --滤除设备开关机状态标志位异常
  279. log.warn("++++++++++++++++++++++++++++++++++++++++Parameter display start!!+++++++++++++++++++++++++++++++++++++++++++++++")
  280. print("Table:", result)
  281. print( "eeprom state:", result.iSave,
  282. "\nDevice Status:", result.ds,
  283. "\nLignt control times:", result.tt,
  284. "\nWork Status:", result.ws,
  285. "\nLignt control Status:", result.lps,
  286. "\nRain control Status:", result.rps,
  287. "\ntempture control Status:", result.tps,
  288. "\nDump Protect:", result.dps,
  289. "\nvoltage Status:", result.vps,
  290. "\nCharging voltage:", result.cv,
  291. "\nBattery voltage:", result.bv,
  292. "\nBoard temperature:", result.bt,
  293. "\nLight control Type:", paramconf.lcm,
  294. "\nSunup voltage:", paramconf.vsunrise,
  295. "\nSunset voltage:", paramconf.vsunset,
  296. "\nCharging up to voltage:", paramconf.vcutof,
  297. "\nfloating charge voltage:", paramconf.vfloat,
  298. "\nonce again startup charging action voltage:", paramconf.vrecharge,
  299. "\nfirst startup voltage:", paramconf.vstart,
  300. "\nundervoltage clear voltage:", paramconf.uvoff,
  301. "\nundervoltage lock voltage:", paramconf.uvon,
  302. "\nHigh temperature Protect:", paramconf.overtemp,
  303. "\nLow temperature Protect:", paramconf.lowtemp,
  304. "\nHigh temperature clear:", paramconf.unovert,
  305. "\nLow temperature clear:", paramconf.unlowt,
  306. "红外计数器:", infrared_count,
  307. "\nVol counts:", result.kcnt,
  308. "\nboard version:", result.ver)
  309. log.warn("++++++++++++++++++++++++++++++++++++++++Parameter display end!!+++++++++++++++++++++++++++++++++++++++++++++++")
  310. end
  311. --+++++++++++++++++++++++++++++++++++++++++获取主板信息+++++++++++++++++++++++++++++++++++++++++
  312. -- 获取主板状态 -->STM8从机地址0x51
  313. local function getStatus()
  314. local data = string.char(0x55,0x03)
  315. uart.write(1,data)
  316. sys.wait(300)
  317. end
  318. --------------------------------------------------------------------------------------------------------------
  319. -- ====================================================上传===================================================
  320. ------------------------------------------------- 上传数据信息-四情平台 ----------------------------------------
  321. function upData_120(...)
  322. local data, c, dat = {}
  323. getStatus() -- 获取主板状态
  324. data.imei = misc.getImei() -- 唯一ID
  325. data.iccid = string.upper(sim.getIccid()) --获取SIM卡的iccid号 ++++ 注意:开机lua脚本运行之后,会发送at命令去查询iccid,所以需要一定时间才能获取到iccid。开机后立即调用此接口,基本上返回nil
  326. data.csq = net.getRssi() -- 信号强度
  327. data.dver = VERSION -- 版本号 (main.lua第二行)
  328. data.proj = PROJECT -- 设备名称 (main.lua第一行)
  329. data.stm8vs = string.format(result.ver) -- 主板版本号
  330. -------------------------------------------
  331. data.ds = result.ds or 1 -- 设备是否开机
  332. data.ws = result.ws or 1 -- 工作状态 0待机 1工作
  333. data.cs = result.lps or 0 -- 充电标志位 0 非充电,1 充电
  334. data.rps = result.rps or 0 -- 雨控
  335. data.tps = result.tps or 0 -- 温控
  336. data.dps = result.dps or 0 -- 倾倒
  337. data.bs = result.vps or 0 -- 正常0 欠压 1 过压 2
  338. --------------------------------------
  339. data.tcs = timcontrl.timctrl --时控开关
  340. data.st = timcontrl.st --时控开始时间
  341. data.et = timcontrl.et --时控结束时间
  342. --------------------------------------
  343. data.lcm = result.lcm or 0 -- 光控类型 0太阳能板光控 1光敏二极管光控
  344. data.cv = result.cv or 0 -- 充电电压 单位:mV
  345. data.bv = result.bv or 12000 -- 电池电压 单位:mV
  346. data.bt = result.bt / 10 -- 主板温度
  347. data.at = result.bt/10 --环境温度
  348. data.ah = hum or 30.0 -- 环境湿度
  349. data.infr_ct = infrared_count -- 红外计数
  350. if data.infr_ct > 70 then --过滤掉开机之后的红外计数异常
  351. data.infr_ct = 0
  352. end
  353. data.volt_ct = result.kcnt -- 高压计数值
  354. if data.volt_ct > 10 then --过滤掉开机之后的电击计数异常
  355. data.volt_ct = 0
  356. end
  357. data.wind_drec = 666
  358. data.wind_sped = 66.6
  359. -----------------------------------------
  360. rebootcnt = io.readFile(DEV_REBOOT)
  361. data.bt_ct = rebootcnt -- 设备重启次数
  362. log.warn("Device Reboot times is:", rebootcnt)
  363. data.gps = gps_status -- 定位标志位 0 手动定位,1 GPS定位,2 LBS定位
  364. if gps_status == 0 then
  365. data.lat = manual_location.lat
  366. data.lng = manual_location.lng
  367. elseif gps_status == 1 then
  368. data.lat = gps_loc_lat
  369. data.lng = gps_loc_lng
  370. elseif gps_status == 2 then
  371. data.lat = lbs_loc_lat
  372. data.lng = lbs_loc_lng
  373. end
  374. log.warn("upload LBS data message:", data.lat, data.lng)
  375. c = misc.getClock() -- 获取系统时间
  376. data.stamp = string.format("%04d%02d%02d%02d%02d%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
  377. message.cmd = "data"
  378. message.ext = data
  379. dat = json.encode(message)
  380. log.info("upload data:", dat)
  381. --ClearKcnt() --上报数据清零红外
  382. return dat
  383. end
  384. ------------------------- 上传参数配置信息
  385. function upStatus()
  386. local status, dat = {}
  387. getStatus()-- 获取主板状态
  388. status.imei = misc.getImei() -- 唯一ID
  389. status.iccid = string.upper(sim.getIccid())--获取SIM卡的iccid号 ++++ 注意:开机lua脚本运行之后,会发送at命令去查询iccid,所以需要一定时间才能获取到iccid。开机后立即调用此接口,基本上返回nil
  390. status.csq = net.getRssi() -- 信号强度
  391. status.tt = result.tt or 0 -- 定时时长
  392. message.cmd = "status"
  393. message.ext = status
  394. dat = json.encode(message)
  395. log.info("upload status:", dat)
  396. return dat
  397. end
  398. -----------------------------------------------------------------------------------------------------------------
  399. --------------------------------------- 上传数据信息-------大数据平台----------------------------------------------
  400. function upData()
  401. local data, c, dat = {}
  402. getStatus() -- 获取主板状态
  403. data.imei = misc.getImei() -- 唯一ID
  404. data.iccid = string.format(sim.getIccid()) -- 获取SIM卡的iccid号
  405. data.csq = string.format(net.getRssi()) -- 信号强度
  406. data.dver = VERSION -- 版本号 (main.lua第二行)
  407. data.proj = PROJECT -- 设备名称 (main.lua第一行)
  408. data.stm8vs = string.format(result.ver) --
  409. data.dtype = "4" -- 设备类型 -性诱III
  410. data.btype = "0" -- 0 蓄电池,1锂电池
  411. data.ds = string.format(result.ds or 1) -- 设备是否开机
  412. data.ws = string.format(result.ws or 1) -- 工作状态0待机,1工作,2充电
  413. data.cs = string.format(result.lps or 0) -- 充电标志位 0 非充电,1 充电
  414. data.rps = string.format(result.rps or 0) -- 雨控
  415. data.tps = string.format(result.tps or 0) -- 温控
  416. data.dps = string.format(result.dps or 0) -- 倾倒
  417. data.bs = string.format(result.vps or 0) -- 正常0 欠压 1 过压 2
  418. data.lcm = string.format(result.lcm or 0) -- 光控类型 0太阳能板光控 1光敏二极管光控
  419. data.bt = string.format(result.bt / 10) -- 主板温度
  420. data.ts = string.format(timcontrl.timctrl) -- 时控开关
  421. data.st = string.format(timcontrl.st) -- 时控开始时间
  422. data.et = string.format(timcontrl.et) -- 时控结束时间
  423. data.cv = string.format((result.cv or 18000) / 1000) -- 充电电压
  424. data.bv = string.format((result.bv or 12800) / 1000) -- 电池电压
  425. data.at = string.format(result.bt/10) or "25.0" -- 环境温度
  426. data.ah = string.format(hum) or "30.0" -- 环境湿度
  427. data.volt_ct = string.format(result.kcnt) -- 电击次数
  428. if tonumber(data.volt_ct) > 10 then --过滤掉开机之后的电击计数异常
  429. data.volt_ct = "0"
  430. end
  431. data.infr_ct = infrared_count -- 光电开关计数值
  432. if tonumber(data.infr_ct) > 70 then -- 过滤掉开机之后的光栅计数异常
  433. data.infr_ct = 0
  434. end
  435. data.wind_drec = "666"
  436. data.wind_sped = "66.6"
  437. data.dat_f = string.format(dat_f) -- 数据上传时间间隔
  438. data.clt_t = string.format(clt_t) -- 清虫时间间隔
  439. rebootcnt = io.readFile(DEV_REBOOT)
  440. if rebootcnt == nil or rebootcnt == "" then
  441. log.info("first startup!!!!!!!!")
  442. rebootcnt = 0
  443. rebootcnt = tonumber(rebootcnt)
  444. end
  445. log.warn("Device Reboot times is:", rebootcnt)
  446. data.rcnt = string.format(rebootcnt) -- 重启次数
  447. data.gps = string.format(gps_status) -- 定位标志位 0 手动定位,1 GPS定位,2 LBS定位
  448. if gps_status == 0 then
  449. data.lat = manual_location.lat
  450. data.lng = manual_location.lng
  451. elseif gps_status == 1 then
  452. data.lat = gps_loc_lat
  453. data.lng = gps_loc_lng
  454. elseif gps_status == 2 then
  455. data.lat = lbs_loc_lat
  456. data.lng = lbs_loc_lng
  457. end
  458. c = misc.getClock()
  459. data.stamp = string.format("%04d%02d%02d%02d%02d%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
  460. message.cmd = "data"
  461. message.ext = data
  462. dat = json.encode(message)
  463. log.info("upload data:", dat)
  464. --ClearKcnt(); --清除点击次数
  465. return dat
  466. end
  467. -----------------------------------------------------------------------------------------------------------
  468. ----------------------------------------- 物联网模块参数配置开始 --------------------------------------------
  469. ----------------------------------------- 上传主板参数配置信息-----------------------------------------------
  470. function upParamConf(...)
  471. local c, dat
  472. paramconf.imei = misc.getImei() -- 唯一ID
  473. c = misc.getClock()
  474. paramconf.stamp = string.format("%04d%02d%02d%02d%02d%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
  475. message.cmd = "paramconf"
  476. message.ext = paramconf
  477. dat = json.encode(message)
  478. log.info("upload paramconf:", dat)
  479. return dat
  480. end
  481. ----------------------------------------- 上传主服务器配置信息--------------------------------------------------
  482. function upServerConf(...)
  483. local dat
  484. serverconf.imei = misc.getImei()-- 唯一ID
  485. message.cmd = "serverconf"
  486. message.ext = serverconf
  487. dat = json.encode(message)
  488. log.info("upload serverconf:", dat)
  489. return dat
  490. end
  491. ----------------------------------------- 上传第三方服务器配置信息---------------------------------------------
  492. function upThirdserverConf(...)
  493. local dat
  494. thirdserverconf.imei = misc.getImei()-- 唯一ID
  495. message.cmd = "thirdserverconf"
  496. message.ext = thirdserverconf
  497. dat = json.encode(message)
  498. log.info("upload thirdserverconf:", dat)
  499. return dat
  500. end
  501. -- 设备给客户端的反馈 -->远程控制设备更新和重启等
  502. function upres(c_type, c_status)
  503. local dat
  504. -- 设备上报数据表
  505. local data = {
  506. type = c_type,
  507. status = c_status
  508. }
  509. message.cmd = "warn"
  510. message.ext = data
  511. dat = json.encode(message)
  512. log.info("upload upres:", dat)
  513. return dat
  514. end
  515. ------------------------------------------------- 物联网模块参数配置结束 --------------------------------------------------------
  516. ------------------------------------------------------------------------------------------------------------------------------
  517. --++++++++++++++++++++++++++++++++++++++++++++++++ 功能函数集合 开始++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  518. ---------------------------------------------------主板参数下发配置 开始--------------------------------------------------------
  519. --- 设置主板开关机
  520. function setsw(pwb)
  521. local setsw_cnt = 0
  522. local set_onoff = string.char(0xAA,0x01,pwb)
  523. while result.ds ~= pwd do
  524. setsw_cnt = setsw_cnt + 1
  525. uart.write(1,set_onoff)
  526. if setsw_cnt == 2 then break end
  527. sys.wait(500)
  528. end
  529. log.info("设备开关机:", pwb)
  530. end
  531. --- 设置主板光控定时时长
  532. -- @param tt, number类型
  533. function setTimer(tt)
  534. if not tt then
  535. return
  536. end
  537. if (tt <= 0 or tt > 8) and tt ==nil and tt == "" then
  538. log.error("setTimer value error!!!!!!!")
  539. return
  540. end
  541. local send_cnt = 0
  542. local dat_freq = string.char(0xAA,0x02,tt)
  543. while tt~=result.tt do
  544. send_cnt = send_cnt + 1
  545. uart.write(1,dat_freq)
  546. if send_cnt == 3 then
  547. break end
  548. end
  549. log.info("定时模式为光控,时长:", tt)
  550. end
  551. ---清零红外和高压计数值
  552. function ClearKcnt()
  553. local kcnt = 0
  554. local clear = string.char(0xAA,0x06)
  555. while true do
  556. kcnt = kcnt +1
  557. if result.infr_ct ~=0 or result.volt_ct ~=0 then
  558. uart.write(1,clear)
  559. end
  560. if kcnt == 2 then break end
  561. sys.wait(500)
  562. end
  563. log.info("clear kcnt!!!!")
  564. end
  565. ---清虫
  566. local function Clearworm()
  567. local setsw_cnt = 0
  568. local clear_worm = string.char(0xAA,0x05)
  569. while true do
  570. setsw_cnt = setsw_cnt + 1
  571. uart.write(1,clear_worm)
  572. sys.wait(500)
  573. if setsw_cnt == 2 then break end --确保置位清虫标志位
  574. end
  575. log.info("clear worm!!!!")
  576. end
  577. --下发时控设置
  578. function SetTimControl(crtl,st1,et1)
  579. if crtl == nil or crtl == "" then return end
  580. if st1==nil or st1=="" or et1 ==nil or et1 == "" then return end
  581. st = tonumber(st1)
  582. et = tonumber(et1)
  583. if (st < 1 or st > 23) or (et < 1 or et > 23) then
  584. log.error("value error!!!!!!!!!!")
  585. return
  586. end
  587. if crtl == 1 or crtl == 0 then
  588. timcontrl.timctrl = crtl
  589. end
  590. if (st >= 0 and st <=23) and ( et >= 0 and et <= 23) then
  591. timcontrl.st = st
  592. timcontrl.et = et
  593. end
  594. log.info("时控参数:", "timctrl:", timcontrl.timctrl, "st:", timcontrl.st, "et:", timcontrl.et)
  595. local data = json.encode(timcontrl)
  596. io.writeFile(CONTROL_CONF, data)
  597. end
  598. --- 设置清虫时间间隔
  599. function SetCleartime(clt)
  600. if not clt then
  601. return
  602. end
  603. if clt < 1 or clt > 120 then
  604. log.error("clt value error******")
  605. return
  606. end
  607. if clt > 9 and clt < 121 then
  608. cleartim = clt
  609. end
  610. log.info("设置清虫时间间隔为:", cleartim, "分钟")
  611. io.writeFile(CLEART_CONF, cleartim)
  612. end
  613. --- 下发配置数据上传时间间隔:
  614. function setDattim(dat)
  615. if not dat then
  616. return
  617. end
  618. if dat < 1 or dat > 120 then
  619. log.error("Dattim value error!!!!!!!")
  620. return
  621. end
  622. if dat > 9 and dat < 121 then
  623. dattim = dat
  624. end
  625. log.info("设置数据上传时间间隔为:", dattim, "分钟")
  626. io.writeFile(DATTIM_CONF, dattim)
  627. end
  628. -- 一键测试函数
  629. function Test_key()
  630. if stm8_update_sw == 1 then return end
  631. local test = string.char(0XAA,0X0A)
  632. uart.write(1,test)
  633. end
  634. --下发主板升级命令
  635. function update_stm32()
  636. local update_cnt = 0
  637. local up_date_32 = string.char(0xAA,0xA0)
  638. while true do
  639. update_cnt = update_cnt + 1
  640. uart.write(1,up_date_32)
  641. sys.wait(500)
  642. if update_cnt == 2 then break end
  643. end
  644. log.info("update_stm32 begin!!!!")
  645. end
  646. --光控模式切换
  647. function Light_control_handoff()
  648. local Light_control1 = string.char(0xAA,0x03,0x01)
  649. local Light_control2 = string.char(0xAA,0x03,0x00)
  650. while true do
  651. if result.lcm == 0 then
  652. uart.write(1,Light_control1)
  653. elseif result.lcm == 1 then
  654. uart.write(1,Light_control2)
  655. end
  656. return
  657. end
  658. log.info("Light control handoff begin!!!!")
  659. end
  660. --下发BootLoader交互命令
  661. function BootLoader_stm32()
  662. local boot_count = 0
  663. local BootLoader_32 = string.char(0x31)
  664. while true do
  665. boot_count = boot_count + 1
  666. uart.write(1,BootLoader_32)
  667. sys.wait(200)
  668. if boot_count == 2 then break end
  669. end
  670. log.info("BootLoader begin!!!!")
  671. end
  672. -----------------------------------------------------------------------------------------------------------------------------
  673. --================================================ 主板参数下发配置 结束 =======================================================
  674. -----------------------------------------------反向获取平台温湿度接口传回MQTT 开始----------------------------------------------------
  675. function Setsensor_value(dat_sensor)
  676. local cmds,result,err = json.decode(dat_sensor)
  677. if not result then
  678. return
  679. end
  680. if cmds.ext.new_hum~=nil and cmds.ext.new_hum~="" then
  681. if tonumber(cmds.ext.new_hum)~= nil and tonumber(cmds.ext.new_hum)>=0 and tonumber(cmds.ext.new_hum)<= 100 then
  682. hum = tonumber(cmds.ext.new_hum)
  683. if nvm.get("hum")~= hum then
  684. nvm.set("hum",hum)
  685. end
  686. end
  687. end
  688. if cmds.ext.new_tem~=nil and cmds.ext.new_tem~="" then
  689. if tonumber(cmds.ext.new_tem)~= nil and tonumber(cmds.ext.new_tem) < 100 then
  690. temp = tonumber(cmds.ext.new_tem)
  691. if nvm.get("temp")~= temp then
  692. nvm.set("temp",temp)
  693. end
  694. end
  695. end
  696. log.warn(">>>>>>>>>sensor data get is:>>>>>>>>>>",hum,temp)
  697. end
  698. -----------------------------------------------反向获取平台温湿度接口传回MQTT 结束----------------------------------------------------
  699. ---------------------------------------------------------------------------------------------------------------------------
  700. ------------------------------------------------- 物联网模块参数配置开始 ------------------------------------------------------
  701. ---------------------------------------------------下发用户配置的参数----------------------------------------------------------
  702. -- --- 下发配置数据上传时间间隔
  703. -- @param dat, json数据结构
  704. function Set_dattim(dat)
  705. if nvm.get("platform")== "120.27.222.26" then
  706. local cmds, result, err = json.decode(dat)
  707. if not result then log.info("Set_dattim set the parameter error!") end
  708. if type(cmds.ext.dat_f) == "number" and cmds.ext.dat_f >= 10 and cmds.ext.dat_f <= 120 then -- number类型 data
  709. dat_f = cmds.ext.dat_f
  710. else
  711. log.error("EEEE:::::::::::::Dattim parameter not number or not range:::::::::::::::EEEE")
  712. return
  713. end
  714. log.warn("Set_dattim set the parameter value is: ", dat_f, "minutes")
  715. io.writeFile(DATTIM_CONF, dat)
  716. else
  717. local cmds, result, err = json.decode(dat)
  718. if not result then log.info("Set_dattim set the parameter error!") end
  719. dat_f = tonumber(cmds.ext.data_tim.dat_f)
  720. log.warn("Set_dattim set the parameter value is: ", dat_f, "minutes")
  721. paramtable.ext.data_tim.dat_f = dat_f
  722. local dat = json.encode(paramtable) -- 参数配置存入文件
  723. io.writeFile(PRARM_CONF,dat)
  724. end
  725. end
  726. -- --- 下发配置清虫时间间隔
  727. -- @param dat, json数据结构
  728. function Set_clttim(dat)
  729. local cmds, result, err = json.decode(dat)
  730. if not result then log.info("Set_dattim set the parameter error!") end
  731. clt_t = tonumber(cmds.ext.clt_tim.clt_t)
  732. log.warn("Set_dattim set the parameter value is: ", clt_t, "minutes")
  733. paramtable.ext.clt_tim.clt_t = clt_t
  734. local dat = json.encode(paramtable) -- 参数配置存入文件
  735. io.writeFile(PRARM_CONF,dat)
  736. end
  737. --- 下发设置时控参数
  738. -- @param dat, json数据结构
  739. function Set_timcontrol(dat)
  740. --四情平台设置
  741. if nvm.get("platform")== "120.27.222.26" then
  742. local cmds, result, err = json.decode(dat)
  743. if not result then
  744. log.error("Set_timcontrol error!!!!!")
  745. end
  746. timcontrl = cmds.ext
  747. log.warn("Set_timcontrol set the parameter value is: ", timcontrl)
  748. io.writeFile(CONTROL_CONF, dat)
  749. else
  750. --大数据平台设置
  751. local cmds, result, err = json.decode(dat)
  752. if not result then log.error("Set_timcontrol error!!!!!") end
  753. if cmds.ext.work_tim.timctrl ~= nil and type(cmds.ext.work_tim.timctrl) == "string" and tonumber(cmds.ext.work_tim.timctrl) >= 0 and tonumber(cmds.ext.work_tim.timctrl) <= 1 then
  754. timcontrl.timctrl = tonumber(cmds.ext.work_tim.timctrl)
  755. end
  756. if cmds.ext.work_tim.st ~= nil and type(cmds.ext.work_tim.st) == "string" and tonumber(cmds.ext.work_tim.st) >= 0 and tonumber(cmds.ext.work_tim.st) <= 23 then
  757. timcontrl.st = tonumber(cmds.ext.work_tim.st)
  758. end
  759. if cmds.ext.work_tim.et ~= nil and type(cmds.ext.work_tim.et) == "string" and tonumber(cmds.ext.work_tim.et) >= 0 and tonumber(cmds.ext.work_tim.et) <= 23 then
  760. timcontrl.et = tonumber(cmds.ext.work_tim.et)
  761. end
  762. log.warn("Set_timcontrol set the parameter value is: ", timcontrl)
  763. paramtable.ext.work_tim = timcontrl
  764. local dat = json.encode(paramtable) -- 参数配置存入文件
  765. io.writeFile(PRARM_CONF,dat)
  766. end
  767. end
  768. --- 下发参数配置信息
  769. -- @param dat, json数据结构
  770. function setParamConf(dat)
  771. local cmds, result, err = json.decode(dat)
  772. if not result then log.info("setParamConf set the parameter error!") end
  773. scdParam = cmds.ext
  774. log.warn("setParamConf set the parameter value is: ", paramconf)
  775. io.writeFile(DEVICE_CONF, dat)
  776. SetStatus()
  777. end
  778. --- 下发服务器配置信息
  779. -- @param dat, json数据结构
  780. function setServerConf(dat)
  781. local cmds, result, err = json.decode(dat)
  782. if not result then log.info("setServerConf set the parameter error!") end
  783. serverconf = cmds.ext
  784. log.warn("setServerConf set the parameter value is: ", serverconf)
  785. io.writeFile(SERVER_CONF, dat)
  786. end
  787. --- 下发第三方服务器配置信息
  788. -- @param dat, json数据结构
  789. function setThirdserverConf(dat)
  790. local cmds, result, err = json.decode(dat)
  791. if not result then log.info("setThirdserverConf set the parameter error!") end
  792. thirdserverconf = cmds.ext
  793. log.warn("setThirdserverConf set the parameter value is: ", thirdserverconf)
  794. io.writeFile(THIRD_CONF, dat)
  795. end
  796. --- 下发设置定位数据(--百度坐标系--)
  797. -- @param dat, json数据结构
  798. function Set_location(dat)
  799. local cmds, result, err = json.decode(dat)
  800. if not result then
  801. log.warn("Set work location failed!")
  802. end
  803. manual_location = cmds.ext
  804. log.warn("set manual_location is:",manual_location.lat,manual_location.lng)
  805. --paramtable.ext.location = manual_location
  806. --local dat = json.encode(paramtable) -- 参数配置存入文件
  807. io.writeFile(GPS_CONF,dat)
  808. end
  809. -----------------------------------------------------------------------------------------------------------------------------
  810. ---------------------------------------------------读取用户配置的参数----------------------------------------------------------
  811. --- 开机获取用户配置的参数
  812. function getConfig()
  813. local param, server,datt, third_ser,loc,param_conf, cmds, result, err
  814. param = io.readFile(DEVICE_CONF) -- 获取参数配置参数
  815. cmds, result, err = json.decode(param)
  816. if result then
  817. paramconf = cmds.ext
  818. end
  819. datt = io.readFile(DATTIM_CONF) -- 获取数据上传时间间隔参数
  820. cmds, result, err = json.decode(datt)
  821. if result then dat_f = cmds.ext.dat_f end
  822. server = io.readFile(SERVER_CONF) -- 开机读取主服务器配置
  823. cmds, result, err = json.decode(server)
  824. if result then
  825. serverconf = cmds.ext
  826. end
  827. third_ser = io.readFile(THIRD_CONF) -- 获取第三方服务器配置参数
  828. cmds, result, err = json.decode(third_ser)
  829. if result then
  830. thirdserverconf = cmds.ext
  831. end
  832. loc = io.readFile(GPS_CONF) -- 开机读取手动定位值
  833. cmds,result,err = json.decode(loc)
  834. if result then manual_location = cmds.ext end
  835. ----------------------------设备参数读取失败重置默认参数------------------------------------
  836. param_conf = io.readFile(PRARM_CONF)
  837. cmds, result, err = json.decode(param_conf)
  838. if result then
  839. dat_f = cmds.ext.data_tim.dat_f -- 获取数据上传时间间隔参数
  840. clt_t = cmds.ext.clt_tim.clt_t -- 获取清虫间隔参数
  841. timcontrl = cmds.ext.work_tim -- 获取时控控制参数
  842. if timcontrl == nil then
  843. timcontrl.st = 20
  844. timcontrl.et = 0
  845. timcontrl.timctrl = 0
  846. end
  847. -- manual_location = cmds.ext.location -- 获取手动定位值
  848. end
  849. end
  850. -----------------------------------------------------------------------------------------------------------------------------
  851. ------------------------------------------------- 物联网模块参数配置结束 ------------------------------------------------------
  852. -- +++++++++++++++++++++++++++++++++++++++++++++++++ 协程功能进程开始 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  853. -------------------------------------------------------定时清虫任务------------------------------------------------------------
  854. --+++++性诱测报III型设备没有定时清虫功能----可以屏蔽该段代码
  855. sys.taskInit(function()
  856. while true do
  857. sys.wait(clt_t * 60 *1000) --30分钟清虫一次
  858. Clearworm()
  859. log.warn("Clear worm time is:", clt_t)
  860. end
  861. end)
  862. -----------------------------------------------定时工作任务----------------------------------------------------
  863. -- 定时模式启动判断
  864. sys.taskInit(
  865. function()
  866. worksta = 0
  867. local workdone = 0 --(光控定时模式下)工作完成标志位
  868. local timeover = 0 --定时模式结束时间戳
  869. sys.wait(30 * 1000)
  870. --等待开机启动对时
  871. log.warn("Read timctrl is..................", timcontrl.timctrl)
  872. local c = misc.getClock()
  873. while true do
  874. while true do
  875. if c.year < 2020 then --如果未对时,关闭时控
  876. timcontrl.timctrl = 0
  877. c = misc.getClock()
  878. end
  879. if timcontrl.timctrl == 0 then -- 若时控关闭
  880. log.warn("it's not time control")
  881. log.warn("开始时间:", timcontrl.st, "结束时间:", timcontrl.et)
  882. worksta = 0
  883. workdone = 0
  884. end
  885. if timcontrl.timctrl == 1 then -- 若时控开启
  886. log.warn("it's time control", "start time:", timcontrl.st, "end time:", timcontrl.et)
  887. local c_sta = misc.getClock()
  888. c_sta.hour = timcontrl.st
  889. c_sta.min = 0
  890. c_sta.sec = 0
  891. if timcontrl.st < timcontrl.et then -- 如果开始和结束时间是同一天
  892. log.warn("the same day !!!!")
  893. local c_end = misc.getClock() -- **获取当前时间**
  894. c_end.hour = timcontrl.et
  895. c_end.min = 0
  896. c_end.sec = 0
  897. -- 如果当前时间大于开始时间且小于结束时间,且没有开始工作
  898. if os.difftime(os.time(), os.time(c_sta)) > 0 and os.difftime(os.time(), os.time(c_end)) < 0 and workdone == 0 then
  899. log.warn("模式1当前时间大于开始时间,且没有开始工作,当前时间小于结束时间的情况:计算结束时间戳")
  900. timeover = os.time(c_end)
  901. timeover = tonumber(timeover)
  902. worksta = 1
  903. break
  904. elseif os.difftime(os.time(), os.time(c_sta)) < 0 then
  905. log.warn("模式1当前时间小于开始时间!!!")
  906. worksta = 0
  907. elseif os.difftime(os.time(), os.time(c_end)) > 0 then
  908. log.warn("模式1当前时间大于结束时间!!!")
  909. worksta = 0
  910. end
  911. -- 如果工作完成:
  912. if workdone == 1 then
  913. workdone = 0
  914. end
  915. elseif timcontrl.st > timcontrl.et then -- 如果结束时间是第二天
  916. log.warn("not the same day !!!!")
  917. local n = misc.getClock() -- **获取当前时间**
  918. -- 如果当前时间大于开始时间,且没有开始工作 ,注意时间戳日期加1
  919. if os.difftime(os.time(), os.time(c_sta)) > 0 and workdone == 0 and n.hour > timcontrl.et then
  920. log.warn("模式2当前时间大于开始时间,且没有开始工作,当前时间位于0点之前,结束时间戳加1天,计算结束时间戳")
  921. local c_end = misc.getClock()
  922. c_end.hour = timcontrl.et
  923. c_end.min = 0
  924. c_end.sec = 0
  925. timeover = os.time(c_end) + 3600 * 24
  926. timeover = tonumber(timeover)
  927. worksta = 1
  928. break
  929. elseif os.difftime(os.time(), os.time(c_sta)) > 0 and workdone == 0 and n.hour < timcontrl.et then
  930. log.warn("模式2当前时间大于开始时间,但是小于结束时间,当前时间位于0点之后,所以是重启引起的,时间戳不动,计算结束时间戳")
  931. local c_end = misc.getClock()
  932. c_end.hour = timcontrl.et
  933. c_end.min = 0
  934. c_end.sec = 0
  935. timeover = os.time(c_end)
  936. worksta = 1
  937. break
  938. elseif os.difftime(os.time(), os.time(c_sta)) < 0 then
  939. log.warn("模式2当前时间小于开始时间!!!")
  940. worksta = 0
  941. end
  942. -- 如果工作完成:
  943. if workdone == 1 then
  944. workdone = 0
  945. end
  946. end
  947. end
  948. sys.wait(1000)
  949. end
  950. -- 等待定时任务完成
  951. if timeover ~= nil or timeover ~= 0 then
  952. while (timeover > os.time()) do
  953. sys.wait(1000)
  954. log.warn("Working.....:", "over", timeover, "now:", os.time())
  955. end
  956. end
  957. log.info(" The workTask time is end!")
  958. ----------------------标志工作定时结束!!!++++
  959. worksta = 0
  960. workdone = 1
  961. ----------------------标志工作完成!!!++++
  962. sys.wait(1000)
  963. end
  964. end
  965. )
  966. -- 时控判断是否工作-------------------------------------------------
  967. sys.taskInit(
  968. function()
  969. sys.wait(20 * 1000)
  970. while true do
  971. if timcontrl.timctrl == 1 then --时控定时模式
  972. log.warn("Start Timng Mode....")
  973. if worksta == 1 then
  974. if result.ds == 0 then -- 如果设备关机
  975. setsw(1) --开机
  976. end
  977. else
  978. if result.ds == 1 then -- 如果设备开机
  979. setsw(0)
  980. end
  981. end
  982. end
  983. if timcontrl.timctrl == 0 then --光控
  984. log.warn("Light control mode...")
  985. end
  986. if timcontrl.timctrl ~= timcontrl.timctrl then --如果时控状态改变清除当前计数值
  987. infrared_count = 0
  988. end
  989. sys.wait(1000)
  990. end
  991. end
  992. )
  993. --时控工作修改光控工作状态消除时控工作状态下不能达到工作时长
  994. sys.taskInit(
  995. function ()
  996. local cnf, result, err = json.decode(dat)
  997. sys.wait(1000)
  998. while true do
  999. if timcontrl.timctrl == 1 then
  1000. tt = 0
  1001. setTimer(0)
  1002. end
  1003. sys.wait(1000)
  1004. end
  1005. end
  1006. )
  1007. -----------------------------------------------雨控即时上报----------------------------------------------------
  1008. --雨控即时上报
  1009. sys.taskInit(
  1010. function()
  1011. sys.wait(1000)
  1012. while true do
  1013. if rps_x == 1 then
  1014. updata_freq = 0
  1015. rps_x = 0
  1016. rps_y = 1
  1017. end
  1018. sys.wait(1000)
  1019. end
  1020. end
  1021. )
  1022. ------------------------------------------------------------协程通讯进程开始----------------------------------------------------------
  1023. -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MQTT1 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1024. sys.taskInit(function()
  1025. getConfig() -- 开机获取用户配置的参数
  1026. nvm.init("config.lua")
  1027. sys.wait(5000)
  1028. log.info("MQTT1 Task is start!")
  1029. -- 是否获取分配到的ip
  1030. while not socket.isReady() do
  1031. log.info("socket is not ready,err_num:", err_num)
  1032. err_num = err_num + 1
  1033. sys.wait(1000)
  1034. if err_num >= 600 then
  1035. rebootinfo = 2 -- ***SOCKET断开上报***(注意只针对120.27.222.26服务器)
  1036. io.writeFile(DEVICE_ERR, rebootinfo)
  1037. sys.restart("socket connect overtime!")
  1038. end
  1039. end
  1040. serverconf.ip = nvm.get("platform")
  1041. if serverconf.ip == "8.136.98.49" then
  1042. serverconf.port = 61883
  1043. sub = "/yfkj/xycb/s2c/" -- 服务器到客户端
  1044. pub = "/yfkj/xycb/c2s/" -- 客户端到服务器
  1045. lastwill = "/yfkj/xycb/offline/" -- 离线消息主题(部分)-->设备异常中断时用于mqtt服务器发布该设备的遗愿消息,个人网站客户端需订阅
  1046. elseif serverconf.ip == "120.27.222.26" then
  1047. serverconf.port = 1883
  1048. sub1 = "yfkj/xycb/s2c/" -- 服务器到客户端
  1049. pub1 = "yfkj/xycb/c2s/" -- 客户端到服务器
  1050. lastwill1 = "yfkj/xycb/offline/" -- 离线消息主题(部分)-->设备异常中断时用于mqtt服务器发布该设备的遗愿消息,个人网站客户端需订阅
  1051. end
  1052. if nvm.get("lat_lbs") ~= "" and nvm.get("lat_lbs") ~= nil then
  1053. lbs_loc_lat = nvm.get("lat_lbs")
  1054. lbs_loc_lng = nvm.get("lng_lbs")
  1055. gps_status = 2
  1056. end
  1057. if nvm.get("lat_gps") ~= "" and nvm.get("lat_gps") ~= nil then
  1058. gps_loc_lat = nvm.get("lat_gps")
  1059. gps_loc_lng = nvm.get("lng_gps")
  1060. gps_status = 1
  1061. end
  1062. if nvm.get("hum") ~= "" and nvm.get("hum") ~= nil then
  1063. hum = nvm.get("hum")
  1064. end
  1065. if nvm.get("temp") ~= "" and nvm.get("temp") ~= nil then
  1066. temp = nvm.get("temp")
  1067. end
  1068. -- 离线消息
  1069. willmsg.ext.imei = misc.getImei()
  1070. if serverconf.ip == "8.136.98.49" then
  1071. serverconf.lastwill = "/yfkj/xycb/offline/"
  1072. serverconf.pub = "/yfkj/xycb/c2s/"
  1073. serverconf.sub = "/yfkj/xycb/s2c/"
  1074. elseif serverconf.ip == "120.27.222.26" then
  1075. serverconf.lastwill = "yfkj/xycb/offline/"
  1076. serverconf.pub = "yfkj/xycb/c2s/"
  1077. serverconf.sub = "yfkj/xycb/s2c/"
  1078. end
  1079. local will = {qos = 1, retain = 0, topic = string.format(serverconf.lastwill .. misc.getImei()), payload = json.encode(willmsg)} -- 创建mqtt客户端--默认配置了MQTT遗愿消息
  1080. local mqttc = mqtt.client(misc.getImei(), serverconf.keepalive, serverconf.uid, serverconf.pwd, 1,will)
  1081. local pub = string.format(serverconf.pub .. misc.getImei())
  1082. local sub = string.format(serverconf.sub .. misc.getImei())
  1083. local mqtt_sta = true
  1084. while true do
  1085. -- 连接mqtt服务器
  1086. mqtt_sta = mqttc:connect(serverconf.ip, serverconf.port)
  1087. log.info('mqtt connect status::', mqtt_sta)
  1088. if mqtt_sta == false then
  1089. log.info("mqtt1 connect fail,try to reconnect!", tcp_cont)
  1090. tcp_cont = tcp_cont + 1
  1091. if tcp_cont >= 600 then
  1092. rebootinfo = 3 -- ***MQTT断开上报***
  1093. io.writeFile(DEVICE_ERR, rebootinfo)
  1094. sys.restart("mqtt1 reconnect overtime:60!!!")
  1095. end
  1096. end
  1097. -- 订阅主题
  1098. if mqttc:subscribe(sub, serverconf.qos) then
  1099. local reason = rtos.poweron_reason()
  1100. log.info("reason:", reason)
  1101. mqttc:publish(pub,upwarn("device_820UG","turnon:" ..rtos.poweron_reason() ..";stm32:"..nvm.get("reboot_stm8")..";freefilesize:" ..rtos.get_fs_free_size() .. ";VERSION:" .. VERSION .. ";"..PROJECT.. "&core_version:" .. rtos.get_version() ..";stm8:"..result.ver),serverconf.qos)
  1102. if serverconf.ip == "8.136.98.49" then
  1103. if not mqttc:publish(pub, upData(), serverconf.qos) then break end
  1104. elseif serverconf.ip == "120.27.222.26" then
  1105. if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end
  1106. if not mqttc:publish(pub, upData_120(), serverconf.qos) then break end
  1107. end
  1108. log.info("MQTT1 upload is done!")
  1109. while mqtt_sta==true do
  1110. mqtt_status = "true"
  1111. --local r, packet = mqttc:receive(dattim * 60 * 1000) -- 处理服务器下发指令
  1112. local r, packet, param = mqttc:receive(timeout * 1000 * 60, "NET_SENT_RDY_")
  1113. if r then -- 这里是有数据下发的处理
  1114. datalink = 2
  1115. local cnf, result, err = json.decode(packet.payload)
  1116. if result then
  1117. log.info("MQTT1 recv json is::::::::::::::::::::::::::::::::::::::::::::::", packet.payload)
  1118. if serverconf.ip == "8.136.98.49" then
  1119. -----------------------------------设备参数读取--------------------------------
  1120. if cnf.cmd == "read" then
  1121. if cnf.ext == 'data' then --参数读取
  1122. updata_freq = 0
  1123. elseif cnf.ext == 'paramconf' then --获取参数配置
  1124. if not mqttc:publish(pub, upParamConf(), serverconf.qos) then break end
  1125. elseif cnf.ext == 'serverconf' then --获取主服务器参数配置
  1126. if not mqttc:publish(pub, upServerConf(), serverconf.qos) then break end
  1127. updata_freq = 0
  1128. elseif cnf.ext == 'thirdserver_conf' then --获取第三方服务器配置
  1129. if not mqttc:publish(pub, upThirdserverConf(), serverconf.qos) then break end
  1130. updata_freq = 0
  1131. end
  1132. --------------------------------平台设备控制参数下发-----------------------------------
  1133. elseif cnf.cmd == 'paramconf' then
  1134. if cnf.ext.data_tim ~= nil then -- 大数据平台配置数据上传时间间隔
  1135. Set_dattim(packet.payload)
  1136. sys.wait(300)
  1137. end
  1138. if cnf.ext.clt_tim ~= nil then -- 大数据平台配置清虫时间间隔
  1139. Set_clttim(packet.payload)
  1140. sys.wait(300)
  1141. end
  1142. if cnf.ext.work_tim ~= nil then -- 大数据平台配置定时控制参数
  1143. Set_timcontrol(packet.payload)
  1144. sys.wait(300)
  1145. end
  1146. if cnf.ext.power ~= nil then -- 大数据平台开关机控制
  1147. setsw(tonumber(cnf.ext.power.ds))
  1148. sys.wait(300)
  1149. end
  1150. if cnf.ext.location ~= nil then -- 大数据平台下发手动定位
  1151. Set_location(packet.payload)
  1152. sys.wait(300)
  1153. end
  1154. if not mqttc:publish(pub, upres("SCD-paramconf","data_tim is".." "..cnf.ext.data_tim.dat_f.." ".."clt_tim is".." "..cnf.ext.clt_tim.clt_t.." ".."TimControl".." "..cnf.ext.work_tim.timctrl.." ".."start_time".." "..cnf.ext.work_tim.st.." ".."end_time".." "..cnf.ext.work_tim.et.." ".."power is".." "..cnf.ext.power.ds), serverconf.qos) then break end
  1155. ---------------------------------------------------------------------------------------------------------
  1156. elseif cnf.cmd == "clearworm" then -- 大数据平台清虫
  1157. if not mqttc:publish(pub, upres("xy-clrworm", "Remote clearworm action will run!!"), serverconf.qos) then break end
  1158. sys.publish("clearworm")
  1159. Clearworm()
  1160. updata_freq = 0
  1161. sys.wait(300)
  1162. elseif cnf.cmd == "reboot" then -- 大数据平台重启
  1163. if not mqttc:publish(pub, upres("air820-reboot", "System will restart!!"), serverconf.qos) then break end
  1164. sys.restart("Device remote restart")
  1165. elseif cnf.cmd == "update" then -- 大数据平台物联网模块升级
  1166. if not mqttc:publish(pub, upres("air820-updata", "System will update!!"), serverconf.qos) then break end
  1167. Update.run()
  1168. elseif cnf.cmd == "update_stm32" then -- 大数据平台主板stm32升级
  1169. if not mqttc:publish(pub, upres("update_stm32", "stm32 update will start!!"), serverconf.qos) then break end
  1170. stm8_update_sw = 1
  1171. update_stm32() --STM32远程升级
  1172. ----------------------------参数配置下发------------------------------
  1173. elseif cnf.cmd == 'param_conf' then -- 大数据平台设备参数配置下发
  1174. setParamConf(packet.payload)
  1175. updata_freq = 0
  1176. elseif cnf.cmd == 'server_conf' then -- 大数据平台服务器配置下发
  1177. setServerConf(packet.payload)
  1178. updata_freq = 0
  1179. sys.restart("server_conf done then restart!!!")
  1180. elseif cnf.cmd == 'thirdserver_conf' then -- 大数据平台第三方服务器配置下发
  1181. setThirdserverConf(packet.payload)
  1182. sys.restart("thirdserver_conf done then restart!!!")
  1183. elseif result and cnf.cmd=="platform" then----平台切换参数下发
  1184. if cnf.ext.type == "120.27.222.26" then
  1185. nvm.set("platform","120.27.222.26")
  1186. sys.restart("120.27.222.26")
  1187. elseif cnf.ext.type == "8.136.98.49" then
  1188. nvm.set("platform","8.136.98.49")
  1189. sys.restart("8.136.98.49")
  1190. end
  1191. local c = misc.getClock()
  1192. local date = string.format("%00004d-%02d-%02d %02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
  1193. if not mqttc:publish(pub,upwarn("平台操作","切换平台至:"..cnf.ext.type..",操作时间:"..date), serverconf.qos) then
  1194. break
  1195. end
  1196. end
  1197. elseif serverconf.ip == "120.27.222.26" then
  1198. if cnf.cmd == "read" then
  1199. if cnf.ext == 'status' then --状态读取
  1200. updata_freq = 0
  1201. elseif cnf.ext == 'data' then --参数读取
  1202. updata_freq = 0
  1203. elseif cnf.ext == 'paramconf' then --获取参数配置
  1204. if not mqttc:publish(pub, upParamConf(), serverconf.qos) then break end
  1205. elseif cnf.ext == 'serverconf' then --获取主服务器配置
  1206. if not mqttc:publish(pub, upServerConf(), serverconf.qos) then break end
  1207. elseif cnf.ext == 'thirdserver_conf' then --第三方服务器配置读取
  1208. if not mqttc:publish(pub, upThirdserverConf(), serverconf.qos) then break end
  1209. updata_freq = 0
  1210. end
  1211. elseif cnf.cmd == 'set' then
  1212. if cnf.ext.type == "data_tim" then -- 四情平台配置数据上传时间间隔
  1213. Set_dattim(packet.payload)
  1214. updata_freq = 0
  1215. sys.wait(300)
  1216. elseif cnf.ext.type == "work_tim" then -- 四情平台配置定时控制参数
  1217. Set_timcontrol(packet.payload)
  1218. updata_freq = 0
  1219. sys.wait(300)
  1220. else
  1221. log.error("EEEE:::::::::::::not set match:::::::::::::::EEEE")
  1222. end
  1223. elseif cnf.cmd == "ctrl" then
  1224. if cnf.ext.type == "power" then -- 四情平台开关机
  1225. if not mqttc:publish(pub, upres("Remote startup&shutdown action will run!", "ok"), serverconf.qos) then break end
  1226. setsw(cnf.ext.ds)
  1227. updata_freq = 0
  1228. sys.wait(300)
  1229. elseif cnf.ext == "clearworm" then -- 四情平台清虫
  1230. if not mqttc:publish(pub, upres("Remote clearworm action will run!", "ok"), serverconf.qos) then break end
  1231. sys.publish("clearworm")
  1232. Clearworm()
  1233. updata_freq = 0
  1234. sys.wait(300)
  1235. end
  1236. elseif cnf.cmd == "timer" then --下发设置光控定时时长参数
  1237. setTimer(cnf.ext.tt)
  1238. sys.wait(300)
  1239. if not mqttc:publish(pub, upData_120(), serverconf.qos) then break end
  1240. elseif cnf.cmd == "location" then -- 四情平台下发手动定位
  1241. Set_location(packet.payload)
  1242. if not mqttc:publish(pub, upres("Set the location", "OK"), serverconf.qos) then break end
  1243. elseif cnf.cmd == "reboot" then -- 四情平台重启
  1244. log.warn("Device remote reboot!!!!!")
  1245. if not mqttc:publish(pub, upres("air820-reboot", "system will restart!!", "ok"), serverconf.qos) then break end
  1246. sys.restart("Device remote restart")
  1247. elseif cnf.cmd == "update" then -- 四情平台物联网模块升级
  1248. log.warn("Device remote update!!!!!")
  1249. if not mqttc:publish(pub, upres("air820-updata", "system update will start!!", "ok"), serverconf.qos) then break end
  1250. Update.run()
  1251. elseif cnf.cmd == "update_stm32" then -- 四情平台平台主板stm32升级
  1252. if not mqttc:publish(pub, upres("update_stm32", "stm32 update will start!!"), serverconf.qos) then break end
  1253. stm8_update_sw = 1
  1254. update_stm32() --STM32远程升级
  1255. -------------------------------
  1256. elseif cnf.cmd == 'paramconf' then --四情平台下发参数配置
  1257. setParamConf(packet.payload)
  1258. updata_freq = 0
  1259. sys.restart("paramconf done then restart!!!")
  1260. elseif cnf.cmd == 'server_conf' then -- 四情平台服务器配置下发
  1261. setServerConf(packet.payload)
  1262. updata_freq = 0
  1263. sys.restart("server_conf done then restart!!!")
  1264. elseif cnf.cmd == 'thirdserver_conf' then --四情平台下第三方发服务器参数配置
  1265. setThirdserverConf(packet.payload)
  1266. sys.restart("thirdserver_conf done then restart!!!")
  1267. elseif result and cnf.cmd=="platform" then --四情平台平台切换参数下发
  1268. if cnf.ext.type == "120.27.222.26" then
  1269. nvm.set("platform","120.27.222.26")
  1270. sys.restart("120.27.222.26")
  1271. elseif cnf.ext.type == "8.136.98.49" then
  1272. nvm.set("platform","8.136.98.49")
  1273. sys.restart("8.136.98.49")
  1274. end
  1275. local c = misc.getClock()
  1276. local date = string.format("%00004d-%02d-%02d %02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
  1277. if not mqttc:publish(pub,upwarn("平台操作","切换平台至:"..cnf.ext.type..",操作时间:"..date), serverconf.qos) then
  1278. break
  1279. end
  1280. end
  1281. elseif result and cnf.cmd=="sensor" then --温湿度
  1282. Setsensor_value(packet.payload)
  1283. if nvm.get("json_w_stm8boot") ~= "" and nvm.get("json_w_stm8boot") ~= nil then
  1284. if mqttc:publish(pub, upwarn(nvm.get("json_w_stm8boot"),"主板重启"), serverconf.qos) then
  1285. nvm.set("json_w_stm8boot","")
  1286. end
  1287. end
  1288. if nvm.get("json_w_stm32_app") ~= "" and nvm.get("json_w_stm32_app") ~= nil then
  1289. if mqttc:publish(pub, upwarn(nvm.get("json_w_stm32_app"),"输出故障"), serverconf.qos) then
  1290. nvm.set("json_w_stm32_app","")
  1291. end
  1292. end
  1293. end
  1294. else
  1295. log.error("EEEE:::::::::::::not json download::::::::::::::EEEE")
  1296. end
  1297. end
  1298. if packet == "NET_SENT_RDY_" then
  1299. timeout = 60
  1300. log.info("updata is", param)
  1301. if not mqttc:publish(pub, param, serverconf.qos) then
  1302. break
  1303. end
  1304. end
  1305. end
  1306. end
  1307. mqttc:disconnect()
  1308. log.info("=============mqtt1 disconnect=============")
  1309. sys.wait(1000)
  1310. datalink = 0 -- 服务器断开链接数据指示灯慢闪
  1311. end
  1312. end)
  1313. -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MQTT2 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1314. sys.taskInit(function()
  1315. sys.wait(10*1000)
  1316. getConfig() -- 开机获取用户配置的参数
  1317. log.warn('MQTT2 Task is running!!!!!!!!!!')
  1318. if thirdserverconf.ip == "" or thirdserverconf.ip == nil then
  1319. log.info("MQTT2 Ip Not Set!")
  1320. return
  1321. end
  1322. -- 是否获取分配到的ip
  1323. while not socket.isReady() do
  1324. log.info("socket2 is not ready,err2_num:", err2_num)
  1325. err2_num = err2_num + 1
  1326. sys.wait(1000)
  1327. if err2_num >= 600 then
  1328. log.warn("socket2 connect overtime!") --软件重启(重启原因:socket connect overtime!)注意:重启后的trace中会打印出此重启原因
  1329. end
  1330. end
  1331. -- 离线消息
  1332. willmsg.ext.imei = misc.getImei()
  1333. will2 = {qos = 1, retain = 0, topic = string.format(thirdserverconf.lastwill .. misc.getImei()), payload = json.encode(willmsg)}-- 创建mqtt客户端--默认配置了MQTT遗愿消息
  1334. local mqttc2 = mqtt.client(misc.getImei(), thirdserverconf.keepalive, thirdserverconf.uid, thirdserverconf.pwd, 1, will2)
  1335. -- 拼接主题
  1336. local pub2 = string.format(thirdserverconf.pub .. misc.getImei())
  1337. local sub2 = string.format(thirdserverconf.sub .. misc.getImei())
  1338. local mqtt2_sta = true
  1339. while true do
  1340. mqtt2_sta = mqttc2:connect(thirdserverconf.ip, thirdserverconf.port)
  1341. log.info('mqtt2 connect status::', mqtt2_sta)
  1342. if mqtt2_sta == false then
  1343. log.info("mqtt2 connect fail,try to reconnect!", tcp2_cont)
  1344. tcp2_cont = tcp2_cont + 1
  1345. if tcp2_cont >= 50 then
  1346. tcp2_cont = 0
  1347. sys.restart("mqtt2 reconnect overtime:30!!!")
  1348. end
  1349. end
  1350. -- 订阅主题
  1351. if mqttc2:subscribe(sub2, thirdserverconf.qos) then
  1352. log.warn("------------------------------------------*-*-*-*---*-------------------------------------------")
  1353. if not mqttc2:publish(pub, upData(), thirdserverconf.qos) then break end
  1354. log.info("'mqtt2 First upload data is done!!!!!'")
  1355. log.warn("*********************************************-*-*-*---*-********************************************")
  1356. sys.wait(2000)
  1357. while mqtt2_sta==true do
  1358. local r, packet, param = mqttc2:receive(timeout * 1000 * 60, "NET_SENT_RDY_")
  1359. if r then -- 这里是有数据下发的处理
  1360. local cnf, result, err = json.decode(packet.payload) -- json解析
  1361. if result then
  1362. log.info("::::::::::::::::::::::::::::::::::::::::MQTT2 recv json is::::::::::::::::::::::::::::::::::::::::::", packet.payload)
  1363. if cnf.cmd == "read" then
  1364. if cnf.ext == "data" then
  1365. updata_freq = 0
  1366. end
  1367. -- ++++++下发设置/远程设置++++++
  1368. elseif cnf.cmd == "paramconf" then -- 参数配置
  1369. if cnf.ext.data_tim ~= nil then -- 平台配置数据上传时间间隔
  1370. if not mqttc:publish(pub, upres("xy-dat_f", "Remote set data_tim!!"), serverconf.qos) then break end
  1371. Set_dattim(packet.payload)
  1372. sys.wait(300)
  1373. end
  1374. if cnf.ext.clt_tim ~= nil then -- 平台配置清虫时间间隔
  1375. if not mqttc:publish(pub, upres("xy-clt_f", "Remote set clt_tim!!"), serverconf.qos) then break end
  1376. Set_clttim(packet.payload)
  1377. sys.wait(300)
  1378. end
  1379. if cnf.ext.work_tim ~= nil then -- 平台配置定时控制参数
  1380. if not mqttc:publish(pub, upres("xy-timcotrl", "Remote set work_tim!!"), serverconf.qos) then break end
  1381. Set_timcontrol(packet.payload)
  1382. sys.wait(300)
  1383. end
  1384. if cnf.ext.power ~= nil then -- 平台开关机控制
  1385. if not mqttc:publish(pub, upres("xy-switch", "Remote startup&shutdown action will run!!"), serverconf.qos) then break end
  1386. setsw(tonumber(cnf.ext.power.ds))
  1387. sys.wait(300)
  1388. end
  1389. if cnf.ext.location ~= nil then -- 平台下发手动定位
  1390. Set_location(packet.payload)
  1391. if not mqttc:publish(pub, upres("xy-manual_location", "Remote set manual_location!!"), serverconf.qos) then break end
  1392. end
  1393. if not mqttc:publish(pub, upData(), serverconf.qos) then break end
  1394. updata_freq = 0
  1395. elseif cnf.cmd == "clearworm" then -- 平台手动下发清虫
  1396. if not mqttc:publish(pub, upres("xy-clrworm", "Remote clearworm action will run!!"), serverconf.qos) then break end
  1397. Clearworm()
  1398. updata_freq = 0
  1399. elseif cnf.cmd == "reboot" then -- 物联网模块重启
  1400. if not mqttc:publish(pub, upres("air820-reboot", "System will restart!!"), serverconf.qos) then break end
  1401. sys.restart("Device remote restart")
  1402. elseif cnf.cmd == "update" then -- 物联网模块升级
  1403. if not mqttc:publish(pub, upres("air820-updata", "System will update!!"), serverconf.qos) then break end
  1404. Update.run()
  1405. elseif cnf.cmd == "update_stm32" then -- 四情平台平台主板stm32升级
  1406. if not mqttc:publish(pub, upres("update_stm32", "stm32 update will start!!"), serverconf.qos) then break end
  1407. stm8_update_sw = 1
  1408. update_stm32() --STM32远程升级
  1409. end
  1410. end
  1411. end
  1412. if packet == "NET_SENT_RDY_" then
  1413. timeout = 60
  1414. log.info("updata is", param)
  1415. if not mqttc2:publish(pub2, param, thirdserverconf.qos) then break end
  1416. end
  1417. end
  1418. end
  1419. mqttc2:disconnect()
  1420. sys.wait(1000)
  1421. end
  1422. sys.restart("mqtt2 first publish message is error cause mqtt task is break!")
  1423. end)
  1424. -- +++++++++++++++++++++++++++++++++++++++++++++ *网络状况监控任务* ++++++++++++++++++++++++++++++++++++++++++++++++++
  1425. -- 网络状况监控任务:
  1426. sys.taskInit(function()
  1427. local err = 0
  1428. -- 等待设备联网:
  1429. log.warn("***************socket monitor task is running!***************")
  1430. while true do
  1431. while not socket.isReady() do
  1432. log.warn("socket is not Ready,", "err:", err)
  1433. err = err + 1
  1434. if err >= 600 then
  1435. sys.restart("socket connect err overtime:30!!!")
  1436. end
  1437. sys.wait(1000)
  1438. end
  1439. sys.wait(1000)
  1440. end
  1441. end)
  1442. --+++++++++++++++++++++++++++++++++++++++++++++++ * LBS+GPS定位任务 开始* ++++++++++++++++++++++++++++++++++++++++++++++++++
  1443. --[[
  1444. 功能 :获取基站对应的经纬度后的回调函数
  1445. 参数 :
  1446. result:number类型,0表示成功,1表示网络环境尚未就绪,2表示连接服务器失败,3表示发送数据失败,4表示接收服务器应答超时,5表示服务器返回查询失败;为0时,后面的3个参数才有意义
  1447. lat:string类型,纬度,整数部分3位,小数部分7位,例如031.2425864
  1448. lng:string类型,经度,整数部分3位,小数部分7位,例如121.4736522
  1449. 返回值:无
  1450. ]]
  1451. -- LBS定位回调函数 GCJ02(火星坐标)-->需转换BD-09(百度坐标)
  1452. function getLocCb(result, lat, lng) --注意:进入此函数时LBS已经定位成功
  1453. if result == 0 then --如果result=0,表示定位成功
  1454. log.info("get LBS location success!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  1455. log.warn("testLbsLoc.getLocCb*****************", result, lat, lng)
  1456. lbs_loc_lat = lat
  1457. lbs_loc_lng = lng
  1458. log.warn("get LBS location message >>>>>>>>>>>>>>>>>>>>>>>>>>", lbs_loc_lat, lbs_loc_lng)
  1459. gps_status = 2
  1460. nvm.set("lat_lbs",lat)
  1461. nvm.set("lng_lbs",lng)
  1462. else
  1463. log.info("get LBS location failed!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  1464. end
  1465. end
  1466. -- GPS日志信息输出函数 WGS-84(国际标准GPS原始坐标)-->需转换BD-09(百度坐标)
  1467. local function printGps()
  1468. if gps.isOpen() then
  1469. local tLocation = gps.getLocation()
  1470. local speed = gps.getSpeed()
  1471. log.info("testGps.printGps",
  1472. gps.isOpen(),
  1473. gps.isFix(),
  1474. tLocation.lngType,
  1475. tLocation.lng,
  1476. tLocation.latType,
  1477. tLocation.lat, -- 度格式的经纬度信息
  1478. gps.getAltitude(), -- 海拔
  1479. speed, -- 速度
  1480. gps.getCourse(), -- 方向角
  1481. gps.getViewedSateCnt(), -- 可见卫星的个数
  1482. gps.getUsedSateCnt()) -- 定位使用的卫星个数
  1483. end
  1484. end
  1485. ---------------------- GPS 模式切换 ------------------------------
  1486. local function test1Cb(tag)
  1487. log.info("testGps.test1Cb",tag)
  1488. printGps()
  1489. end
  1490. local function test2Cb(tag)
  1491. log.info("testGps.test2Cb",tag)
  1492. printGps()
  1493. end
  1494. local function test3Cb(tag)
  1495. log.info("testGps.test3Cb",tag)
  1496. printGps()
  1497. end
  1498. --测试代码开关,取值1,2
  1499. local testIdx = 1
  1500. local function test(idx)
  1501. --第1种测试代码
  1502. if idx==1 then
  1503. --执行完下面三行代码后,GPS就会一直开启,永远不会关闭
  1504. --因为gps.open(gps.DEFAULT,{tag="TEST1",cb=test1Cb}),这个开启,没有调用gps.close关闭
  1505. gps.open(gps.DEFAULT,{tag="TEST1",cb=test1Cb})
  1506. --10秒内,如果gps定位成功,会立即调用test2Cb,然后自动关闭这个“GPS应用”
  1507. --10秒时间到,没有定位成功,会立即调用test2Cb,然后自动关闭这个“GPS应用”
  1508. gps.open(gps.TIMERORSUC,{tag="TEST2",val=10,cb=test2Cb})
  1509. --300秒时间到,会立即调用test3Cb,然后自动关闭这个“GPS应用”
  1510. gps.open(gps.TIMER,{tag="TEST3",val=300,cb=test3Cb})
  1511. --第2种测试代码
  1512. elseif idx==2 then
  1513. --执行完下面三行代码打开GPS后,5分钟之后GPS会关闭
  1514. gps.open(gps.DEFAULT,{tag="TEST1",cb=test1Cb})
  1515. sys.timerStart(gps.close,300000,gps.DEFAULT,{tag="TEST1"})
  1516. gps.open(gps.TIMERORSUC,{tag="TEST2",val=10,cb=test2Cb})
  1517. gps.open(gps.TIMER,{tag="TEST3",val=60,cb=test3Cb})
  1518. end
  1519. end
  1520. --------------------------------------------------------------------
  1521. local function nmeaCb(nmeaItem)
  1522. log.info("testGps.nmeaCb",nmeaItem)
  1523. end
  1524. -- GPS+LBS定位任务
  1525. sys.subscribe("AUTOGPS_READY",function(gpsLib,agpsLib,kind,baudrate)
  1526. gps=gpsLib
  1527. agps=agpsLib
  1528. log.info("testGps.AUTOGPS_READY",baudrate,kind)
  1529. gps.setUart(uartId,baudrate,8,uart.PAR_NONE,uart.STOP_1) -- 设置串口通信参数,波特率为自适应
  1530. gps.setNmeaMode(2,nmeaCb) -- gps.lua和外部程序都处理NEMA数据
  1531. test(testIdx)
  1532. sys.timerLoopStart(printGps,2000)
  1533. end)
  1534. sys.taskInit(
  1535. function()
  1536. while true do
  1537. gps_status = 0
  1538. locat_cnt = 0
  1539. sys.wait(8 * 1000) -- 等待socket连接完毕
  1540. while true do
  1541. if tonumber(manual_location.type) == 0 then -- 判断是否手动定位 若手动定位直接关闭GPS
  1542. if socket.isReady() and gps_status ~=1 and gps_status ~= 2 then
  1543. log.warn("================ LBS Location successful ===============")
  1544. lbsLoc.request(getLocCb)
  1545. sys.wait(1000)
  1546. end
  1547. if gps.isFix() == false then
  1548. log.info("================ GPS Location failed ===============")
  1549. printGps()
  1550. elseif gps.isFix() == true then
  1551. gps_cont = gps_cont + 1
  1552. local location = gps.getLocation()
  1553. gps_loc_lat = location.lat
  1554. gps_loc_lng = location.lng
  1555. printGps()
  1556. if gps_cont >= 3 then -- 获取3次gps定位数据的最后一次
  1557. nvm.set("lat_gps",gps_loc_lat)
  1558. nvm.set("lng_gps",gps_loc_lng)
  1559. gps.closeAll()
  1560. end
  1561. gps_status = 1
  1562. log.info("================ GPS Location successful ===============")
  1563. end
  1564. sys.wait(1000)
  1565. log.info("GPS open status is:", gps.isOpen())
  1566. log.info("GPS location status is:", gps.isFix())
  1567. else
  1568. gps_status = 0
  1569. gps.closeAll()
  1570. sys.wait(2000)
  1571. end
  1572. sys.wait(1000)
  1573. locat_cnt = locat_cnt + 1
  1574. if locat_cnt >= 1800 then -- 每隔30分钟判断一下定位,若失败,则break
  1575. if (gps_loc_lng == "0" and gps_loc_lat == "0") and (lbs_loc_lat == "0" and lbs_loc_lng == "0") then
  1576. break
  1577. else
  1578. locat_cnt = 0
  1579. log.warn("location normal !!!")
  1580. end
  1581. end
  1582. end
  1583. end
  1584. end
  1585. )
  1586. ------------------------------------------------------ * LBS+GPS定位任务 结束* ------------------------------------------------
  1587. --++++++++++++++++++++++++++++++++++++++++++++++++++++ * SIM卡自动切换线程 * +++++++++++++++++++++++++++++++++++++++++++++++++++
  1588. local function cbFnc(result)
  1589. if result then
  1590. log.info("SIM switch successful")
  1591. else
  1592. log.info("SIM switch failed")
  1593. end
  1594. end
  1595. -- 说明:目前版本不支持SIM自动切换功能需手动切换SIM卡
  1596. -- 注意:本命令关机保存,但是需重启生效
  1597. -- 初次刷入程序默认SIM ID = 0
  1598. sys.taskInit(
  1599. function()
  1600. sys.wait(5 * 1000) -- 注意:开机lua脚本运行之后,会发送at命令去查询id,所以需要一定时间才能获取到id。开机后立即调用此接口,基本上返回nil
  1601. local ID1 = sim.getId()
  1602. local ID2 = ID1
  1603. log.info("Now SIM is:::", ID1)
  1604. if ID1 == 0 then
  1605. ID2 = 1
  1606. elseif ID1 == 1 then
  1607. ID2 = 0
  1608. end
  1609. sys.wait(5 * 1000)
  1610. while true do
  1611. if sim.getStatus() == false or sim.getStatus() == nil then -- 切换SIM卡
  1612. sim.setId(ID2,cbFnc)
  1613. sys.wait(1000)
  1614. sim.setId(ID2,cbFnc)
  1615. sys.restart("switch sim card")
  1616. end
  1617. local id = sim.getId() -- 获取目前设置的双卡单待id
  1618. log.info("Now system SIM card is:::", id)
  1619. sys.wait(5 * 1000)
  1620. end
  1621. end
  1622. )
  1623. --+++++++++++++++++++++++++++++++++++++++++++++++ * MQTT守护线程 * ++++++++++++++++++++++++++++++++++++++++++++++++
  1624. -- Mqtt异常监测
  1625. sys.taskInit(function()
  1626. sys.wait(10*1000)
  1627. local dev_dta_on = 1
  1628. while true do
  1629. if mqtt_status == "" then
  1630. mqtt_status_num = mqtt_status_num + 1
  1631. elseif mqtt_status == "true" then
  1632. mqtt_status = ""
  1633. mqtt_status_num = 0
  1634. sys.wait(1000)
  1635. end
  1636. if mqtt_status_num > timeout * 61 then
  1637. sys.restart("MQTT ERROR!!!")
  1638. end
  1639. log.warn("====================mqtt_check=================:",mqtt_status_num,mqtt_status,timeout)
  1640. sys.wait(1000)
  1641. end
  1642. end)
  1643. ---------------------------------------------------------------
  1644. --定时上报任务
  1645. sys.taskInit(
  1646. function()
  1647. sys.wait(15*1000)
  1648. if dat_f ==0 or dat_f == nil or dat_f =="" then
  1649. dat_f = 30
  1650. end
  1651. while true do
  1652. updata_freq = dat_f * 60
  1653. while updata_freq ~= 0 do
  1654. updata_freq = updata_freq - 1
  1655. sys.wait(1000)
  1656. log.info("++++++++ 1 !!!!!!!!")
  1657. end
  1658. if serverconf.ip == "8.136.98.49" then
  1659. sys.publish("NET_SENT_RDY_", upData())
  1660. infrared_count = 0
  1661. ClearKcnt() -- 上报数据清除电机次数
  1662. log.info("++++++++ 2 !!!!!!!!")
  1663. elseif serverconf.ip == "120.27.222.26" then
  1664. sys.publish("NET_SENT_RDY_", upData_120())
  1665. sys.publish("NET_SENT_RDY_", upStatus())
  1666. infrared_count = 0
  1667. ClearKcnt() -- 上报数据清除电机次数
  1668. log.info("++++++++ 3 !!!!!!!!")
  1669. end
  1670. sys.wait(100)
  1671. log.info("+++++++++ 4 !!!!!!!!")
  1672. end
  1673. end
  1674. )
  1675. -- 每隔5秒更新主板数据and打印
  1676. sys.taskInit(function()
  1677. sys.wait(5 * 1000)
  1678. while true do
  1679. log.warn("................................Mainboard-uart 通信中1....................................")
  1680. PrintData()
  1681. --getStatus()
  1682. local firmware_name = rtos.get_version() -- 获取底层固件版本
  1683. local space = rtos.get_fs_free_size() -- 获取文件系统剩余空间(单位Bytes)
  1684. local netmode = net.getNetMode() -- 4:4G LTE网络
  1685. local SIMS = sim.getStatus() -- 获取sim卡的状态
  1686. log.warn("Clear worm time is:", clt_t)
  1687. log.warn("Data time is:", dat_f)
  1688. log.warn("Now firmware version is:", firmware_name .. " PROJECT:" .. _G.PROJECT .. " VERSION:" .. _G.VERSION)
  1689. log.warn("File system free space:", space)
  1690. log.warn("Net mode is:", netmode)
  1691. log.warn("Sim status is:", SIMS)
  1692. sys.wait(5 * 1000)
  1693. end
  1694. end)
  1695. --++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1696. -- 重启预警函数
  1697. function getRebootState()
  1698. rebootstate = io.readFile(DEV_REBOOT) -- 开机获取设备启动次数
  1699. rebootinfo = io.readFile(DEVICE_ERR) -- 开机获取设备软件重启原因
  1700. if rebootstate == nil then
  1701. log.info("first startup!!!!!!!!")
  1702. rebootstate = 0
  1703. end
  1704. rebootstate = rebootstate + 1
  1705. io.writeFile(DEV_REBOOT, rebootstate)
  1706. end
  1707. --------------------------------------------光栅计数线程---------------------------------------------------
  1708. sys.taskInit(function()
  1709. -- GPIO中断处理函数(修正递归调用问题)
  1710. local function gpioInterruptHandler(msg)
  1711. log.info("GPIO中断", "触发类型:", msg)
  1712. if msg == cpu.INT_GPIO_POSEDGE then
  1713. if result_crc.ds == 1 then
  1714. infrared_count = infrared_count + 1 -- 操作局部变量
  1715. log.info("红外计数器", "当前值:", infrared_count)
  1716. log.info("GPIO_2", "检测到上升沿触发")
  1717. else
  1718. infrared_count = 0
  1719. end
  1720. else
  1721. log.info("GPIO_2", "非上升沿触发事件")
  1722. end
  1723. end
  1724. -- 配置GPIO引脚及中断
  1725. local function setupGPIO()
  1726. log.info("GPIO初始化", "开始配置P0_2...")
  1727. local pin = pins.setup(pio.P0_2, gpioInterruptHandler,pio.PULLUP)-- 绑定处理函数
  1728. if not pin then
  1729. log.error("GPIO配置", "P0_2初始化失败!")
  1730. return false
  1731. end
  1732. log.info("GPIO配置", "P0_2上升沿中断已启用")
  1733. return true
  1734. end
  1735. -- 主任务逻辑
  1736. if setupGPIO() then
  1737. while true do
  1738. sys.wait(1000) -- 示例:每1秒输出当前计数
  1739. log.info("状态报告", "累计触发次数:", infrared_count)
  1740. end
  1741. else
  1742. log.error("任务终止", "GPIO初始化失败")
  1743. end
  1744. end)
  1745. -- function Interrupt_re(msg)
  1746. -- log.info("testGpioSingle.gpio2IntFnc",msg,Interrupt_re())
  1747. -- log.info("first infrared_count!!!!!!!!")
  1748. -- if msg == cpu.INT_GPIO_POSEDGE then
  1749. -- infrared_count = infrared_count + 1
  1750. -- log.info("infrared_count", infrared_count)
  1751. -- log.info("GPIO_2 被触发")
  1752. -- else
  1753. -- log.info("GPI0_2 未触发")
  1754. -- end
  1755. -- end
  1756. -- Interrupt_re = pins.setup(pio.P0_2,Interrupt_re,pio.PULLUP)
  1757. --------------------------------------------光栅计数线程---------------------------------------------------
  1758. ---+++++++++++++++++++++++++++++++++++++++++++++ * Mainboard-uart 通信中 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  1759. --每隔10秒打印输出
  1760. sys.taskInit(
  1761. function()
  1762. getRebootState()
  1763. sys.wait(100)
  1764. while true do
  1765. log.warn("................................Mainboard-uart 通信中....................................")
  1766. PrintData()
  1767. sys.wait(5 * 1000)
  1768. end
  1769. end
  1770. )
  1771. --BootLoader交互信息下发
  1772. sys.taskInit(
  1773. function()
  1774. sys.wait(500)
  1775. while true do
  1776. if BootLoader_flag == 1 then
  1777. BootLoader_flag = 0
  1778. log.info("BootLoader_flag",BootLoader_flag)
  1779. BootLoader_stm32()
  1780. log.info("stm32 SerialDownload !!!")
  1781. end
  1782. if upgrade_again == 1 then
  1783. log.info("update_stm32 system will upgrade again !!!")
  1784. update32.run()
  1785. end
  1786. sys.wait(500)
  1787. end
  1788. end
  1789. )
  1790. --串口通讯心跳交互
  1791. sys.taskInit(
  1792. function()
  1793. sys.wait(100)
  1794. local uart_flag_count = 0
  1795. local uart_32 = string.char(0xCC,0XDD)
  1796. while true do
  1797. if uart_flag == 1 then
  1798. uart_flag = 0
  1799. uart_flag_count = uart_flag_count + 1
  1800. if uart_flag_count > 5 then
  1801. uart_flag_count = 0
  1802. uart.write(1,uart_32)
  1803. log.info("uart_flag back!!!!")
  1804. end
  1805. end
  1806. sys.wait(50)
  1807. end
  1808. end
  1809. )
  1810. -- 串口缓冲区最大值
  1811. local SENDSIZE = 128
  1812. --串口写空闲
  1813. local writeIdle = {true}
  1814. --数据发送的消息队列
  1815. recvBuff = {{}}
  1816. local writeBuff = {{}}
  1817. local uartReadTime = 50 -- 串口读超时
  1818. local flowCount = {0, 0}
  1819. local uid = 1
  1820. -- 写标志位
  1821. local function writeDone()
  1822. if #writeBuff[1] == 0 then
  1823. writeIdle[1] = true
  1824. sys.publish("UART_" .. 1 .. "_WRITE_DONE")
  1825. log.warn("UART_" .. uid .. "write done!")
  1826. else
  1827. writeIdle[1] = false
  1828. uart.write(1, table.remove(writeBuff[1], 1))
  1829. log.warn("UART_" .. 1 .. "writing ...")
  1830. end
  1831. end
  1832. -- uart 写
  1833. function write(str)
  1834. if not str or str == "" or str == nil then
  1835. return
  1836. end
  1837. if str ~= true then
  1838. for i = 1, #str, SENDSIZE do
  1839. table.insert(writeBuff[1], str:sub(i, i + SENDSIZE - 1))
  1840. end
  1841. log.warn("uart" .. 1 .. ".write data length:", writeIdle[1], #str)
  1842. end
  1843. if writeIdle[1] and writeBuff[1] then
  1844. local str = table.concat(writeBuff[1])
  1845. table.remove(writeBuff[1], 1)
  1846. while true do
  1847. uart.write(1, str)
  1848. break
  1849. end
  1850. log.warn("UART_" .. uid .. "writing ...")
  1851. end
  1852. end
  1853. local function read(s)
  1854. local s = table.concat(recvBuff[1])
  1855. local idx, tmp = 1
  1856. local conf = s
  1857. recvBuff[1] = {}
  1858. -- 串口流量统计
  1859. flowCount[1] = flowCount[1] + #s
  1860. log.info("UART_" .. 1 .. "read length:", #s)
  1861. log.info("串口流量统计值:", flowCount[1])
  1862. log.info("UART:",s,string.toHex(s))
  1863. if updateflag == 1 then
  1864. log.info(s)
  1865. sys.publish("YM_IS_OK", s)
  1866. return
  1867. end
  1868. if s:find("update") then --判断是否进入升级模式
  1869. updateflag = 1
  1870. if update32.updateok == 0 then
  1871. s = upwarn("device_stm32", "system will update")
  1872. sys.publish("NET_SENT_RDY_", s)
  1873. else
  1874. s = upwarn("device_stm32", "system is updating......")
  1875. sys.publish("NET_SENT_RDY_", s)
  1876. end
  1877. log.info("update_stm32 system will update !!!")
  1878. update32.run()
  1879. end
  1880. if s:find("bootflag") then --重复远程升级标志位
  1881. upgrade_again = 1
  1882. end
  1883. if flowCount[1] == 64 then --串口通讯心跳检测
  1884. uart_flag = 1
  1885. end
  1886. if s:find("Lamp_fauit") then --判断灯管是否故障
  1887. local c = misc.getClock()
  1888. local date = string.format("%00004d-%02d-%02d %02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
  1889. log.info("检测到灯管故障!!!")
  1890. nvm.set("json_w_stm32_app","检测到杀虫灯LED灯管短路:".."故障时间:"..date)
  1891. end
  1892. if s:find("App") then --判断主板是否复位
  1893. local c = misc.getClock()
  1894. local date = string.format("%00004d-%02d-%02d %02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
  1895. log.info("检测到stm32复位!!!")
  1896. nvm.set("reboot_stm8",nvm.get("reboot_stm8")+1)
  1897. nvm.set("json_w_stm8boot","检测到主板复位,总复位次数:"..nvm.get("reboot_stm8").."复位时间:"..date)
  1898. end
  1899. if #conf == nil or #conf == 0 or conf:len() == 64 then
  1900. log.info("getParam len,value:", string.toHex(conf, " ")) -- 将返回的数据填充到result表
  1901. result.ver = string.sub(conf, 49,63) -- 软件版本-FX-SCD-U-V1.0
  1902. idx, result.iSave = pack.unpack(conf, "b", idx) -- eeprom标志位
  1903. if result.iSave ~= 0xAA then return end -- 判断chuankou上传数据格式是否正确
  1904. idx, result_crc.ds = pack.unpack(conf, ">b", idx) -- 设备状态
  1905. if(result_crc.ds==0 or result_crc.ds==1) then result.ds = result_crc.ds end
  1906. idx, result_crc.tt = pack.unpack(conf, "b", idx) -- 光控时长小时
  1907. if(result_crc.tt>=0 and result_crc.tt<8) then result.tt = result_crc.tt end
  1908. idx, result_crc.ws = pack.unpack(conf, "b", idx) -- 工作状态
  1909. if(result_crc.ws==0 or result_crc.ws==1 or result_crc.ws==2) then result.ws = result_crc.ws end
  1910. idx, result_crc.lps = pack.unpack(conf, "b", idx) -- 光控状态
  1911. if(result_crc.lps==0 or result_crc.lps==1) then result.lps = result_crc.lps end
  1912. idx, result_crc.rps = pack.unpack(conf, "b", idx) -- 雨控状态
  1913. if(result_crc.rps==0 or result_crc.rps==1) then
  1914. result.rps = result_crc.rps
  1915. if(result_crc.rps==1 and rps_y==0) then
  1916. rps_x = 1
  1917. elseif(result_crc.rps==0) then
  1918. rps_y = 0
  1919. end
  1920. end
  1921. idx, result_crc.tps = pack.unpack(conf, "b", idx) -- 温控状态
  1922. if(result_crc.tps==0 or result_crc.tps==1 or result_crc.tps==2) then result.tps = result_crc.tps end
  1923. idx, result_crc.dps = pack.unpack(conf, "b", idx) -- 倾倒保护
  1924. if(result_crc.dps==0 or result_crc.dps==1) then result.dps = result_crc.dps end
  1925. idx, result_crc.vps = pack.unpack(conf, "b", idx) -- 电压状态
  1926. if(result_crc.vps==0 or result_crc.vps==1 or result_crc.vps==2) then result.vps = result_crc.vps end
  1927. idx, result.lcm = pack.unpack(conf, "b", idx) -- 光控类型类型
  1928. idx, result.Lamp = pack.unpack(conf, 'b', idx) -- 灯管故障检测
  1929. idx, result.Infrared = pack.unpack(conf, 'b', idx) -- 红外传感器
  1930. idx, result.kcnt = pack.unpack(conf, "<H", idx) -- 电击击杀检测
  1931. if(result_crc.kcnt>0 and result_crc.kcnt<9000) then result.kcnt = result_crc.kcnt end
  1932. idx, result.cleartim = pack.unpack(conf, 'b', idx) -- 清虫时间间隔
  1933. idx, result.clear_on = pack.unpack(conf, 'b', idx) -- 自清虫标志位
  1934. idx, result.cycle_off = pack.unpack(conf, '<H', idx) --放电结束频率
  1935. idx, result_crc.cv = pack.unpack(conf, "<H", idx) -- 充电电压
  1936. if(result_crc.cv>0 and result_crc.cv<30000) then
  1937. result.cv = result_crc.cv
  1938. if result.cv < 500 then
  1939. result.cv = 0
  1940. end
  1941. end
  1942. idx, result_crc.bv = pack.unpack(conf, "<H", idx) -- 电池电压
  1943. if(result_crc.bv>0 and result_crc.bv<30000) then result.bv = result_crc.bv end
  1944. idx, result.bt = pack.unpack(conf, "<h", idx) -- 主板温度
  1945. idx, paramconf.vsunrise = pack.unpack(conf, "<H", idx) -- 日出电压
  1946. idx, paramconf.vsunset = pack.unpack(conf, "<H", idx) -- 日落电压
  1947. idx, paramconf.vcutof = pack.unpack(conf, "<H", idx) -- 充电截至电压
  1948. idx, paramconf.vfloat = pack.unpack(conf, "<H", idx) -- 充电浮充电压
  1949. idx, paramconf.vrecharge = pack.unpack(conf, "<H", idx) -- 再次启动充电动作的电压
  1950. idx, paramconf.vstart = pack.unpack(conf, "<H", idx) -- 首次启动电压
  1951. idx, paramconf.uvoff = pack.unpack(conf, "<H", idx) -- 欠压解锁电压
  1952. idx, paramconf.uvon = pack.unpack(conf, "<H", idx) -- 欠压锁定电压
  1953. idx, paramconf.overtemp = pack.unpack(conf, "<H", idx) -- 高温保护
  1954. idx, paramconf.lowtemp = pack.unpack(conf, "<H", idx) -- 低温保护
  1955. idx, paramconf.unovert = pack.unpack(conf, "<H", idx) -- 高温解锁
  1956. idx, paramconf.unlowt = pack.unpack(conf, "<H", idx) -- 低温解锁
  1957. return result
  1958. end
  1959. end
  1960. -- 串口配置
  1961. function uart_INIT()
  1962. uart.setup(1, 9600, 8, uart.PAR_NONE, uart.STOP_1)
  1963. uart.on(1, "sent", writeDone)
  1964. uart.on(
  1965. 1,
  1966. "receive",
  1967. function()
  1968. table.insert(recvBuff[1], uart.read(1, 8192))
  1969. sys.timerStart(sys.publish, tonumber(uartReadTime) or 30, "UART_RECV_WAIT_")
  1970. end
  1971. )
  1972. -- 处理串口接收到的数据
  1973. sys.subscribe("UART_RECV_WAIT_", read)
  1974. sys.subscribe("UART_SENT_RDY_", write)
  1975. end
  1976. local timecnt = 1
  1977. -- 每隔1分钟重置串口计数
  1978. sys.timerLoopStart(
  1979. function()
  1980. flow = tonumber(flow)
  1981. if flow and flow ~= 0 then
  1982. if flowCount[1] > flow then
  1983. uart.on(1, "receive")
  1984. log.info("uart1.read length count:", flowCount[1])
  1985. end
  1986. end
  1987. if timecnt > 10 then
  1988. timecnt = 1
  1989. flowCount = {0, 0}
  1990. else
  1991. timecnt = timecnt + 1
  1992. end
  1993. end,
  1994. 1000
  1995. )
  1996. --*********************开机运行**************************
  1997. uart_INIT()