| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142 |
- ---scd--@module testSocket--@author 稀饭放姜--@license MIT--@copyright hnyfkj.com--@release 2017.9.27
- require "socket"
- require "misc"
- require "led"
- require "mqtt"
- require "lbsLoc"
- require "pins"
- require "autoGPS" -- utoGPS功能模块只能配合Air820使用;如果不是这款模块,不要打开agps功能
- require "ril"
- require "Update"
- require "sim"
- ------------------------------
- require "config" --默认参数保存
- require "nvm"
- module(..., package.seeall)
- -- 本地存储文件
- local DEVICE_CONF = "/device.conf"
- local SERVER_CONF = "/server.conf"
- local DATTIM_CONF = "/dat_f.conf"
- local DEV_REBOOT = "/rebootmes.txt"
- local PRARM_CONF = "/prarm.conf"
- local CONTROL_CONF = "/control.txt"
- local THIRD_CONF = "/thirdconf.conf" --第三方服务器数据保存
- local SHT30_DATA = "/sht30data.conf" --温湿度参数保存
- local GPS_CONF = "/gps.conf" --保存GPS定位数据
- -- 上报json数据的基础表
- local message = {cmd = "", ext = {}}
- -- 上报遗言的json表
- local willmsg = {cmd = "offline", ext = {imei = ""}}
- -- 温湿度天气接口的值
- local temp, hum
- -- GPIO 输入检测
- pmd.ldoset(2, pmd.LDO_VLCD)
- -------红外计数------
- local infrared_count = 0
- --------------------------MQTT定时数据上报----------------------------
- local mqtt_status = "true"
- local mqtt_status_num = 0
- local timeout = 1
- local updata_freq = 0
- ---------------------------------------------------------------------
- --------------------------物联网模块重启--------------------------
- -- 重启标志
- local rebootstate
- -- 重启次数
- local rebootcnt
- -- 重启信息
- local rebootinfo = 1 --1:正常 2:socket重连 3:MQTT重连
- ----------------------------------------------------------------
- -- 清虫时间间隔
- local dat_f = 10
- -- 上报数据时间间隔
- local clt_t = 30
- local wsflag = 0
- local worktim = 0
- -- 光控模式状态标志位
- local clps = 0
- --雨控即时上报标志位
- local rps_x = 0
- local rps_y = 0
- ----------------------主板远程升级交互参数----------
- --置位BootLoader交互下发标志位 --全局变量定义参数
- updateflag = 0 --BootLoader进入升级模式标志位
- BootLoader_flag = 0 --BootLoader交互下发标志位
- upgrade_again =0 --STM32固件升级再次升级标志位
- bootend = 0 --STM32固件升级完成标志位
- local uart_flag = 0 --串口通讯交互心跳标志位
- stm8_update_sw = 0 --主板升级一键测试防误触
- -------------------------------------------------
- ---------------------MQTT1----------------------
- -- 检测是否分配到ip次数
- local err_num = 0
- -- TCP重连次数
- local tcp_cont = 0
- -- TCP连接正常的情况下,MQTT重订阅次数
- local sub_cont = 0
- -- mqtt1协程守护变量
- local mqtt1_cont = 1 * 60 * 60 -- 超时时间1小时
- ----------------------MQTT2---------------------
- -- 检测是否分配到ip次数
- local err2_num = 0
- -- TCP重连次数
- local tcp2_cont = 0
- -- mqtt2协程守护变量
- local mqtt2_cont = 1 * 60 * 60 -- 超时时间1小时
- ----------------------------------------------
- -- 时控参数配置
- local timcontrl = {
- type = "",
- timctrl = 0, --时控开关 0-关 1开 默认:时控关闭
- st = 20, --时控开始时间 默认:时间控制从半夜20点开始
- et = 2 --时控结束时间 默认:时间控制到次日2点结束
- }
- -- 配置参数保存基础表
- local paramtable = {
- cmd = "paramconf",
- ext = {
- power = {ds = 1}, -- 配置开关机状态
- work_tim = {timctrl = 0, st = 20, et = 2}, -- 配置定时控制模式
- data_tim = {dat_f = 10}, -- 配置数据上报时间间隔
- clt_tim = {clt_t = 30}, -- 配置清虫时间间隔
- }
- }
- -- -------------------------定位-------------------------
- -- LBS经纬度
- local lbs_loc_lat
- local lbs_loc_lng
- -- GPS经纬度
- local gps_loc_lat
- local gps_loc_lng
- -- 定位状态
- local gps_status = 0 -- 初始值0
- local locat_cnt = 0
- local gps,agps
- local uartId=3
- -- GPS定位次数(处理GPS模块返回数据次数)
- local gps_cont = 0
- -- 手动定位数据调度基础表 BD-09(百度坐标)-->不用坐标转换
- local manual_location = {lat = "0", lng = "0", type = "0"}
- -- ------------------------------------------------------
- -- MQTT1服务器配置表
- serverconf = {
- imei = "", -- 唯一ID
- ip = "8.136.98.49",
- port = 61883, -- MQTT服务端口
- sub = "/yfkj/xycb/s2c/", -- 服务器到客户端 -- 注意pub和sub后带" /" ,以便设备自动拼接imei
- pub = "/yfkj/xycb/c2s/", -- 客户端到服务器
- lastwill = "/yfkj/xycb/offline/", -- 离线消息主题(部分)-->设备异常中断时用于mqtt服务器发布该设备的遗愿消息,个人网站客户端需订阅
- sub1 = "yfkj/xycb/s2c/",
- pub1 = "yfkj/xycb/c2s/",
- lastwill1 = "yfkj/xycb/offline/",
- keepalive = 60, -- 心跳保持时间
- uid = "user", -- 用户名
- pwd = "f335bf402c655ee5fd2b5300905124e", -- 密码
- qos = 0
- }
- -- MQTT2服务配置表,用于设备对接
- thirdserverconf = {
- imei = "", -- 唯一ID
- ip = "",
- port = 1883,
- sub = "/yfkj/xycb/s2c/",
- pub = "/yfkj/xycb/c2s/",
- keepalive = 60,
- lastwill = "/yfkj/xycb/offline/",
- uid = "",
- pwd = "",
- qos = 0
- }
- -- 设备运行上报下发参数表
- local paramconf = {
- imei = "", -- 唯一ID
- tt = 0, -- 默认光控定时模式下定时时常0小时
- vsunrise = 6000, -- 日出电压
- vsunset = 1500, -- 日落电压
- lcm = 0, -- 光控类型 0太阳能板光控 1光敏二极管光控
- vstart = 12000, -- 首次启动电压
- uvon = 11500, -- 电池欠压锁定电压
- uvoff = 12500, -- 电池欠压解锁电压
- vrecharge = 12800, -- 再次启动充电动作的电压
- vfloat = 13600, -- 电池浮充电压
- vcutof = 14400, -- 电池充电截至电压
- overtemp = 700, -- 高温保护阀值
- lowtemp = 100, -- 低温保护阀值
- unovert = 500, -- 高温解锁阀值
- unlowt = 150, -- 低温解锁阀值
- stamp = "20180301211805" -- 时间戳
- }
- --主板参数配置
- scdParam = {
- cmd = "Set_scdparam",
- ext = {
- lcm = 0, -- 光控类型 0太阳能板光控 1光敏二极管光控
- vsunrise = 1500, --日落电压
- vsunset = 6000, --日出电压
- vcutof = 14400, --最高充电电压
- vfloat = 13600, --恒压触发电压(浮充/恒压)
- vrecharge = 12800, --充电回滞电压
- uvstart = 12000, --开机电压
- uvoff = 12500, --放电迟滞电压
- uvon = 11500, --过放保护电压
- overtemp = 700, --高温保护电压
- lowtemp = 100, --低温保护电压
- unovert = 500, --高温解除电压
- unlowt = 150 --低温解除电压
- }
- }
- --串口接收检验
- result_crc = {
- ds = 1, --设备开启状态 1:开 0:关
- tt=4, -- 光控定时模式下定时时常(1--7)小时
- ws = 0, -- 工作状态 0 待机,1工作,2充电
- lps = 0, --光控状态 1:0
- rps = 0, --雨控保护状态 1:0
- tps = 0, --温度保护状态 1:0
- dps = 0, --倾倒保护状态 1:0
- bt = 0, --主板温度
- kcnt = 0, -- 风机状态
- cv = 0, --充电电压 xx.x
- ci = 0, --充电电流 x.xx
- bv = 12000, --电池电压 xx.x
- wv = 12, --工作电压 xx.x
- wi = 0, --工作电流 x.xx
- ver = "0", --e2prom版本
- cycle_off = 0, --未放电时检测到的频率
- clear_on = 0, --自清虫标志位
- cleartim = 30,--清虫定时时间
- Lamp = 0,--灯管故障检测
- Infrared = 0--红外传感器
- }
- --串口接收缓存
- result = {
- ds = 1, --设备开启状态 1:开 0:关
- tt=4, -- 光控定时模式下定时时常(1--7)小时
- ws = 0, -- 工作状态 0 待机,1工作,2充电
- lps = 0, --光控状态 1:0
- rps = 0, --雨控保护状态 1:0
- tps = 0, --温度保护状态 1:0
- dps = 0, --倾倒保护状态 1:0
- bt = 0, --主板温度
- kcnt = 0, -- 风机状态
- cv = 0, --充电电压 xx.x
- ci = 0, --充电电流 x.xx
- bv = 12000, --电池电压 xx.x
- wv = 12, --工作电压 xx.x
- wi = 0, --工作电流 x.xx
- cycle_off = 0, --未放电时检测到的频率
- clear_on = 0, --自清虫标志位
- ver = "0",
- cleartim = 30,--清虫定时时间
- Lamp = 0,--灯管故障检测
- Infrared = 0--红外传感器
- }
- local function packAndSend(fid, value, multiplier)
- local scaledValue = (multiplier or 1) * value
- local highByte = bit.rshift(scaledValue, 8)
- local lowByte = bit.band(scaledValue, 0xFF)
- local command = string.char(0xDD, fid, highByte, lowByte)
- uart.write(1, command)
- sys.wait(400)
- end
- local function SetStatus()
- packAndSend(fid.vsunrise, scdParam.vsunrise)
- packAndSend(fid.vsunset, scdParam.vsunset)
- packAndSend(fid.vcutof, scdParam.vcutof)
- packAndSend(fid.vfloat, scdParam.vfloat)
- packAndSend(fid.vrecharge, scdParam.vrecharge)
- packAndSend(fid.uvstart, scdParam.uvstart)
- packAndSend(fid.uvoff, scdParam.uvoff)
- packAndSend(fid.uvon, scdParam.uvon)
- packAndSend(fid.overtemp, scdParam.overtemp, 10)
- packAndSend(fid.lowtemp, scdParam.lowtemp, 10)
- packAndSend(fid.unovert, scdParam.unovert, 10)
- packAndSend(fid.unlowt, scdParam.unlowt, 10)
- end
- --- 上传预警信息
- -- t:type
- -- s:status
- function upwarn(t,s)
- log.warn("------------------------t,:",t)
- log.warn("------------------------s,:",s)
- local dat
- -- 设备上报数据表
- local data = {
- type = t,
- status = s,
- }
- message.cmd = "warn"
- message.ext = data
- dat = json.encode(message)
- log.info("upload warn:", dat)
- return dat
- end
- ------------------------------------------------------------------------------------------------------
- --- 打印数据信息
- function PrintData()
- sys.wait(1000)
- if result.ds == 4 then result.ds = 1 end --滤除设备开关机状态标志位异常
- log.warn("++++++++++++++++++++++++++++++++++++++++Parameter display start!!+++++++++++++++++++++++++++++++++++++++++++++++")
- print("Table:", result)
- print( "eeprom state:", result.iSave,
- "\nDevice Status:", result.ds,
- "\nLignt control times:", result.tt,
- "\nWork Status:", result.ws,
- "\nLignt control Status:", result.lps,
- "\nRain control Status:", result.rps,
- "\ntempture control Status:", result.tps,
- "\nDump Protect:", result.dps,
- "\nvoltage Status:", result.vps,
- "\nCharging voltage:", result.cv,
- "\nBattery voltage:", result.bv,
- "\nBoard temperature:", result.bt,
- "\nLight control Type:", paramconf.lcm,
- "\nSunup voltage:", paramconf.vsunrise,
- "\nSunset voltage:", paramconf.vsunset,
- "\nCharging up to voltage:", paramconf.vcutof,
- "\nfloating charge voltage:", paramconf.vfloat,
- "\nonce again startup charging action voltage:", paramconf.vrecharge,
- "\nfirst startup voltage:", paramconf.vstart,
- "\nundervoltage clear voltage:", paramconf.uvoff,
- "\nundervoltage lock voltage:", paramconf.uvon,
- "\nHigh temperature Protect:", paramconf.overtemp,
- "\nLow temperature Protect:", paramconf.lowtemp,
- "\nHigh temperature clear:", paramconf.unovert,
- "\nLow temperature clear:", paramconf.unlowt,
- "红外计数器:", infrared_count,
- "\nVol counts:", result.kcnt,
- "\nboard version:", result.ver)
- log.warn("++++++++++++++++++++++++++++++++++++++++Parameter display end!!+++++++++++++++++++++++++++++++++++++++++++++++")
- end
- --+++++++++++++++++++++++++++++++++++++++++获取主板信息+++++++++++++++++++++++++++++++++++++++++
- -- 获取主板状态 -->STM8从机地址0x51
- local function getStatus()
- local data = string.char(0x55,0x03)
- uart.write(1,data)
- sys.wait(300)
- end
- --------------------------------------------------------------------------------------------------------------
- -- ====================================================上传===================================================
- ------------------------------------------------- 上传数据信息-四情平台 ----------------------------------------
- function upData_120(...)
- local data, c, dat = {}
- getStatus() -- 获取主板状态
- data.imei = misc.getImei() -- 唯一ID
- data.iccid = string.upper(sim.getIccid()) --获取SIM卡的iccid号 ++++ 注意:开机lua脚本运行之后,会发送at命令去查询iccid,所以需要一定时间才能获取到iccid。开机后立即调用此接口,基本上返回nil
- data.csq = net.getRssi() -- 信号强度
- data.dver = VERSION -- 版本号 (main.lua第二行)
- data.proj = PROJECT -- 设备名称 (main.lua第一行)
- data.stm8vs = string.format(result.ver) -- 主板版本号
- -------------------------------------------
- data.ds = result.ds or 1 -- 设备是否开机
- data.ws = result.ws or 1 -- 工作状态 0待机 1工作
- data.cs = result.lps or 0 -- 充电标志位 0 非充电,1 充电
- data.rps = result.rps or 0 -- 雨控
- data.tps = result.tps or 0 -- 温控
- data.dps = result.dps or 0 -- 倾倒
- data.bs = result.vps or 0 -- 正常0 欠压 1 过压 2
- --------------------------------------
- data.tcs = timcontrl.timctrl --时控开关
- data.st = timcontrl.st --时控开始时间
- data.et = timcontrl.et --时控结束时间
- --------------------------------------
- data.lcm = result.lcm or 0 -- 光控类型 0太阳能板光控 1光敏二极管光控
- data.cv = result.cv or 0 -- 充电电压 单位:mV
- data.bv = result.bv or 12000 -- 电池电压 单位:mV
- data.bt = result.bt / 10 -- 主板温度
- data.at = result.bt/10 --环境温度
- data.ah = hum or 30.0 -- 环境湿度
- data.infr_ct = infrared_count -- 红外计数
- if data.infr_ct > 70 then --过滤掉开机之后的红外计数异常
- data.infr_ct = 0
- end
- data.volt_ct = result.kcnt -- 高压计数值
- if data.volt_ct > 10 then --过滤掉开机之后的电击计数异常
- data.volt_ct = 0
- end
- data.wind_drec = 666
- data.wind_sped = 66.6
- -----------------------------------------
-
- rebootcnt = io.readFile(DEV_REBOOT)
- data.bt_ct = rebootcnt -- 设备重启次数
- log.warn("Device Reboot times is:", rebootcnt)
- data.gps = gps_status -- 定位标志位 0 手动定位,1 GPS定位,2 LBS定位
- if gps_status == 0 then
- data.lat = manual_location.lat
- data.lng = manual_location.lng
- elseif gps_status == 1 then
- data.lat = gps_loc_lat
- data.lng = gps_loc_lng
- elseif gps_status == 2 then
- data.lat = lbs_loc_lat
- data.lng = lbs_loc_lng
- end
- log.warn("upload LBS data message:", data.lat, data.lng)
- c = misc.getClock() -- 获取系统时间
- data.stamp = string.format("%04d%02d%02d%02d%02d%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
- message.cmd = "data"
- message.ext = data
- dat = json.encode(message)
- log.info("upload data:", dat)
- --ClearKcnt() --上报数据清零红外
- return dat
- end
- ------------------------- 上传参数配置信息
- function upStatus()
- local status, dat = {}
- getStatus()-- 获取主板状态
- status.imei = misc.getImei() -- 唯一ID
- status.iccid = string.upper(sim.getIccid())--获取SIM卡的iccid号 ++++ 注意:开机lua脚本运行之后,会发送at命令去查询iccid,所以需要一定时间才能获取到iccid。开机后立即调用此接口,基本上返回nil
- status.csq = net.getRssi() -- 信号强度
- status.tt = result.tt or 0 -- 定时时长
- message.cmd = "status"
- message.ext = status
- dat = json.encode(message)
- log.info("upload status:", dat)
- return dat
- end
- -----------------------------------------------------------------------------------------------------------------
- --------------------------------------- 上传数据信息-------大数据平台----------------------------------------------
- function upData()
- local data, c, dat = {}
- getStatus() -- 获取主板状态
-
- data.imei = misc.getImei() -- 唯一ID
- data.iccid = string.format(sim.getIccid()) -- 获取SIM卡的iccid号
- data.csq = string.format(net.getRssi()) -- 信号强度
- data.dver = VERSION -- 版本号 (main.lua第二行)
- data.proj = PROJECT -- 设备名称 (main.lua第一行)
- data.stm8vs = string.format(result.ver) --
- data.dtype = "4" -- 设备类型 -性诱III
- data.btype = "0" -- 0 蓄电池,1锂电池
- data.ds = string.format(result.ds or 1) -- 设备是否开机
- data.ws = string.format(result.ws or 1) -- 工作状态0待机,1工作,2充电
- data.cs = string.format(result.lps or 0) -- 充电标志位 0 非充电,1 充电
- data.rps = string.format(result.rps or 0) -- 雨控
- data.tps = string.format(result.tps or 0) -- 温控
- data.dps = string.format(result.dps or 0) -- 倾倒
- data.bs = string.format(result.vps or 0) -- 正常0 欠压 1 过压 2
- data.lcm = string.format(result.lcm or 0) -- 光控类型 0太阳能板光控 1光敏二极管光控
- data.bt = string.format(result.bt / 10) -- 主板温度
- data.ts = string.format(timcontrl.timctrl) -- 时控开关
- data.st = string.format(timcontrl.st) -- 时控开始时间
- data.et = string.format(timcontrl.et) -- 时控结束时间
- data.cv = string.format((result.cv or 18000) / 1000) -- 充电电压
- data.bv = string.format((result.bv or 12800) / 1000) -- 电池电压
- data.at = string.format(result.bt/10) or "25.0" -- 环境温度
- data.ah = string.format(hum) or "30.0" -- 环境湿度
- data.volt_ct = string.format(result.kcnt) -- 电击次数
- if tonumber(data.volt_ct) > 10 then --过滤掉开机之后的电击计数异常
- data.volt_ct = "0"
- end
- data.infr_ct = infrared_count -- 光电开关计数值
- if tonumber(data.infr_ct) > 70 then -- 过滤掉开机之后的光栅计数异常
- data.infr_ct = 0
- end
- data.wind_drec = "666"
- data.wind_sped = "66.6"
- data.dat_f = string.format(dat_f) -- 数据上传时间间隔
- data.clt_t = string.format(clt_t) -- 清虫时间间隔
- rebootcnt = io.readFile(DEV_REBOOT)
- if rebootcnt == nil or rebootcnt == "" then
- log.info("first startup!!!!!!!!")
- rebootcnt = 0
- rebootcnt = tonumber(rebootcnt)
- end
- log.warn("Device Reboot times is:", rebootcnt)
- data.rcnt = string.format(rebootcnt) -- 重启次数
- data.gps = string.format(gps_status) -- 定位标志位 0 手动定位,1 GPS定位,2 LBS定位
- if gps_status == 0 then
- data.lat = manual_location.lat
- data.lng = manual_location.lng
- elseif gps_status == 1 then
- data.lat = gps_loc_lat
- data.lng = gps_loc_lng
- elseif gps_status == 2 then
- data.lat = lbs_loc_lat
- data.lng = lbs_loc_lng
- end
- c = misc.getClock()
- data.stamp = string.format("%04d%02d%02d%02d%02d%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
- message.cmd = "data"
- message.ext = data
- dat = json.encode(message)
- log.info("upload data:", dat)
- --ClearKcnt(); --清除点击次数
- return dat
- end
- -----------------------------------------------------------------------------------------------------------
- ----------------------------------------- 物联网模块参数配置开始 --------------------------------------------
- ----------------------------------------- 上传主板参数配置信息-----------------------------------------------
- function upParamConf(...)
- local c, dat
- paramconf.imei = misc.getImei() -- 唯一ID
- c = misc.getClock()
- paramconf.stamp = string.format("%04d%02d%02d%02d%02d%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
- message.cmd = "paramconf"
- message.ext = paramconf
- dat = json.encode(message)
- log.info("upload paramconf:", dat)
- return dat
- end
- ----------------------------------------- 上传主服务器配置信息--------------------------------------------------
- function upServerConf(...)
- local dat
- serverconf.imei = misc.getImei()-- 唯一ID
- message.cmd = "serverconf"
- message.ext = serverconf
- dat = json.encode(message)
- log.info("upload serverconf:", dat)
- return dat
- end
- ----------------------------------------- 上传第三方服务器配置信息---------------------------------------------
- function upThirdserverConf(...)
- local dat
- thirdserverconf.imei = misc.getImei()-- 唯一ID
- message.cmd = "thirdserverconf"
- message.ext = thirdserverconf
- dat = json.encode(message)
- log.info("upload thirdserverconf:", dat)
- return dat
- end
- -- 设备给客户端的反馈 -->远程控制设备更新和重启等
- function upres(c_type, c_status)
- local dat
- -- 设备上报数据表
- local data = {
- type = c_type,
- status = c_status
- }
- message.cmd = "warn"
- message.ext = data
- dat = json.encode(message)
- log.info("upload upres:", dat)
- return dat
- end
- ------------------------------------------------- 物联网模块参数配置结束 --------------------------------------------------------
- ------------------------------------------------------------------------------------------------------------------------------
- --++++++++++++++++++++++++++++++++++++++++++++++++ 功能函数集合 开始++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- ---------------------------------------------------主板参数下发配置 开始--------------------------------------------------------
- --- 设置主板开关机
- function setsw(pwb)
- local setsw_cnt = 0
- local set_onoff = string.char(0xAA,0x01,pwb)
- while result.ds ~= pwd do
- setsw_cnt = setsw_cnt + 1
- uart.write(1,set_onoff)
- if setsw_cnt == 2 then break end
- sys.wait(500)
- end
- log.info("设备开关机:", pwb)
- end
- --- 设置主板光控定时时长
- -- @param tt, number类型
- function setTimer(tt)
- if not tt then
- return
- end
- if (tt <= 0 or tt > 8) and tt ==nil and tt == "" then
- log.error("setTimer value error!!!!!!!")
- return
- end
- local send_cnt = 0
- local dat_freq = string.char(0xAA,0x02,tt)
- while tt~=result.tt do
- send_cnt = send_cnt + 1
- uart.write(1,dat_freq)
- if send_cnt == 3 then
- break end
- end
- log.info("定时模式为光控,时长:", tt)
- end
- ---清零红外和高压计数值
- function ClearKcnt()
- local kcnt = 0
- local clear = string.char(0xAA,0x06)
- while true do
- kcnt = kcnt +1
- if result.infr_ct ~=0 or result.volt_ct ~=0 then
- uart.write(1,clear)
- end
- if kcnt == 2 then break end
- sys.wait(500)
- end
- log.info("clear kcnt!!!!")
- end
- ---清虫
- local function Clearworm()
- local setsw_cnt = 0
- local clear_worm = string.char(0xAA,0x05)
- while true do
- setsw_cnt = setsw_cnt + 1
- uart.write(1,clear_worm)
- sys.wait(500)
- if setsw_cnt == 2 then break end --确保置位清虫标志位
- end
- log.info("clear worm!!!!")
- end
- --下发时控设置
- function SetTimControl(crtl,st1,et1)
- if crtl == nil or crtl == "" then return end
- if st1==nil or st1=="" or et1 ==nil or et1 == "" then return end
- st = tonumber(st1)
- et = tonumber(et1)
- if (st < 1 or st > 23) or (et < 1 or et > 23) then
- log.error("value error!!!!!!!!!!")
- return
- end
- if crtl == 1 or crtl == 0 then
- timcontrl.timctrl = crtl
- end
- if (st >= 0 and st <=23) and ( et >= 0 and et <= 23) then
- timcontrl.st = st
- timcontrl.et = et
- end
- log.info("时控参数:", "timctrl:", timcontrl.timctrl, "st:", timcontrl.st, "et:", timcontrl.et)
- local data = json.encode(timcontrl)
- io.writeFile(CONTROL_CONF, data)
- end
- --- 设置清虫时间间隔
- function SetCleartime(clt)
- if not clt then
- return
- end
- if clt < 1 or clt > 120 then
- log.error("clt value error******")
- return
- end
- if clt > 9 and clt < 121 then
- cleartim = clt
- end
- log.info("设置清虫时间间隔为:", cleartim, "分钟")
- io.writeFile(CLEART_CONF, cleartim)
- end
- --- 下发配置数据上传时间间隔:
- function setDattim(dat)
- if not dat then
- return
- end
- if dat < 1 or dat > 120 then
- log.error("Dattim value error!!!!!!!")
- return
- end
- if dat > 9 and dat < 121 then
- dattim = dat
- end
- log.info("设置数据上传时间间隔为:", dattim, "分钟")
- io.writeFile(DATTIM_CONF, dattim)
- end
- -- 一键测试函数
- function Test_key()
- if stm8_update_sw == 1 then return end
- local test = string.char(0XAA,0X0A)
- uart.write(1,test)
- end
- --下发主板升级命令
- function update_stm32()
- local update_cnt = 0
- local up_date_32 = string.char(0xAA,0xA0)
- while true do
- update_cnt = update_cnt + 1
- uart.write(1,up_date_32)
- sys.wait(500)
- if update_cnt == 2 then break end
- end
- log.info("update_stm32 begin!!!!")
- end
- --光控模式切换
- function Light_control_handoff()
- local Light_control1 = string.char(0xAA,0x03,0x01)
- local Light_control2 = string.char(0xAA,0x03,0x00)
- while true do
- if result.lcm == 0 then
- uart.write(1,Light_control1)
- elseif result.lcm == 1 then
- uart.write(1,Light_control2)
- end
- return
- end
- log.info("Light control handoff begin!!!!")
- end
- --下发BootLoader交互命令
- function BootLoader_stm32()
- local boot_count = 0
- local BootLoader_32 = string.char(0x31)
- while true do
- boot_count = boot_count + 1
- uart.write(1,BootLoader_32)
- sys.wait(200)
- if boot_count == 2 then break end
- end
- log.info("BootLoader begin!!!!")
- end
- -----------------------------------------------------------------------------------------------------------------------------
- --================================================ 主板参数下发配置 结束 =======================================================
- -----------------------------------------------反向获取平台温湿度接口传回MQTT 开始----------------------------------------------------
- function Setsensor_value(dat_sensor)
- local cmds,result,err = json.decode(dat_sensor)
- if not result then
- return
- end
- if cmds.ext.new_hum~=nil and cmds.ext.new_hum~="" then
- if tonumber(cmds.ext.new_hum)~= nil and tonumber(cmds.ext.new_hum)>=0 and tonumber(cmds.ext.new_hum)<= 100 then
- hum = tonumber(cmds.ext.new_hum)
- if nvm.get("hum")~= hum then
- nvm.set("hum",hum)
- end
- end
- end
- if cmds.ext.new_tem~=nil and cmds.ext.new_tem~="" then
- if tonumber(cmds.ext.new_tem)~= nil and tonumber(cmds.ext.new_tem) < 100 then
- temp = tonumber(cmds.ext.new_tem)
- if nvm.get("temp")~= temp then
- nvm.set("temp",temp)
- end
- end
- end
- log.warn(">>>>>>>>>sensor data get is:>>>>>>>>>>",hum,temp)
- end
- -----------------------------------------------反向获取平台温湿度接口传回MQTT 结束----------------------------------------------------
- ---------------------------------------------------------------------------------------------------------------------------
- ------------------------------------------------- 物联网模块参数配置开始 ------------------------------------------------------
- ---------------------------------------------------下发用户配置的参数----------------------------------------------------------
- -- --- 下发配置数据上传时间间隔
- -- @param dat, json数据结构
- function Set_dattim(dat)
- if nvm.get("platform")== "120.27.222.26" then
- local cmds, result, err = json.decode(dat)
- if not result then log.info("Set_dattim set the parameter error!") end
- if type(cmds.ext.dat_f) == "number" and cmds.ext.dat_f >= 10 and cmds.ext.dat_f <= 120 then -- number类型 data
- dat_f = cmds.ext.dat_f
- else
- log.error("EEEE:::::::::::::Dattim parameter not number or not range:::::::::::::::EEEE")
- return
- end
- log.warn("Set_dattim set the parameter value is: ", dat_f, "minutes")
- io.writeFile(DATTIM_CONF, dat)
- else
- local cmds, result, err = json.decode(dat)
- if not result then log.info("Set_dattim set the parameter error!") end
- dat_f = tonumber(cmds.ext.data_tim.dat_f)
- log.warn("Set_dattim set the parameter value is: ", dat_f, "minutes")
- paramtable.ext.data_tim.dat_f = dat_f
- local dat = json.encode(paramtable) -- 参数配置存入文件
- io.writeFile(PRARM_CONF,dat)
- end
- end
- -- --- 下发配置清虫时间间隔
- -- @param dat, json数据结构
- function Set_clttim(dat)
- local cmds, result, err = json.decode(dat)
- if not result then log.info("Set_dattim set the parameter error!") end
- clt_t = tonumber(cmds.ext.clt_tim.clt_t)
- log.warn("Set_dattim set the parameter value is: ", clt_t, "minutes")
- paramtable.ext.clt_tim.clt_t = clt_t
- local dat = json.encode(paramtable) -- 参数配置存入文件
- io.writeFile(PRARM_CONF,dat)
- end
- --- 下发设置时控参数
- -- @param dat, json数据结构
- function Set_timcontrol(dat)
- --四情平台设置
- if nvm.get("platform")== "120.27.222.26" then
- local cmds, result, err = json.decode(dat)
- if not result then
- log.error("Set_timcontrol error!!!!!")
- end
- timcontrl = cmds.ext
- log.warn("Set_timcontrol set the parameter value is: ", timcontrl)
- io.writeFile(CONTROL_CONF, dat)
- else
- --大数据平台设置
- local cmds, result, err = json.decode(dat)
- if not result then log.error("Set_timcontrol error!!!!!") end
- 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
- timcontrl.timctrl = tonumber(cmds.ext.work_tim.timctrl)
- end
- 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
- timcontrl.st = tonumber(cmds.ext.work_tim.st)
- end
- 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
- timcontrl.et = tonumber(cmds.ext.work_tim.et)
- end
- log.warn("Set_timcontrol set the parameter value is: ", timcontrl)
- paramtable.ext.work_tim = timcontrl
- local dat = json.encode(paramtable) -- 参数配置存入文件
- io.writeFile(PRARM_CONF,dat)
- end
- end
- --- 下发参数配置信息
- -- @param dat, json数据结构
- function setParamConf(dat)
- local cmds, result, err = json.decode(dat)
- if not result then log.info("setParamConf set the parameter error!") end
- scdParam = cmds.ext
- log.warn("setParamConf set the parameter value is: ", paramconf)
- io.writeFile(DEVICE_CONF, dat)
- SetStatus()
- end
- --- 下发服务器配置信息
- -- @param dat, json数据结构
- function setServerConf(dat)
- local cmds, result, err = json.decode(dat)
- if not result then log.info("setServerConf set the parameter error!") end
- serverconf = cmds.ext
- log.warn("setServerConf set the parameter value is: ", serverconf)
- io.writeFile(SERVER_CONF, dat)
- end
- --- 下发第三方服务器配置信息
- -- @param dat, json数据结构
- function setThirdserverConf(dat)
- local cmds, result, err = json.decode(dat)
- if not result then log.info("setThirdserverConf set the parameter error!") end
- thirdserverconf = cmds.ext
- log.warn("setThirdserverConf set the parameter value is: ", thirdserverconf)
- io.writeFile(THIRD_CONF, dat)
- end
- --- 下发设置定位数据(--百度坐标系--)
- -- @param dat, json数据结构
- function Set_location(dat)
- local cmds, result, err = json.decode(dat)
- if not result then
- log.warn("Set work location failed!")
- end
- manual_location = cmds.ext
- log.warn("set manual_location is:",manual_location.lat,manual_location.lng)
- --paramtable.ext.location = manual_location
- --local dat = json.encode(paramtable) -- 参数配置存入文件
- io.writeFile(GPS_CONF,dat)
- end
- -----------------------------------------------------------------------------------------------------------------------------
- ---------------------------------------------------读取用户配置的参数----------------------------------------------------------
- --- 开机获取用户配置的参数
- function getConfig()
- local param, server,datt, third_ser,loc,param_conf, cmds, result, err
- param = io.readFile(DEVICE_CONF) -- 获取参数配置参数
- cmds, result, err = json.decode(param)
- if result then
- paramconf = cmds.ext
- end
-
- datt = io.readFile(DATTIM_CONF) -- 获取数据上传时间间隔参数
- cmds, result, err = json.decode(datt)
- if result then dat_f = cmds.ext.dat_f end
- server = io.readFile(SERVER_CONF) -- 开机读取主服务器配置
- cmds, result, err = json.decode(server)
- if result then
- serverconf = cmds.ext
- end
-
- third_ser = io.readFile(THIRD_CONF) -- 获取第三方服务器配置参数
- cmds, result, err = json.decode(third_ser)
- if result then
- thirdserverconf = cmds.ext
- end
- loc = io.readFile(GPS_CONF) -- 开机读取手动定位值
- cmds,result,err = json.decode(loc)
- if result then manual_location = cmds.ext end
- ----------------------------设备参数读取失败重置默认参数------------------------------------
- param_conf = io.readFile(PRARM_CONF)
- cmds, result, err = json.decode(param_conf)
- if result then
- dat_f = cmds.ext.data_tim.dat_f -- 获取数据上传时间间隔参数
- clt_t = cmds.ext.clt_tim.clt_t -- 获取清虫间隔参数
- timcontrl = cmds.ext.work_tim -- 获取时控控制参数
- if timcontrl == nil then
- timcontrl.st = 20
- timcontrl.et = 0
- timcontrl.timctrl = 0
- end
- -- manual_location = cmds.ext.location -- 获取手动定位值
- end
- end
- -----------------------------------------------------------------------------------------------------------------------------
- ------------------------------------------------- 物联网模块参数配置结束 ------------------------------------------------------
- -- +++++++++++++++++++++++++++++++++++++++++++++++++ 协程功能进程开始 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- -------------------------------------------------------定时清虫任务------------------------------------------------------------
- --+++++性诱测报III型设备没有定时清虫功能----可以屏蔽该段代码
- sys.taskInit(function()
- while true do
- sys.wait(clt_t * 60 *1000) --30分钟清虫一次
- Clearworm()
- log.warn("Clear worm time is:", clt_t)
- end
- end)
- -----------------------------------------------定时工作任务----------------------------------------------------
- -- 定时模式启动判断
- sys.taskInit(
- function()
- worksta = 0
- local workdone = 0 --(光控定时模式下)工作完成标志位
- local timeover = 0 --定时模式结束时间戳
- sys.wait(30 * 1000)
- --等待开机启动对时
- log.warn("Read timctrl is..................", timcontrl.timctrl)
- local c = misc.getClock()
- while true do
- while true do
- if c.year < 2020 then --如果未对时,关闭时控
- timcontrl.timctrl = 0
- c = misc.getClock()
- end
- if timcontrl.timctrl == 0 then -- 若时控关闭
- log.warn("it's not time control")
- log.warn("开始时间:", timcontrl.st, "结束时间:", timcontrl.et)
- worksta = 0
- workdone = 0
- end
- if timcontrl.timctrl == 1 then -- 若时控开启
- log.warn("it's time control", "start time:", timcontrl.st, "end time:", timcontrl.et)
- local c_sta = misc.getClock()
- c_sta.hour = timcontrl.st
- c_sta.min = 0
- c_sta.sec = 0
- if timcontrl.st < timcontrl.et then -- 如果开始和结束时间是同一天
- log.warn("the same day !!!!")
- local c_end = misc.getClock() -- **获取当前时间**
- c_end.hour = timcontrl.et
- c_end.min = 0
- c_end.sec = 0
- -- 如果当前时间大于开始时间且小于结束时间,且没有开始工作
- if os.difftime(os.time(), os.time(c_sta)) > 0 and os.difftime(os.time(), os.time(c_end)) < 0 and workdone == 0 then
- log.warn("模式1当前时间大于开始时间,且没有开始工作,当前时间小于结束时间的情况:计算结束时间戳")
- timeover = os.time(c_end)
- timeover = tonumber(timeover)
- worksta = 1
- break
- elseif os.difftime(os.time(), os.time(c_sta)) < 0 then
- log.warn("模式1当前时间小于开始时间!!!")
- worksta = 0
- elseif os.difftime(os.time(), os.time(c_end)) > 0 then
- log.warn("模式1当前时间大于结束时间!!!")
- worksta = 0
- end
- -- 如果工作完成:
- if workdone == 1 then
- workdone = 0
- end
- elseif timcontrl.st > timcontrl.et then -- 如果结束时间是第二天
- log.warn("not the same day !!!!")
- local n = misc.getClock() -- **获取当前时间**
- -- 如果当前时间大于开始时间,且没有开始工作 ,注意时间戳日期加1
- if os.difftime(os.time(), os.time(c_sta)) > 0 and workdone == 0 and n.hour > timcontrl.et then
- log.warn("模式2当前时间大于开始时间,且没有开始工作,当前时间位于0点之前,结束时间戳加1天,计算结束时间戳")
- local c_end = misc.getClock()
- c_end.hour = timcontrl.et
- c_end.min = 0
- c_end.sec = 0
- timeover = os.time(c_end) + 3600 * 24
- timeover = tonumber(timeover)
- worksta = 1
- break
- elseif os.difftime(os.time(), os.time(c_sta)) > 0 and workdone == 0 and n.hour < timcontrl.et then
- log.warn("模式2当前时间大于开始时间,但是小于结束时间,当前时间位于0点之后,所以是重启引起的,时间戳不动,计算结束时间戳")
- local c_end = misc.getClock()
- c_end.hour = timcontrl.et
- c_end.min = 0
- c_end.sec = 0
- timeover = os.time(c_end)
- worksta = 1
- break
- elseif os.difftime(os.time(), os.time(c_sta)) < 0 then
- log.warn("模式2当前时间小于开始时间!!!")
- worksta = 0
- end
- -- 如果工作完成:
- if workdone == 1 then
- workdone = 0
- end
- end
- end
- sys.wait(1000)
- end
- -- 等待定时任务完成
- if timeover ~= nil or timeover ~= 0 then
- while (timeover > os.time()) do
- sys.wait(1000)
- log.warn("Working.....:", "over", timeover, "now:", os.time())
- end
- end
- log.info(" The workTask time is end!")
- ----------------------标志工作定时结束!!!++++
- worksta = 0
- workdone = 1
- ----------------------标志工作完成!!!++++
- sys.wait(1000)
- end
- end
- )
- -- 时控判断是否工作-------------------------------------------------
- sys.taskInit(
- function()
- sys.wait(20 * 1000)
- while true do
- if timcontrl.timctrl == 1 then --时控定时模式
- log.warn("Start Timng Mode....")
- if worksta == 1 then
- if result.ds == 0 then -- 如果设备关机
- setsw(1) --开机
- end
- else
- if result.ds == 1 then -- 如果设备开机
- setsw(0)
- end
- end
- end
- if timcontrl.timctrl == 0 then --光控
- log.warn("Light control mode...")
- end
- if timcontrl.timctrl ~= timcontrl.timctrl then --如果时控状态改变清除当前计数值
- infrared_count = 0
- end
- sys.wait(1000)
- end
- end
- )
- --时控工作修改光控工作状态消除时控工作状态下不能达到工作时长
- sys.taskInit(
- function ()
- local cnf, result, err = json.decode(dat)
- sys.wait(1000)
- while true do
- if timcontrl.timctrl == 1 then
- tt = 0
- setTimer(0)
- end
- sys.wait(1000)
- end
- end
- )
- -----------------------------------------------雨控即时上报----------------------------------------------------
- --雨控即时上报
- sys.taskInit(
- function()
- sys.wait(1000)
- while true do
- if rps_x == 1 then
- updata_freq = 0
- rps_x = 0
- rps_y = 1
- end
- sys.wait(1000)
- end
- end
- )
- ------------------------------------------------------------协程通讯进程开始----------------------------------------------------------
- -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MQTT1 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- sys.taskInit(function()
- getConfig() -- 开机获取用户配置的参数
- nvm.init("config.lua")
- sys.wait(5000)
- log.info("MQTT1 Task is start!")
- -- 是否获取分配到的ip
- while not socket.isReady() do
- log.info("socket is not ready,err_num:", err_num)
- err_num = err_num + 1
- sys.wait(1000)
- if err_num >= 600 then
- rebootinfo = 2 -- ***SOCKET断开上报***(注意只针对120.27.222.26服务器)
- io.writeFile(DEVICE_ERR, rebootinfo)
- sys.restart("socket connect overtime!")
- end
- end
- serverconf.ip = nvm.get("platform")
- if serverconf.ip == "8.136.98.49" then
- serverconf.port = 61883
- sub = "/yfkj/xycb/s2c/" -- 服务器到客户端
- pub = "/yfkj/xycb/c2s/" -- 客户端到服务器
- lastwill = "/yfkj/xycb/offline/" -- 离线消息主题(部分)-->设备异常中断时用于mqtt服务器发布该设备的遗愿消息,个人网站客户端需订阅
- elseif serverconf.ip == "120.27.222.26" then
- serverconf.port = 1883
- sub1 = "yfkj/xycb/s2c/" -- 服务器到客户端
- pub1 = "yfkj/xycb/c2s/" -- 客户端到服务器
- lastwill1 = "yfkj/xycb/offline/" -- 离线消息主题(部分)-->设备异常中断时用于mqtt服务器发布该设备的遗愿消息,个人网站客户端需订阅
- end
- if nvm.get("lat_lbs") ~= "" and nvm.get("lat_lbs") ~= nil then
- lbs_loc_lat = nvm.get("lat_lbs")
- lbs_loc_lng = nvm.get("lng_lbs")
- gps_status = 2
- end
- if nvm.get("lat_gps") ~= "" and nvm.get("lat_gps") ~= nil then
- gps_loc_lat = nvm.get("lat_gps")
- gps_loc_lng = nvm.get("lng_gps")
- gps_status = 1
- end
- if nvm.get("hum") ~= "" and nvm.get("hum") ~= nil then
- hum = nvm.get("hum")
- end
- if nvm.get("temp") ~= "" and nvm.get("temp") ~= nil then
- temp = nvm.get("temp")
- end
- -- 离线消息
- willmsg.ext.imei = misc.getImei()
- if serverconf.ip == "8.136.98.49" then
- serverconf.lastwill = "/yfkj/xycb/offline/"
- serverconf.pub = "/yfkj/xycb/c2s/"
- serverconf.sub = "/yfkj/xycb/s2c/"
- elseif serverconf.ip == "120.27.222.26" then
- serverconf.lastwill = "yfkj/xycb/offline/"
- serverconf.pub = "yfkj/xycb/c2s/"
- serverconf.sub = "yfkj/xycb/s2c/"
- end
- local will = {qos = 1, retain = 0, topic = string.format(serverconf.lastwill .. misc.getImei()), payload = json.encode(willmsg)} -- 创建mqtt客户端--默认配置了MQTT遗愿消息
- local mqttc = mqtt.client(misc.getImei(), serverconf.keepalive, serverconf.uid, serverconf.pwd, 1,will)
- local pub = string.format(serverconf.pub .. misc.getImei())
- local sub = string.format(serverconf.sub .. misc.getImei())
- local mqtt_sta = true
- while true do
- -- 连接mqtt服务器
- mqtt_sta = mqttc:connect(serverconf.ip, serverconf.port)
- log.info('mqtt connect status::', mqtt_sta)
- if mqtt_sta == false then
- log.info("mqtt1 connect fail,try to reconnect!", tcp_cont)
- tcp_cont = tcp_cont + 1
- if tcp_cont >= 600 then
- rebootinfo = 3 -- ***MQTT断开上报***
- io.writeFile(DEVICE_ERR, rebootinfo)
- sys.restart("mqtt1 reconnect overtime:60!!!")
- end
- end
- -- 订阅主题
- if mqttc:subscribe(sub, serverconf.qos) then
- local reason = rtos.poweron_reason()
- log.info("reason:", reason)
- 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)
- if serverconf.ip == "8.136.98.49" then
- if not mqttc:publish(pub, upData(), serverconf.qos) then break end
- elseif serverconf.ip == "120.27.222.26" then
- if not mqttc:publish(pub, upStatus(), serverconf.qos) then break end
- if not mqttc:publish(pub, upData_120(), serverconf.qos) then break end
- end
- log.info("MQTT1 upload is done!")
- while mqtt_sta==true do
- mqtt_status = "true"
- --local r, packet = mqttc:receive(dattim * 60 * 1000) -- 处理服务器下发指令
- local r, packet, param = mqttc:receive(timeout * 1000 * 60, "NET_SENT_RDY_")
- if r then -- 这里是有数据下发的处理
- datalink = 2
- local cnf, result, err = json.decode(packet.payload)
- if result then
- log.info("MQTT1 recv json is::::::::::::::::::::::::::::::::::::::::::::::", packet.payload)
- if serverconf.ip == "8.136.98.49" then
- -----------------------------------设备参数读取--------------------------------
- if cnf.cmd == "read" then
- if cnf.ext == 'data' then --参数读取
- updata_freq = 0
- elseif cnf.ext == 'paramconf' then --获取参数配置
- if not mqttc:publish(pub, upParamConf(), serverconf.qos) then break end
- elseif cnf.ext == 'serverconf' then --获取主服务器参数配置
- if not mqttc:publish(pub, upServerConf(), serverconf.qos) then break end
- updata_freq = 0
- elseif cnf.ext == 'thirdserver_conf' then --获取第三方服务器配置
- if not mqttc:publish(pub, upThirdserverConf(), serverconf.qos) then break end
- updata_freq = 0
- end
- --------------------------------平台设备控制参数下发-----------------------------------
- elseif cnf.cmd == 'paramconf' then
- if cnf.ext.data_tim ~= nil then -- 大数据平台配置数据上传时间间隔
- Set_dattim(packet.payload)
- sys.wait(300)
- end
- if cnf.ext.clt_tim ~= nil then -- 大数据平台配置清虫时间间隔
- Set_clttim(packet.payload)
- sys.wait(300)
- end
- if cnf.ext.work_tim ~= nil then -- 大数据平台配置定时控制参数
- Set_timcontrol(packet.payload)
- sys.wait(300)
- end
- if cnf.ext.power ~= nil then -- 大数据平台开关机控制
- setsw(tonumber(cnf.ext.power.ds))
- sys.wait(300)
- end
- if cnf.ext.location ~= nil then -- 大数据平台下发手动定位
- Set_location(packet.payload)
- sys.wait(300)
- end
- 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
- ---------------------------------------------------------------------------------------------------------
- elseif cnf.cmd == "clearworm" then -- 大数据平台清虫
- if not mqttc:publish(pub, upres("xy-clrworm", "Remote clearworm action will run!!"), serverconf.qos) then break end
- sys.publish("clearworm")
- Clearworm()
- updata_freq = 0
- sys.wait(300)
- elseif cnf.cmd == "reboot" then -- 大数据平台重启
- if not mqttc:publish(pub, upres("air820-reboot", "System will restart!!"), serverconf.qos) then break end
- sys.restart("Device remote restart")
- elseif cnf.cmd == "update" then -- 大数据平台物联网模块升级
- if not mqttc:publish(pub, upres("air820-updata", "System will update!!"), serverconf.qos) then break end
- Update.run()
- elseif cnf.cmd == "update_stm32" then -- 大数据平台主板stm32升级
- if not mqttc:publish(pub, upres("update_stm32", "stm32 update will start!!"), serverconf.qos) then break end
- stm8_update_sw = 1
- update_stm32() --STM32远程升级
- ----------------------------参数配置下发------------------------------
- elseif cnf.cmd == 'param_conf' then -- 大数据平台设备参数配置下发
- setParamConf(packet.payload)
- updata_freq = 0
- elseif cnf.cmd == 'server_conf' then -- 大数据平台服务器配置下发
- setServerConf(packet.payload)
- updata_freq = 0
- sys.restart("server_conf done then restart!!!")
- elseif cnf.cmd == 'thirdserver_conf' then -- 大数据平台第三方服务器配置下发
- setThirdserverConf(packet.payload)
- sys.restart("thirdserver_conf done then restart!!!")
- elseif result and cnf.cmd=="platform" then----平台切换参数下发
- if cnf.ext.type == "120.27.222.26" then
- nvm.set("platform","120.27.222.26")
- sys.restart("120.27.222.26")
- elseif cnf.ext.type == "8.136.98.49" then
- nvm.set("platform","8.136.98.49")
- sys.restart("8.136.98.49")
- end
- local c = misc.getClock()
- local date = string.format("%00004d-%02d-%02d %02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
- if not mqttc:publish(pub,upwarn("平台操作","切换平台至:"..cnf.ext.type..",操作时间:"..date), serverconf.qos) then
- break
- end
- end
- elseif serverconf.ip == "120.27.222.26" then
- if cnf.cmd == "read" then
- if cnf.ext == 'status' then --状态读取
- updata_freq = 0
- elseif cnf.ext == 'data' then --参数读取
- updata_freq = 0
- elseif cnf.ext == 'paramconf' then --获取参数配置
- if not mqttc:publish(pub, upParamConf(), serverconf.qos) then break end
- elseif cnf.ext == 'serverconf' then --获取主服务器配置
- if not mqttc:publish(pub, upServerConf(), serverconf.qos) then break end
- elseif cnf.ext == 'thirdserver_conf' then --第三方服务器配置读取
- if not mqttc:publish(pub, upThirdserverConf(), serverconf.qos) then break end
- updata_freq = 0
- end
- elseif cnf.cmd == 'set' then
- if cnf.ext.type == "data_tim" then -- 四情平台配置数据上传时间间隔
- Set_dattim(packet.payload)
- updata_freq = 0
- sys.wait(300)
- elseif cnf.ext.type == "work_tim" then -- 四情平台配置定时控制参数
- Set_timcontrol(packet.payload)
- updata_freq = 0
- sys.wait(300)
- else
- log.error("EEEE:::::::::::::not set match:::::::::::::::EEEE")
- end
- elseif cnf.cmd == "ctrl" then
- if cnf.ext.type == "power" then -- 四情平台开关机
- if not mqttc:publish(pub, upres("Remote startup&shutdown action will run!", "ok"), serverconf.qos) then break end
- setsw(cnf.ext.ds)
- updata_freq = 0
- sys.wait(300)
- elseif cnf.ext == "clearworm" then -- 四情平台清虫
- if not mqttc:publish(pub, upres("Remote clearworm action will run!", "ok"), serverconf.qos) then break end
- sys.publish("clearworm")
- Clearworm()
- updata_freq = 0
- sys.wait(300)
- end
- elseif cnf.cmd == "timer" then --下发设置光控定时时长参数
- setTimer(cnf.ext.tt)
- sys.wait(300)
- if not mqttc:publish(pub, upData_120(), serverconf.qos) then break end
- elseif cnf.cmd == "location" then -- 四情平台下发手动定位
- Set_location(packet.payload)
- if not mqttc:publish(pub, upres("Set the location", "OK"), serverconf.qos) then break end
- elseif cnf.cmd == "reboot" then -- 四情平台重启
- log.warn("Device remote reboot!!!!!")
- if not mqttc:publish(pub, upres("air820-reboot", "system will restart!!", "ok"), serverconf.qos) then break end
- sys.restart("Device remote restart")
- elseif cnf.cmd == "update" then -- 四情平台物联网模块升级
- log.warn("Device remote update!!!!!")
- if not mqttc:publish(pub, upres("air820-updata", "system update will start!!", "ok"), serverconf.qos) then break end
- Update.run()
- elseif cnf.cmd == "update_stm32" then -- 四情平台平台主板stm32升级
- if not mqttc:publish(pub, upres("update_stm32", "stm32 update will start!!"), serverconf.qos) then break end
- stm8_update_sw = 1
- update_stm32() --STM32远程升级
- -------------------------------
- elseif cnf.cmd == 'paramconf' then --四情平台下发参数配置
- setParamConf(packet.payload)
- updata_freq = 0
- sys.restart("paramconf done then restart!!!")
- elseif cnf.cmd == 'server_conf' then -- 四情平台服务器配置下发
- setServerConf(packet.payload)
- updata_freq = 0
- sys.restart("server_conf done then restart!!!")
- elseif cnf.cmd == 'thirdserver_conf' then --四情平台下第三方发服务器参数配置
- setThirdserverConf(packet.payload)
- sys.restart("thirdserver_conf done then restart!!!")
- elseif result and cnf.cmd=="platform" then --四情平台平台切换参数下发
- if cnf.ext.type == "120.27.222.26" then
- nvm.set("platform","120.27.222.26")
- sys.restart("120.27.222.26")
- elseif cnf.ext.type == "8.136.98.49" then
- nvm.set("platform","8.136.98.49")
- sys.restart("8.136.98.49")
- end
- local c = misc.getClock()
- local date = string.format("%00004d-%02d-%02d %02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
- if not mqttc:publish(pub,upwarn("平台操作","切换平台至:"..cnf.ext.type..",操作时间:"..date), serverconf.qos) then
- break
- end
- end
- elseif result and cnf.cmd=="sensor" then --温湿度
- Setsensor_value(packet.payload)
- if nvm.get("json_w_stm8boot") ~= "" and nvm.get("json_w_stm8boot") ~= nil then
- if mqttc:publish(pub, upwarn(nvm.get("json_w_stm8boot"),"主板重启"), serverconf.qos) then
- nvm.set("json_w_stm8boot","")
- end
- end
- if nvm.get("json_w_stm32_app") ~= "" and nvm.get("json_w_stm32_app") ~= nil then
- if mqttc:publish(pub, upwarn(nvm.get("json_w_stm32_app"),"输出故障"), serverconf.qos) then
- nvm.set("json_w_stm32_app","")
- end
- end
- end
- else
- log.error("EEEE:::::::::::::not json download::::::::::::::EEEE")
- end
- end
- if packet == "NET_SENT_RDY_" then
- timeout = 60
- log.info("updata is", param)
- if not mqttc:publish(pub, param, serverconf.qos) then
- break
- end
- end
- end
- end
- mqttc:disconnect()
- log.info("=============mqtt1 disconnect=============")
- sys.wait(1000)
- datalink = 0 -- 服务器断开链接数据指示灯慢闪
- end
- end)
- -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MQTT2 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- sys.taskInit(function()
- sys.wait(10*1000)
- getConfig() -- 开机获取用户配置的参数
- log.warn('MQTT2 Task is running!!!!!!!!!!')
-
- if thirdserverconf.ip == "" or thirdserverconf.ip == nil then
- log.info("MQTT2 Ip Not Set!")
- return
- end
- -- 是否获取分配到的ip
- while not socket.isReady() do
- log.info("socket2 is not ready,err2_num:", err2_num)
- err2_num = err2_num + 1
- sys.wait(1000)
- if err2_num >= 600 then
- log.warn("socket2 connect overtime!") --软件重启(重启原因:socket connect overtime!)注意:重启后的trace中会打印出此重启原因
- end
- end
- -- 离线消息
- willmsg.ext.imei = misc.getImei()
- will2 = {qos = 1, retain = 0, topic = string.format(thirdserverconf.lastwill .. misc.getImei()), payload = json.encode(willmsg)}-- 创建mqtt客户端--默认配置了MQTT遗愿消息
- local mqttc2 = mqtt.client(misc.getImei(), thirdserverconf.keepalive, thirdserverconf.uid, thirdserverconf.pwd, 1, will2)
- -- 拼接主题
- local pub2 = string.format(thirdserverconf.pub .. misc.getImei())
- local sub2 = string.format(thirdserverconf.sub .. misc.getImei())
- local mqtt2_sta = true
- while true do
- mqtt2_sta = mqttc2:connect(thirdserverconf.ip, thirdserverconf.port)
- log.info('mqtt2 connect status::', mqtt2_sta)
- if mqtt2_sta == false then
- log.info("mqtt2 connect fail,try to reconnect!", tcp2_cont)
- tcp2_cont = tcp2_cont + 1
- if tcp2_cont >= 50 then
- tcp2_cont = 0
- sys.restart("mqtt2 reconnect overtime:30!!!")
- end
- end
- -- 订阅主题
- if mqttc2:subscribe(sub2, thirdserverconf.qos) then
- log.warn("------------------------------------------*-*-*-*---*-------------------------------------------")
- if not mqttc2:publish(pub, upData(), thirdserverconf.qos) then break end
- log.info("'mqtt2 First upload data is done!!!!!'")
- log.warn("*********************************************-*-*-*---*-********************************************")
- sys.wait(2000)
- while mqtt2_sta==true do
- local r, packet, param = mqttc2:receive(timeout * 1000 * 60, "NET_SENT_RDY_")
- if r then -- 这里是有数据下发的处理
- local cnf, result, err = json.decode(packet.payload) -- json解析
- if result then
- log.info("::::::::::::::::::::::::::::::::::::::::MQTT2 recv json is::::::::::::::::::::::::::::::::::::::::::", packet.payload)
- if cnf.cmd == "read" then
- if cnf.ext == "data" then
- updata_freq = 0
- end
- -- ++++++下发设置/远程设置++++++
- elseif cnf.cmd == "paramconf" then -- 参数配置
- if cnf.ext.data_tim ~= nil then -- 平台配置数据上传时间间隔
- if not mqttc:publish(pub, upres("xy-dat_f", "Remote set data_tim!!"), serverconf.qos) then break end
- Set_dattim(packet.payload)
- sys.wait(300)
- end
- if cnf.ext.clt_tim ~= nil then -- 平台配置清虫时间间隔
- if not mqttc:publish(pub, upres("xy-clt_f", "Remote set clt_tim!!"), serverconf.qos) then break end
- Set_clttim(packet.payload)
- sys.wait(300)
- end
- if cnf.ext.work_tim ~= nil then -- 平台配置定时控制参数
- if not mqttc:publish(pub, upres("xy-timcotrl", "Remote set work_tim!!"), serverconf.qos) then break end
- Set_timcontrol(packet.payload)
- sys.wait(300)
- end
- if cnf.ext.power ~= nil then -- 平台开关机控制
- if not mqttc:publish(pub, upres("xy-switch", "Remote startup&shutdown action will run!!"), serverconf.qos) then break end
- setsw(tonumber(cnf.ext.power.ds))
- sys.wait(300)
- end
- if cnf.ext.location ~= nil then -- 平台下发手动定位
- Set_location(packet.payload)
- if not mqttc:publish(pub, upres("xy-manual_location", "Remote set manual_location!!"), serverconf.qos) then break end
- end
- if not mqttc:publish(pub, upData(), serverconf.qos) then break end
- updata_freq = 0
- elseif cnf.cmd == "clearworm" then -- 平台手动下发清虫
- if not mqttc:publish(pub, upres("xy-clrworm", "Remote clearworm action will run!!"), serverconf.qos) then break end
- Clearworm()
- updata_freq = 0
- elseif cnf.cmd == "reboot" then -- 物联网模块重启
- if not mqttc:publish(pub, upres("air820-reboot", "System will restart!!"), serverconf.qos) then break end
- sys.restart("Device remote restart")
- elseif cnf.cmd == "update" then -- 物联网模块升级
- if not mqttc:publish(pub, upres("air820-updata", "System will update!!"), serverconf.qos) then break end
- Update.run()
- elseif cnf.cmd == "update_stm32" then -- 四情平台平台主板stm32升级
- if not mqttc:publish(pub, upres("update_stm32", "stm32 update will start!!"), serverconf.qos) then break end
- stm8_update_sw = 1
- update_stm32() --STM32远程升级
- end
- end
- end
- if packet == "NET_SENT_RDY_" then
- timeout = 60
- log.info("updata is", param)
- if not mqttc2:publish(pub2, param, thirdserverconf.qos) then break end
- end
- end
- end
- mqttc2:disconnect()
- sys.wait(1000)
- end
- sys.restart("mqtt2 first publish message is error cause mqtt task is break!")
- end)
- -- +++++++++++++++++++++++++++++++++++++++++++++ *网络状况监控任务* ++++++++++++++++++++++++++++++++++++++++++++++++++
- -- 网络状况监控任务:
- sys.taskInit(function()
- local err = 0
- -- 等待设备联网:
- log.warn("***************socket monitor task is running!***************")
- while true do
- while not socket.isReady() do
- log.warn("socket is not Ready,", "err:", err)
- err = err + 1
- if err >= 600 then
- sys.restart("socket connect err overtime:30!!!")
- end
- sys.wait(1000)
- end
- sys.wait(1000)
- end
- end)
- --+++++++++++++++++++++++++++++++++++++++++++++++ * LBS+GPS定位任务 开始* ++++++++++++++++++++++++++++++++++++++++++++++++++
- --[[
- 功能 :获取基站对应的经纬度后的回调函数
- 参数 :
- result:number类型,0表示成功,1表示网络环境尚未就绪,2表示连接服务器失败,3表示发送数据失败,4表示接收服务器应答超时,5表示服务器返回查询失败;为0时,后面的3个参数才有意义
- lat:string类型,纬度,整数部分3位,小数部分7位,例如031.2425864
- lng:string类型,经度,整数部分3位,小数部分7位,例如121.4736522
- 返回值:无
- ]]
- -- LBS定位回调函数 GCJ02(火星坐标)-->需转换BD-09(百度坐标)
- function getLocCb(result, lat, lng) --注意:进入此函数时LBS已经定位成功
- if result == 0 then --如果result=0,表示定位成功
- log.info("get LBS location success!!!!!!!!!!!!!!!!!!!!!!!!!!!")
- log.warn("testLbsLoc.getLocCb*****************", result, lat, lng)
- lbs_loc_lat = lat
- lbs_loc_lng = lng
- log.warn("get LBS location message >>>>>>>>>>>>>>>>>>>>>>>>>>", lbs_loc_lat, lbs_loc_lng)
- gps_status = 2
- nvm.set("lat_lbs",lat)
- nvm.set("lng_lbs",lng)
- else
- log.info("get LBS location failed!!!!!!!!!!!!!!!!!!!!!!!!!!!")
- end
- end
- -- GPS日志信息输出函数 WGS-84(国际标准GPS原始坐标)-->需转换BD-09(百度坐标)
- local function printGps()
- if gps.isOpen() then
- local tLocation = gps.getLocation()
- local speed = gps.getSpeed()
- log.info("testGps.printGps",
- gps.isOpen(),
- gps.isFix(),
- tLocation.lngType,
- tLocation.lng,
- tLocation.latType,
- tLocation.lat, -- 度格式的经纬度信息
- gps.getAltitude(), -- 海拔
- speed, -- 速度
- gps.getCourse(), -- 方向角
- gps.getViewedSateCnt(), -- 可见卫星的个数
- gps.getUsedSateCnt()) -- 定位使用的卫星个数
-
- end
- end
- ---------------------- GPS 模式切换 ------------------------------
- local function test1Cb(tag)
- log.info("testGps.test1Cb",tag)
- printGps()
- end
- local function test2Cb(tag)
- log.info("testGps.test2Cb",tag)
- printGps()
- end
- local function test3Cb(tag)
- log.info("testGps.test3Cb",tag)
- printGps()
- end
- --测试代码开关,取值1,2
- local testIdx = 1
- local function test(idx)
- --第1种测试代码
- if idx==1 then
- --执行完下面三行代码后,GPS就会一直开启,永远不会关闭
- --因为gps.open(gps.DEFAULT,{tag="TEST1",cb=test1Cb}),这个开启,没有调用gps.close关闭
- gps.open(gps.DEFAULT,{tag="TEST1",cb=test1Cb})
- --10秒内,如果gps定位成功,会立即调用test2Cb,然后自动关闭这个“GPS应用”
- --10秒时间到,没有定位成功,会立即调用test2Cb,然后自动关闭这个“GPS应用”
- gps.open(gps.TIMERORSUC,{tag="TEST2",val=10,cb=test2Cb})
- --300秒时间到,会立即调用test3Cb,然后自动关闭这个“GPS应用”
- gps.open(gps.TIMER,{tag="TEST3",val=300,cb=test3Cb})
- --第2种测试代码
- elseif idx==2 then
- --执行完下面三行代码打开GPS后,5分钟之后GPS会关闭
- gps.open(gps.DEFAULT,{tag="TEST1",cb=test1Cb})
- sys.timerStart(gps.close,300000,gps.DEFAULT,{tag="TEST1"})
- gps.open(gps.TIMERORSUC,{tag="TEST2",val=10,cb=test2Cb})
- gps.open(gps.TIMER,{tag="TEST3",val=60,cb=test3Cb})
- end
- end
- --------------------------------------------------------------------
- local function nmeaCb(nmeaItem)
- log.info("testGps.nmeaCb",nmeaItem)
- end
- -- GPS+LBS定位任务
- sys.subscribe("AUTOGPS_READY",function(gpsLib,agpsLib,kind,baudrate)
- gps=gpsLib
- agps=agpsLib
- log.info("testGps.AUTOGPS_READY",baudrate,kind)
- gps.setUart(uartId,baudrate,8,uart.PAR_NONE,uart.STOP_1) -- 设置串口通信参数,波特率为自适应
- gps.setNmeaMode(2,nmeaCb) -- gps.lua和外部程序都处理NEMA数据
- test(testIdx)
- sys.timerLoopStart(printGps,2000)
- end)
- sys.taskInit(
- function()
- while true do
- gps_status = 0
- locat_cnt = 0
- sys.wait(8 * 1000) -- 等待socket连接完毕
- while true do
- if tonumber(manual_location.type) == 0 then -- 判断是否手动定位 若手动定位直接关闭GPS
- if socket.isReady() and gps_status ~=1 and gps_status ~= 2 then
- log.warn("================ LBS Location successful ===============")
- lbsLoc.request(getLocCb)
- sys.wait(1000)
- end
- if gps.isFix() == false then
- log.info("================ GPS Location failed ===============")
- printGps()
- elseif gps.isFix() == true then
- gps_cont = gps_cont + 1
- local location = gps.getLocation()
- gps_loc_lat = location.lat
- gps_loc_lng = location.lng
- printGps()
- if gps_cont >= 3 then -- 获取3次gps定位数据的最后一次
- nvm.set("lat_gps",gps_loc_lat)
- nvm.set("lng_gps",gps_loc_lng)
- gps.closeAll()
- end
- gps_status = 1
- log.info("================ GPS Location successful ===============")
- end
- sys.wait(1000)
- log.info("GPS open status is:", gps.isOpen())
- log.info("GPS location status is:", gps.isFix())
- else
- gps_status = 0
- gps.closeAll()
- sys.wait(2000)
- end
- sys.wait(1000)
- locat_cnt = locat_cnt + 1
- if locat_cnt >= 1800 then -- 每隔30分钟判断一下定位,若失败,则break
- if (gps_loc_lng == "0" and gps_loc_lat == "0") and (lbs_loc_lat == "0" and lbs_loc_lng == "0") then
- break
- else
- locat_cnt = 0
- log.warn("location normal !!!")
- end
- end
- end
- end
- end
- )
- ------------------------------------------------------ * LBS+GPS定位任务 结束* ------------------------------------------------
- --++++++++++++++++++++++++++++++++++++++++++++++++++++ * SIM卡自动切换线程 * +++++++++++++++++++++++++++++++++++++++++++++++++++
- local function cbFnc(result)
- if result then
- log.info("SIM switch successful")
- else
- log.info("SIM switch failed")
- end
- end
- -- 说明:目前版本不支持SIM自动切换功能需手动切换SIM卡
- -- 注意:本命令关机保存,但是需重启生效
- -- 初次刷入程序默认SIM ID = 0
- sys.taskInit(
- function()
- sys.wait(5 * 1000) -- 注意:开机lua脚本运行之后,会发送at命令去查询id,所以需要一定时间才能获取到id。开机后立即调用此接口,基本上返回nil
- local ID1 = sim.getId()
- local ID2 = ID1
- log.info("Now SIM is:::", ID1)
- if ID1 == 0 then
- ID2 = 1
- elseif ID1 == 1 then
- ID2 = 0
- end
- sys.wait(5 * 1000)
- while true do
- if sim.getStatus() == false or sim.getStatus() == nil then -- 切换SIM卡
- sim.setId(ID2,cbFnc)
- sys.wait(1000)
- sim.setId(ID2,cbFnc)
- sys.restart("switch sim card")
- end
- local id = sim.getId() -- 获取目前设置的双卡单待id
- log.info("Now system SIM card is:::", id)
- sys.wait(5 * 1000)
- end
- end
- )
- --+++++++++++++++++++++++++++++++++++++++++++++++ * MQTT守护线程 * ++++++++++++++++++++++++++++++++++++++++++++++++
- -- Mqtt异常监测
- sys.taskInit(function()
- sys.wait(10*1000)
- local dev_dta_on = 1
- while true do
- if mqtt_status == "" then
- mqtt_status_num = mqtt_status_num + 1
- elseif mqtt_status == "true" then
- mqtt_status = ""
- mqtt_status_num = 0
- sys.wait(1000)
- end
- if mqtt_status_num > timeout * 61 then
- sys.restart("MQTT ERROR!!!")
- end
- log.warn("====================mqtt_check=================:",mqtt_status_num,mqtt_status,timeout)
- sys.wait(1000)
- end
- end)
- ---------------------------------------------------------------
- --定时上报任务
- sys.taskInit(
- function()
- sys.wait(15*1000)
- if dat_f ==0 or dat_f == nil or dat_f =="" then
- dat_f = 30
- end
- while true do
- updata_freq = dat_f * 60
- while updata_freq ~= 0 do
- updata_freq = updata_freq - 1
- sys.wait(1000)
- log.info("++++++++ 1 !!!!!!!!")
- end
- if serverconf.ip == "8.136.98.49" then
- sys.publish("NET_SENT_RDY_", upData())
- infrared_count = 0
- ClearKcnt() -- 上报数据清除电机次数
- log.info("++++++++ 2 !!!!!!!!")
- elseif serverconf.ip == "120.27.222.26" then
- sys.publish("NET_SENT_RDY_", upData_120())
- sys.publish("NET_SENT_RDY_", upStatus())
- infrared_count = 0
- ClearKcnt() -- 上报数据清除电机次数
- log.info("++++++++ 3 !!!!!!!!")
- end
- sys.wait(100)
- log.info("+++++++++ 4 !!!!!!!!")
- end
- end
- )
- -- 每隔5秒更新主板数据and打印
- sys.taskInit(function()
- sys.wait(5 * 1000)
- while true do
- log.warn("................................Mainboard-uart 通信中1....................................")
- PrintData()
- --getStatus()
- local firmware_name = rtos.get_version() -- 获取底层固件版本
- local space = rtos.get_fs_free_size() -- 获取文件系统剩余空间(单位Bytes)
- local netmode = net.getNetMode() -- 4:4G LTE网络
- local SIMS = sim.getStatus() -- 获取sim卡的状态
- log.warn("Clear worm time is:", clt_t)
- log.warn("Data time is:", dat_f)
- log.warn("Now firmware version is:", firmware_name .. " PROJECT:" .. _G.PROJECT .. " VERSION:" .. _G.VERSION)
- log.warn("File system free space:", space)
- log.warn("Net mode is:", netmode)
- log.warn("Sim status is:", SIMS)
- sys.wait(5 * 1000)
- end
- end)
- --++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- -- 重启预警函数
- function getRebootState()
- rebootstate = io.readFile(DEV_REBOOT) -- 开机获取设备启动次数
- rebootinfo = io.readFile(DEVICE_ERR) -- 开机获取设备软件重启原因
- if rebootstate == nil then
- log.info("first startup!!!!!!!!")
- rebootstate = 0
- end
- rebootstate = rebootstate + 1
- io.writeFile(DEV_REBOOT, rebootstate)
- end
- --------------------------------------------光栅计数线程---------------------------------------------------
- sys.taskInit(function()
- -- GPIO中断处理函数(修正递归调用问题)
- local function gpioInterruptHandler(msg)
- log.info("GPIO中断", "触发类型:", msg)
- if msg == cpu.INT_GPIO_POSEDGE then
- if result_crc.ds == 1 then
- infrared_count = infrared_count + 1 -- 操作局部变量
- log.info("红外计数器", "当前值:", infrared_count)
- log.info("GPIO_2", "检测到上升沿触发")
- else
- infrared_count = 0
- end
- else
- log.info("GPIO_2", "非上升沿触发事件")
- end
- end
- -- 配置GPIO引脚及中断
- local function setupGPIO()
- log.info("GPIO初始化", "开始配置P0_2...")
- local pin = pins.setup(pio.P0_2, gpioInterruptHandler,pio.PULLUP)-- 绑定处理函数
- if not pin then
- log.error("GPIO配置", "P0_2初始化失败!")
- return false
- end
- log.info("GPIO配置", "P0_2上升沿中断已启用")
- return true
- end
- -- 主任务逻辑
- if setupGPIO() then
- while true do
- sys.wait(1000) -- 示例:每1秒输出当前计数
- log.info("状态报告", "累计触发次数:", infrared_count)
- end
- else
- log.error("任务终止", "GPIO初始化失败")
- end
- end)
- -- function Interrupt_re(msg)
- -- log.info("testGpioSingle.gpio2IntFnc",msg,Interrupt_re())
- -- log.info("first infrared_count!!!!!!!!")
- -- if msg == cpu.INT_GPIO_POSEDGE then
- -- infrared_count = infrared_count + 1
- -- log.info("infrared_count", infrared_count)
- -- log.info("GPIO_2 被触发")
- -- else
- -- log.info("GPI0_2 未触发")
- -- end
- -- end
- -- Interrupt_re = pins.setup(pio.P0_2,Interrupt_re,pio.PULLUP)
- --------------------------------------------光栅计数线程---------------------------------------------------
- ---+++++++++++++++++++++++++++++++++++++++++++++ * Mainboard-uart 通信中 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- --每隔10秒打印输出
- sys.taskInit(
- function()
- getRebootState()
- sys.wait(100)
- while true do
- log.warn("................................Mainboard-uart 通信中....................................")
- PrintData()
- sys.wait(5 * 1000)
- end
- end
- )
- --BootLoader交互信息下发
- sys.taskInit(
- function()
- sys.wait(500)
- while true do
- if BootLoader_flag == 1 then
- BootLoader_flag = 0
- log.info("BootLoader_flag",BootLoader_flag)
- BootLoader_stm32()
- log.info("stm32 SerialDownload !!!")
- end
- if upgrade_again == 1 then
- log.info("update_stm32 system will upgrade again !!!")
- update32.run()
- end
- sys.wait(500)
- end
- end
- )
- --串口通讯心跳交互
- sys.taskInit(
- function()
- sys.wait(100)
- local uart_flag_count = 0
- local uart_32 = string.char(0xCC,0XDD)
- while true do
- if uart_flag == 1 then
- uart_flag = 0
- uart_flag_count = uart_flag_count + 1
- if uart_flag_count > 5 then
- uart_flag_count = 0
- uart.write(1,uart_32)
- log.info("uart_flag back!!!!")
- end
- end
- sys.wait(50)
- end
- end
- )
- -- 串口缓冲区最大值
- local SENDSIZE = 128
- --串口写空闲
- local writeIdle = {true}
- --数据发送的消息队列
- recvBuff = {{}}
- local writeBuff = {{}}
- local uartReadTime = 50 -- 串口读超时
- local flowCount = {0, 0}
- local uid = 1
- -- 写标志位
- local function writeDone()
- if #writeBuff[1] == 0 then
- writeIdle[1] = true
- sys.publish("UART_" .. 1 .. "_WRITE_DONE")
- log.warn("UART_" .. uid .. "write done!")
- else
- writeIdle[1] = false
- uart.write(1, table.remove(writeBuff[1], 1))
- log.warn("UART_" .. 1 .. "writing ...")
- end
- end
- -- uart 写
- function write(str)
- if not str or str == "" or str == nil then
- return
- end
- if str ~= true then
- for i = 1, #str, SENDSIZE do
- table.insert(writeBuff[1], str:sub(i, i + SENDSIZE - 1))
- end
- log.warn("uart" .. 1 .. ".write data length:", writeIdle[1], #str)
- end
- if writeIdle[1] and writeBuff[1] then
- local str = table.concat(writeBuff[1])
- table.remove(writeBuff[1], 1)
- while true do
- uart.write(1, str)
- break
- end
- log.warn("UART_" .. uid .. "writing ...")
- end
- end
- local function read(s)
- local s = table.concat(recvBuff[1])
- local idx, tmp = 1
- local conf = s
- recvBuff[1] = {}
- -- 串口流量统计
- flowCount[1] = flowCount[1] + #s
- log.info("UART_" .. 1 .. "read length:", #s)
- log.info("串口流量统计值:", flowCount[1])
- log.info("UART:",s,string.toHex(s))
- if updateflag == 1 then
- log.info(s)
- sys.publish("YM_IS_OK", s)
- return
- end
- if s:find("update") then --判断是否进入升级模式
- updateflag = 1
- if update32.updateok == 0 then
- s = upwarn("device_stm32", "system will update")
- sys.publish("NET_SENT_RDY_", s)
- else
- s = upwarn("device_stm32", "system is updating......")
- sys.publish("NET_SENT_RDY_", s)
- end
- log.info("update_stm32 system will update !!!")
- update32.run()
- end
- if s:find("bootflag") then --重复远程升级标志位
- upgrade_again = 1
- end
-
- if flowCount[1] == 64 then --串口通讯心跳检测
- uart_flag = 1
- end
- if s:find("Lamp_fauit") then --判断灯管是否故障
- local c = misc.getClock()
- local date = string.format("%00004d-%02d-%02d %02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
- log.info("检测到灯管故障!!!")
- nvm.set("json_w_stm32_app","检测到杀虫灯LED灯管短路:".."故障时间:"..date)
- end
- if s:find("App") then --判断主板是否复位
- local c = misc.getClock()
- local date = string.format("%00004d-%02d-%02d %02d:%02d:%02d", c.year, c.month, c.day, c.hour, c.min, c.sec)
- log.info("检测到stm32复位!!!")
- nvm.set("reboot_stm8",nvm.get("reboot_stm8")+1)
- nvm.set("json_w_stm8boot","检测到主板复位,总复位次数:"..nvm.get("reboot_stm8").."复位时间:"..date)
- end
-
- if #conf == nil or #conf == 0 or conf:len() == 64 then
- log.info("getParam len,value:", string.toHex(conf, " ")) -- 将返回的数据填充到result表
- result.ver = string.sub(conf, 49,63) -- 软件版本-FX-SCD-U-V1.0
- idx, result.iSave = pack.unpack(conf, "b", idx) -- eeprom标志位
- if result.iSave ~= 0xAA then return end -- 判断chuankou上传数据格式是否正确
- idx, result_crc.ds = pack.unpack(conf, ">b", idx) -- 设备状态
- if(result_crc.ds==0 or result_crc.ds==1) then result.ds = result_crc.ds end
- idx, result_crc.tt = pack.unpack(conf, "b", idx) -- 光控时长小时
- if(result_crc.tt>=0 and result_crc.tt<8) then result.tt = result_crc.tt end
- idx, result_crc.ws = pack.unpack(conf, "b", idx) -- 工作状态
- if(result_crc.ws==0 or result_crc.ws==1 or result_crc.ws==2) then result.ws = result_crc.ws end
- idx, result_crc.lps = pack.unpack(conf, "b", idx) -- 光控状态
- if(result_crc.lps==0 or result_crc.lps==1) then result.lps = result_crc.lps end
- idx, result_crc.rps = pack.unpack(conf, "b", idx) -- 雨控状态
- if(result_crc.rps==0 or result_crc.rps==1) then
- result.rps = result_crc.rps
- if(result_crc.rps==1 and rps_y==0) then
- rps_x = 1
- elseif(result_crc.rps==0) then
- rps_y = 0
- end
- end
- idx, result_crc.tps = pack.unpack(conf, "b", idx) -- 温控状态
- if(result_crc.tps==0 or result_crc.tps==1 or result_crc.tps==2) then result.tps = result_crc.tps end
- idx, result_crc.dps = pack.unpack(conf, "b", idx) -- 倾倒保护
- if(result_crc.dps==0 or result_crc.dps==1) then result.dps = result_crc.dps end
- idx, result_crc.vps = pack.unpack(conf, "b", idx) -- 电压状态
- if(result_crc.vps==0 or result_crc.vps==1 or result_crc.vps==2) then result.vps = result_crc.vps end
- idx, result.lcm = pack.unpack(conf, "b", idx) -- 光控类型类型
- idx, result.Lamp = pack.unpack(conf, 'b', idx) -- 灯管故障检测
- idx, result.Infrared = pack.unpack(conf, 'b', idx) -- 红外传感器
- idx, result.kcnt = pack.unpack(conf, "<H", idx) -- 电击击杀检测
- if(result_crc.kcnt>0 and result_crc.kcnt<9000) then result.kcnt = result_crc.kcnt end
- idx, result.cleartim = pack.unpack(conf, 'b', idx) -- 清虫时间间隔
- idx, result.clear_on = pack.unpack(conf, 'b', idx) -- 自清虫标志位
- idx, result.cycle_off = pack.unpack(conf, '<H', idx) --放电结束频率
- idx, result_crc.cv = pack.unpack(conf, "<H", idx) -- 充电电压
- if(result_crc.cv>0 and result_crc.cv<30000) then
- result.cv = result_crc.cv
- if result.cv < 500 then
- result.cv = 0
- end
- end
- idx, result_crc.bv = pack.unpack(conf, "<H", idx) -- 电池电压
- if(result_crc.bv>0 and result_crc.bv<30000) then result.bv = result_crc.bv end
- idx, result.bt = pack.unpack(conf, "<h", idx) -- 主板温度
-
- idx, paramconf.vsunrise = pack.unpack(conf, "<H", idx) -- 日出电压
- idx, paramconf.vsunset = pack.unpack(conf, "<H", idx) -- 日落电压
- idx, paramconf.vcutof = pack.unpack(conf, "<H", idx) -- 充电截至电压
- idx, paramconf.vfloat = pack.unpack(conf, "<H", idx) -- 充电浮充电压
- idx, paramconf.vrecharge = pack.unpack(conf, "<H", idx) -- 再次启动充电动作的电压
- idx, paramconf.vstart = pack.unpack(conf, "<H", idx) -- 首次启动电压
- idx, paramconf.uvoff = pack.unpack(conf, "<H", idx) -- 欠压解锁电压
- idx, paramconf.uvon = pack.unpack(conf, "<H", idx) -- 欠压锁定电压
- idx, paramconf.overtemp = pack.unpack(conf, "<H", idx) -- 高温保护
- idx, paramconf.lowtemp = pack.unpack(conf, "<H", idx) -- 低温保护
- idx, paramconf.unovert = pack.unpack(conf, "<H", idx) -- 高温解锁
- idx, paramconf.unlowt = pack.unpack(conf, "<H", idx) -- 低温解锁
- return result
- end
-
- end
- -- 串口配置
- function uart_INIT()
- uart.setup(1, 9600, 8, uart.PAR_NONE, uart.STOP_1)
- uart.on(1, "sent", writeDone)
- uart.on(
- 1,
- "receive",
- function()
- table.insert(recvBuff[1], uart.read(1, 8192))
- sys.timerStart(sys.publish, tonumber(uartReadTime) or 30, "UART_RECV_WAIT_")
- end
- )
- -- 处理串口接收到的数据
- sys.subscribe("UART_RECV_WAIT_", read)
- sys.subscribe("UART_SENT_RDY_", write)
- end
- local timecnt = 1
- -- 每隔1分钟重置串口计数
- sys.timerLoopStart(
- function()
- flow = tonumber(flow)
- if flow and flow ~= 0 then
- if flowCount[1] > flow then
- uart.on(1, "receive")
- log.info("uart1.read length count:", flowCount[1])
- end
- end
- if timecnt > 10 then
- timecnt = 1
- flowCount = {0, 0}
- else
- timecnt = timecnt + 1
- end
- end,
- 1000
- )
- --*********************开机运行**************************
- uart_INIT()
|