nana_sen 2 년 전
부모
커밋
af78118d8d
11개의 변경된 파일523개의 추가작업 그리고 105개의 파일을 삭제
  1. 3 0
      cmd.json
  2. 19 6
      config.lua
  3. 30 1
      devTool.lua
  4. 3 4
      g33mqtt.lua
  5. 25 2
      gpsTask.lua
  6. 3 1
      luatide_project.json
  7. 2 2
      main.lua
  8. 273 73
      modbusTT.lua
  9. 57 0
      mqtt_recieve.lua
  10. 6 10
      powerManage.lua
  11. 102 6
      sdModuel.lua

+ 3 - 0
cmd.json

@@ -0,0 +1,3 @@
+[
+    {"OpType":"directive","CntType":"Config","CntVersion":"1667360654125","Content":{"gpsLng":"120.411725","gpsLat":"30.361992", "gpsTime": 1663579568}}
+]

+ 19 - 6
config.lua

@@ -9,20 +9,24 @@ otaUrl = "47.114.185.186:11113/api/site/firmware_upgrade"
 --ota升级检查周期
 otaCheckInterval = 1200
 -- 本地数据最新版本号
-localCntVersion = "1663321109122"
+localCntVersion = "1667542282722"
+localCntUpdateTime = "0"
 -- 心跳间隔/s
 heartbeatInterval = 600
-
+restartInterval = 86400
 
 -- GPS相关
 gpsEnable = 1
-gpsLng = "0"
+gpsLng = "120.411725"
 lngType = "X"
 --GPS主动定位纬度
-gpsLat = "0"
+gpsLat = "30.361992"
 latType = "X"
 --gps主动定位时间
-gpsTime = 0
+gpsTime = 1663579568
+--gps上报间隔
+gpsInterval = 1800
+
 
 
 -- 泵状态相关 
@@ -35,9 +39,12 @@ elecValve = 0  --电磁阀寿命当前值
 hydOilThr = 90 --液压油告警阈值
 scaleValveThr = 90--比例阀告警阈值
 elecValveThr = 90--电磁阀告警阈值
+
+--低电阈值
+lowBatThd = 3300
  
 lastWorkField = "W045" --上次作业风场编号
-fieldDisplayRadius = 20
+fieldDisplayRadius = 200
 
 --错误日志上报地址
 errorLogReportUrl = "udp://47.114.185.186:11114"
@@ -45,5 +52,11 @@ errorLogReportInterval = 600
 --重启次数
 bootNum = 0
 
+newPumbModel = ""
+newPumbNumber = ""
+oldPumbModel = ""
+oldPumbNumber = ""
+
+
 
 

+ 30 - 1
devTool.lua

@@ -14,4 +14,33 @@ function getDistance( lat1, lng1, lat2, lng2 )
     local s = s * ERadius
     local s = math.floor(s * 10000+0.5) / 10000
     return s
-end
+end
+
+function getPresentAfterHmac( str )
+    -- body
+    
+    if type(str) ~= "string" then
+        -- body
+        return false
+    end
+    sha1Str = crypto.sha1(str)
+    return  sha1Str:sub(1,2)
+end
+
+function guid()
+    math.random( 1,32 )
+    math.randomseed(os.time())
+    local seed={'e','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}
+    local tb={}
+    for i=1,32 do
+        table.insert(tb,seed[math.random(1,16)])
+    end
+    local sid=table.concat(tb)
+    return string.format('%s-%s-%s-%s-%s',
+        string.sub(sid,1,8),
+        string.sub(sid,9,12),
+        string.sub(sid,13,16),
+        string.sub(sid,17,20),
+        string.sub(sid,21,32)
+    )
+end

+ 3 - 4
g33mqtt.lua

@@ -26,9 +26,6 @@ local isOtaCheckEnd = false
 --     isOtaCheckEnd = true
 -- end)
 
-
-
-
 --启动MQTT客户端任务
 sys.taskInit(
     function()
@@ -56,7 +53,9 @@ sys.taskInit(
                     --订阅主题
                     local topics = {
                         ["SHEGCL/IntelligenTool/UpdateToolInfo/"..imei] = 0, 
-                        ["SHEGCL/TestR/"..imei]=0
+                        ["SHEGCL/IntelligenTool/UploadWorkRecordMA/"..imei]=0,
+                        ["SHEGCL/IntelligenTool/UploadWorkRecordFA/"..imei]=0,
+                        ["SHEGCL/IntelligenTool/Heart/"..imei]=0
                     }
                     if mqttClient:subscribe(topics) then
                         --循环处理接收和发送的数据

+ 25 - 2
gpsTask.lua

@@ -114,6 +114,29 @@ function openGpsSwitch( )
     end
 end
 
-openGpsSwitch()
 
-sys.timerLoopStart(openGpsSwitch,1800*1000)
+
+local gpsInterval = nvm.get("gpsInterval") or 1800
+sys.timerLoopStart(openGpsSwitch, gpsInterval*1000)
+
+
+
+sys.taskInit(function()
+    sys.wait(5000)
+    openGpsSwitch()
+    while true do
+        if socket.isReady() then    --连上网再开始运行
+
+            local result = sys.waitUntil("pub_gps_location_success_msg")
+
+            if socket.isReady() and result == true then
+                -- body
+                local heartBeatData =modbusTT.getHeartbeatContent()
+                sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/Heart",["data"]=heartBeatData}))
+            end
+        else    --没连上网别忘了延时!不然会陷入while true死循环,导致模块无法运行其他代码
+            -- log.info("socket not ready")
+            sys.wait(5000)          --等待5秒
+        end
+    end
+end)

+ 3 - 1
luatide_project.json

@@ -22,5 +22,7 @@
 		"powerManage.lua",
 		"sdModuel.lua"
 	],
-	"ignore": []
+	"ignore": [
+		"cmd.json"
+	]
 }

+ 2 - 2
main.lua

@@ -1,5 +1,5 @@
 PROJECT = "Rlian-GATEWAY-G33"
-VERSION = "1.0.11"
+VERSION = "1.0.20"
 PRODUCT_KEY = "ddd0422aef65441cbe1c6cccd84e2fa0"
 require 'log'
 LOG_LEVEL = log.LOGLEVEL_TRACE
@@ -29,7 +29,7 @@ errDump.request(errorLogReportUrl,errorLogReportInterval*1000)
 require "devTool"
 require "sdModuel"
 require "logModuel"
-require "gpsTask"
+-- require "gpsTask"
 require "ledTask"
 require "g33mqtt"
 require "modbusTT"

+ 273 - 73
modbusTT.lua

@@ -57,6 +57,11 @@ queryFlagResReg["00d2"] = "0000"
 queryFlagResReg["00d3"] = "0000"
 queryFlagResReg["00d4"] = "0000"          --  1400
 local queryRespData = {}            -- 
+local newPumbModelT = ""
+local newPumbNumberT = ""
+local oldPumbModelT = ""
+local oldPumbNumberT = ""
+local sensorNumberT = ""
 
 -- 获取table长度
 function table_leng(t)
@@ -91,6 +96,11 @@ function getAscii2StringHexBe( str, width )
     -- body
     local hexStr = ""
 
+    if width == 0 then
+        -- body
+        return hexStr
+    end
+
     for i=1,#str, 2 do
         if i+1 > #str then
             -- body
@@ -152,13 +162,10 @@ end
 
 local function handlePumbHeart( startAddress, regNumber, data )
     local startAddDec = tonumber(startAddress, 16)
-    if startAddDec == 400 then
-        -- body
-        return true
-    end
+    local regNumberDec = tonumber(regNumber, 16)
     -- 01 10 0191 0001 02 0001 6bd1
 
-    for i=8, (8 + 2 *regNumber)-1 , 2 do
+    for i=1, 2*regNumberDec , 2 do
 
         local value = tonumber(data:sub(i,i+1):toHex(), 16)
         if startAddDec == 401 then
@@ -194,6 +201,74 @@ local function handlePumbHeart( startAddress, regNumber, data )
                 nvm.set("elecValve", value)
             end
         end
+        if startAddDec == 413 then
+            -- body
+            -- log.info("dianci", startAddDec, value)
+            if nvm.get("filterValue") ~= value then
+                -- body
+                nvm.set("elecValve", value)
+            end
+        end
+
+
+        if startAddDec > 419 and startAddDec < 430  then
+            -- body
+            -- log.info("dianci", startAddDec, value)
+            newPumbModelT = newPumbModelT .. data:sub(i,i+1)
+
+            if #newPumbModelT == 20 then
+                -- body
+                newPumbModelT = getByte2AsciiStr(newPumbModelT)
+                nvm.set("newPumbModel", newPumbModelT)
+                newPumbModelT = ""
+            end
+        end
+        if startAddDec > 429 and startAddDec < 440 then
+            -- body
+            -- log.info("dianci", startAddDec, value)
+            newPumbNumberT = newPumbNumberT .. data:sub(i,i+1)
+            if #newPumbNumberT == 20 then
+                -- body
+                newPumbNumberT = getByte2AsciiStr(newPumbNumberT)
+                nvm.set("newPumbNumber", newPumbNumberT)
+                newPumbNumberT = ""
+            end
+        end
+        if startAddDec > 439 and startAddDec < 450  then
+            -- body
+            -- log.info("dianci", startAddDec, value)
+            oldPumbModelT = oldPumbModelT .. data:sub(i,i+1)
+            if #oldPumbModelT == 20 then
+                -- body
+                oldPumbModelT = getByte2AsciiStr(oldPumbModelT)
+                nvm.set("oldPumbModel", oldPumbModelT)
+                oldPumbModelT = ""
+            end
+        end
+        if startAddDec > 449 and startAddDec < 460  then
+            -- body
+            -- log.info("dianci", startAddDec, value)
+            oldPumbNumberT = oldPumbNumberT .. data:sub(i,i+1)
+            if #oldPumbNumberT == 20 then
+                -- body
+                oldPumbNumberT = getByte2AsciiStr(oldPumbNumberT)
+                nvm.set("oldPumbNumber", oldPumbNumberT)
+                oldPumbNumberT = ""
+            end
+        end
+        if startAddDec > 459 and startAddDec < 470  then
+            -- body
+            -- log.info("dianci", startAddDec, value)
+            sensorNumberT = sensorNumberT .. data:sub(i,i+1)
+            if #sensorNumberT == 20 then
+                -- body
+                sensorNumberT = getByte2AsciiStr(sensorNumberT)
+                nvm.set("sensorNumber", sensorNumberT)
+                sensorNumberT = ""
+            end
+        end
+
+        
 
         startAddDec = startAddDec +1
     end
@@ -334,7 +409,8 @@ local function proc( data )
         
         if regAddHex >= 400  and regAddHex < 500 then  --泵心跳相关
             -- queryFlagResReg[startRegAddress] = data
-            handlePumbHeart(startRegAddress, regNumber,data)
+            local byteCount = string.format("%02x",data:byte(7))
+            handlePumbHeart(startRegAddress, regNumber,data:sub(8, tonumber(byteCount, 16)+7))
         end
 
         if regAddHex >= 1400  then
@@ -429,10 +505,8 @@ local function proc( data )
                         mobBussErrSend(slaveAdd, "83", "03")
                         return false
                     end
-                    
                 end
             end
-
             if not respValue then
                 -- body
                 logModuel.debug_log("modbus.proc error! maybe receive data unusual or sequence not correct! regAddHex=" .. regAddHex)
@@ -448,16 +522,78 @@ local function proc( data )
             return true
         end
 
+        if regAddHex >= 600 and regAddHex < 700 then
+            -- body
+            local regNumberDec,startRegAddressDec = tonumber(regNumber,16),  tonumber(startRegAddress,16)
+
+            local networkInfo = getNetWorkInfoHex()
+
+
+            local stap = (regAddHex-600)*4+1
+            local endp = regNumberDec*4 + stap-1
+        
+            
+            for i=stap,endp, 4 do
+                respValue = respValue.. networkInfo:sub(i, i+3)
+            end
+            byteCount = string.format("%02x", tonumber(regNumber, 16)*2)
+            multiRespData = (slaveAdd..functionCode..byteCount..respValue):fromHex()
+            respCrc = pack.pack('<h', crypto.crc16("MODBUS",multiRespData))
+            
+            logModuel.debug_log("send 485:"..(multiRespData..respCrc):toHex())
+            uart.write(uart_id, multiRespData..respCrc)
+            return true
+        end
 
         mobBussErrSend(slaveAdd, "83", "01")
         return false
 
-
     end
 
 end
 
 
+function getNetWorkInfoHex(  )
+    -- body
+    netWorkDeviceData = ""
+    local dateObj = os.date("*t")
+    local temp = ""
+    for i=600,619 do
+        local regHex = string.format("%04x", i)
+
+        if i == 600 then
+            -- body
+            temp = "0001"
+        elseif i == 601 then
+            -- body
+            local csq = math.floor( (net.getRssi() / 31 * 100) )
+            temp = string.format("%04x", csq)
+        elseif i == 602 then
+            temp = string.format("%04x", 0)
+        elseif i == 610 then
+            temp = string.format("%04x", dateObj.year)
+        elseif i == 611 then
+            temp = string.format("%04x", dateObj.month)
+        elseif i == 612 then 
+            temp = string.format("%04x", dateObj.day)
+        elseif i == 613 then
+            temp = string.format("%04x", dateObj.hour)
+        elseif i == 614 then
+            temp = string.format("%04x", dateObj.min)
+        elseif i == 615 then
+            temp = string.format("%04x", dateObj.sec)
+        else
+            temp = "0000"
+        end
+        netWorkDeviceData = netWorkDeviceData .. temp
+    end
+    local dataVersion = getAscii2StringHexBe(nvm.get("localCntVersion"), 20)
+    local updateTime = getAscii2StringHexBe(nvm.get("localCntUpdateTime"), 20)
+    local imei = getAscii2StringHexBe(misc.getImei(), 20)
+    
+    return netWorkDeviceData .. dataVersion ..updateTime ..imei
+end
+
 
 
 
@@ -618,7 +754,6 @@ end
 local function query0064Res()
     -- body
     respRegAddress = "00c8"
-    queryFlagResReg[respRegAddress] = "0002"
 
     local conds = table.concat(queryCondRegValue)
     if #conds < 20 then
@@ -656,8 +791,15 @@ local function query0064Res()
         getAscii2StringHexBe(singleRes.clt, 20),
         getAscii2StringHexBe(singleRes.model, 20),
         getAscii2StringHexBe(singleRes.fixed, 20)
+
+        -- 线性方程系数和常数
+        -- pack.pack(">f", singleRes.eq_a):toHex(),
+        -- pack.pack(">f", singleRes.eq_b):toHex()
+
     }
 
+
+
     local res64Hex = table.concat(resT)
     local j = 1
     for i=1400,1439 do
@@ -673,7 +815,6 @@ end
 local function query0065Res()
     -- body
     respRegAddress = "00c9"
-    queryFlagResReg[respRegAddress] = "0002"
 
     local conds = table.concat(queryCondRegValue)
     if #conds < 90 then
@@ -768,7 +909,6 @@ end
 local function query0067Res() 
     -- body
     respRegAddress = "00cb"
-    queryFlagResReg[respRegAddress] = "0002"
 
     local result, count, desc = getBaseInfo_ununique("Wind", nil, "/sdcard0/common")  
 
@@ -853,8 +993,15 @@ local function query0067Res()
     for k,v in pairs(result) do
         local numberHex = getAscii2StringHexBe(v.number, 10)
         local ucs2Bytes = common.utf8ToUcs2be(v.name)
+        local afterHandleNameByte = ""
+
+        if #ucs2Bytes > 40 then
+            -- body
+            ucs2Bytes = ucs2Bytes:sub(1, 40)
+        end
         local nameHex = ucs2Bytes:toHex()..getAscii2StringHexBe("\0", 40-#ucs2Bytes)
-        -- log.info("number:",numberHex, "name:",nameHex)
+        
+        log.info("number:",numberHex, "name:",nameHex)
         regValueHex = regValueHex..numberHex..nameHex
     end
 
@@ -875,9 +1022,6 @@ end
 local function query0068Res()
     -- body
     respRegAddress = "00cc"
-    queryFlagResReg[respRegAddress] = "0002"
-
-
     local conds = table.concat(queryCondRegValue)
     if #conds < 10 then
         -- body
@@ -919,8 +1063,6 @@ end
 local function query0069Res()
     -- body
     respRegAddress = "00cd"
-    queryFlagResReg[respRegAddress] = "0002"
-
     local conds = table.concat(queryCondRegValue)
     if #conds < 10 then
         -- body
@@ -936,16 +1078,11 @@ local function query0069Res()
     queryCondRegValue = {}--清空查询条件
     if not result then
         -- body
+        queryFlagResReg[respRegAddress] = "0002"
         logModuel.debug_log("查询机位列表失败,count:"..count..",desc:"..desc..",querycond_number:"..wnum)
         return false
     end
 
-    -- local result = {
-    --     {wnum="field001", number="fan001", model="fm-001"},
-    --     {wnum="field002", number="fan002", model="fm-002"},
-    --     {wnum="field003", number="fan003", model="fm-003"}
-    -- }
-
     queryRespData["0578"] = string.format("%04x", table_leng(result))
 
 
@@ -974,7 +1111,6 @@ end
 local function query006aRes()
     -- body
     respRegAddress = "00ce"
-    queryFlagResReg[respRegAddress] = "0002"
 
     local result, count, desc = getBaseInfo_ununique("WorkingParts", nil, "/sdcard0/common")  
 
@@ -982,6 +1118,7 @@ local function query006aRes()
     queryCondRegValue = {}--清空查询条件
     if not result then
         -- body
+        queryFlagResReg[respRegAddress] = "0002"
         logModuel.debug_log("查询部件列表失败,count:"..count..",desc:"..desc)
         return false
     end
@@ -1011,7 +1148,6 @@ end
 -- 查询工作位置并写入结果寄存器
 local function query006bRes()
     respRegAddress = "00cf"
-    queryFlagResReg[respRegAddress]  = "0002"
     -- query body
 
     local conds = table.concat(queryCondRegValue)
@@ -1029,15 +1165,10 @@ local function query006bRes()
     queryCondRegValue = {}--清空查询条件
     if not result then
         -- body
+        queryFlagResReg[respRegAddress] = "0002"
         logModuel.debug_log("查询工作位置列表失败,count:"..count..",desc:"..desc..",querycond:"..json.encode({ fmodel=fmdel, Parts=Parts }))
         return false
     end
-    -- local result = {
-    --     {id=123, Parts="测试部件1", name="工作位置1"},
-    --     {id=124,  Parts="测试部件2", name="工作位置2"},
-    --     {id=125, Parts="测试部件3", name="工作位置3"}
-    -- }
-
 
     queryRespData["0578"] = string.format("%04x", table_leng(result))
     
@@ -1054,8 +1185,6 @@ local function query006bRes()
         queryRespData[regHex] = regValueHex:sub(j, j+3)
         j = j+4
     end
-
-
     queryFlagResReg[respRegAddress] = "0001"
     
 end
@@ -1095,6 +1224,7 @@ local function query006cRes(  )
         return false
     end
 
+    local msgid = devTool.guid()
     local upTable = {
         Username =getByte2AsciiStr(conds:sub(1, 20)),  --用户名          string
         WrenchNumber = getByte2AsciiStr(conds:sub(21, 40)),  --扳手编号    string
@@ -1113,7 +1243,10 @@ local function query006cRes(  )
         SetStress = tonumber(conds:sub(173,174):toHex(), 16), --设定压力bar    u16
         FasteningStress = tonumber(conds:sub(175,176):toHex(), 16), --紧固压力bar    u16
         FasteningStatus = tonumber(conds:sub(177,178):toHex(), 16), --紧固状态   u16
-        Time = tonumber(conds:sub(179,180):toHex(), 16) --紧固时间       u16
+        Time = tonumber(conds:sub(179,180):toHex(), 16), --紧固时间       u16
+        netWorkSaveTime = os.time(),
+        msgid = msgid,
+        id = msgid
     }
 
     -- 查询自定义的3字段是否存在,不存在则新增一个
@@ -1121,12 +1254,13 @@ local function query006cRes(  )
 
     -- 待上传 upTable 全部
 
-    if socket.isReady() then
-        -- body
-        sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordMA",["data"]=upTable}))
-    else
-        saveBaseInfo("wait2upload", {["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordMA",["data"]=upTable}, "/sdcard0/common")
-    end
+    -- if socket.isReady() then
+    --     -- body
+    --     sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordMA",["data"]=upTable}))
+    --     local uploadRes,msgid = sys.waitUntil("WAIT_UPDATA_RESP_SUCCESS")
+    -- else
+        saveBaseInfo("wait2upload", {["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordMA",["data"]=upTable,["id"]=msgid}, "/sdcard0/common/temp")
+    -- end
 
     -- 工作记录表 boltTotal, fastenNm  风场编号+机位号+风机型号+部件号+工作位置
     local localRecord = {
@@ -1146,7 +1280,6 @@ local function query006cRes(  )
 
     if not result or desc:sub(1, 29) == "this data not found where id=" then
         -- body
-        log.info("xxxxxxxxxxxx")
         result, desc =  saveBaseInfo("WorkRecord", localRecord, "/sdcard0/"..localRecord.wnum .."/".. localRecord.fnum )
     end
 
@@ -1173,6 +1306,8 @@ local function query006dRes()
         queryFlagReg["006d"] = "0000"
         return false
     end
+
+    local msgid = devTool.guid()
     local upTable = {
         Username =getByte2AsciiStr(conds:sub(1, 20)),  --用户名          string
         WrenchNumber = getByte2AsciiStr(conds:sub(21, 40)),  --扳手编号    string
@@ -1192,7 +1327,10 @@ local function query006dRes()
         FasteningStress = tonumber(conds:sub(175,176):toHex(), 16), --紧固压力bar    u16
         FasteningStatus = tonumber(conds:sub(177,178):toHex(), 16), --紧固状态   u16
         Time = tonumber(conds:sub(179,180):toHex(), 16), --紧固时间       u16
-        WrenchAngle = tonumber(conds:sub(181,182):toHex(), 16) --扳手转动角度      u16
+        WrenchAngle = tonumber(conds:sub(181,182):toHex(), 16), --扳手转动角度      u16
+        netWorkSaveTime = os.time(),
+        msgid = msgid,
+        id = msgid
     }
 
     -- 查询自定义的3字段是否存在,不存在则新增一个
@@ -1200,12 +1338,12 @@ local function query006dRes()
 
     -- 待上传 upTable 全部
 
-    if socket.isReady() then
-        -- body
-        sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordFA",["data"]=upTable}))
-    else
-        saveBaseInfo("wait2upload", {["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordFA",["data"]=upTable}, "/sdcard0/common")
-    end
+    -- if socket.isReady() and (net.getRssi() > 14) then
+    --     -- body
+    --     sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordFA",["data"]=upTable}))
+    -- else
+        saveBaseInfo("wait2upload", {["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordFA",["data"]=upTable,["id"]=msgid}, "/sdcard0/common/temp")
+    -- end
 
     -- 工作记录表 boltTotal, fastenNm  风场编号+机位号+风机型号+部件号+工作位置
     local localRecord = {
@@ -1262,7 +1400,7 @@ local function query006eRes()
         sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordSimple",["data"]=upTable}))
         result = true
     else
-        result = saveBaseInfo("wait2upload", {["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordSimple",["data"]=upTable}, "/sdcard0/common")
+        result = saveBaseInfo(" ", {["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordSimple",["data"]=upTable}, "/sdcard0/common")
     end
 
     queryFlagReg["006e"] = "0000"
@@ -1275,27 +1413,31 @@ local function query006eRes()
     end
 end
 
-
 -- 获取任务编号列表
 local function query006fRes()
     -- body
     respRegAddress = "00d3"
-    queryFlagResReg[respRegAddress] = "0002"
 
-    local result, count, desc = getBaseInfo_ununique("WorkPlan", nil, "/sdcard0/common")  
+    local conds = table.concat(queryCondRegValue)
+    if #conds ~= 30 then
+        -- body
+        queryFlagReg["006f"] = "0000"
+        return false
+    end
+    local wind = getByte2AsciiStr(conds:sub(1, 10))--查询条件
+    local fmodel = getByte2AsciiStr(conds:sub(11, 30))--查询条件
+
+    local result, count, desc = getBaseInfo_ununique("WorkPlan", {wnum=wind,fmodel=fmodel}, "/sdcard0/common")  
 
     queryFlagReg["006f"] = "0000"
     queryCondRegValue = {}--清空查询条件
     if not result then
         -- body
+        queryFlagResReg[respRegAddress] = "0002"
         logModuel.debug_log("查询任务编号列表失败,count:"..count..",desc:"..desc)
         return false
     end
-    -- local result = {
-    --     {id=123, info="任务测试描述1", pnum="plan-001"},
-    --     {id=124,  info="任务测试描述2", pnum="plan-002"},
-    --     {id=125, info="任务测试描述3", pnum="plan-003"}
-    -- }
+
     queryRespData["0578"] = string.format("%04x", table_leng(result))
     local regValueHex = ""
     for k,v in pairs(result) do
@@ -1340,14 +1482,6 @@ local function query0070Res()
         logModuel.debug_log("查询任务具体详情失败,count:"..count..",desc:"..desc,",cond_pnum="..cond)
         return false
     end
-
-    
-    -- local result = {
-    --     {id=123, pnum="plan-01" ,
-    --     info="测试任务描述1", wnum="field001",
-    --     wname="测试风场1",fnum="fj001",fmodel="fm-001",
-    --     parts="测试部件001",work="测试位置01",bm="lx-001", bn=10, tm=1, bias=5,lt=987654, torque=987654}
-    -- }
     local singleRes = result[1]
     local lt = pack.pack('>I', singleRes.lt)
     local torque = pack.pack('>I', singleRes.torque)
@@ -1369,7 +1503,6 @@ local function query0070Res()
         torque:sub(3, 4):toHex() .. torque:sub(1, 2):toHex()
     }
 
-
     local resValueHex = table.concat(resT)
     local j = 1
     
@@ -1382,12 +1515,62 @@ local function query0070Res()
     queryFlagResReg[respRegAddress] = "0001"
 end
 
+-- 获取扳手编号列表_模糊查询
+local function query0071Res()
+    -- body
+    respRegAddress = "00d5"
+    
+    local conds = table.concat(queryCondRegValue)
+    -- if #conds < 20 then
+    --     -- body
+    --     queryFlagReg["0064"] = "0000"
+    --     return false
+    -- end
+    local seachStr = getByte2AsciiStr(conds)--查询条件
+
+    local result, count, desc = getBaseInfo_ununique_dim("Wrench", {number = seachStr ,fixed = seachStr}, "/sdcard0/common")  
+
+    queryFlagReg["0071"] = "0000"
+    queryCondRegValue = {}--清空查询条件
+    if not result then
+        -- body
+        queryFlagResReg[respRegAddress] = "0002"
+        logModuel.debug_log("查询扳手编号列表失败,count:"..count..",desc:"..desc)
+        return false
+    end
+
+    queryRespData["0578"] = string.format("%04x", table_leng(result))
+    local regValueHex = ""
+    for k,v in pairs(result) do
+        local number = getAscii2StringHexBe(v.number, 20)
+        log.info("number:", v.number)
+        regValueHex = regValueHex..number
+    end
+
+    local j = 1 
+    for i=1410, 1409 + 10*table_leng(result) do
+        local regHex = string.format("%04x", i)
+        queryRespData[regHex] = regValueHex:sub(j, j+3)
+        j = j+4
+    end
+
+    queryFlagResReg[respRegAddress] = "0001"
+end
+
+-- 泵到网关心跳
 function query0191Res()
     -- body
     if condition then
         -- body
     end
 end
+-- 网关到泵心跳
+function query0258Res()
+    -- body
+    if condition then
+        -- body
+    end
+end
 
 
 local function queryByRegAdd(regAddress)
@@ -1445,11 +1628,13 @@ local function queryByRegAdd(regAddress)
         -- body
         query0070Res()
     end
+    if regAddress == "0071" then
+        -- body
+        query0071Res()
+    end
 end
 
 
-
-
 local function queryByQueryflag()
 
     while true do
@@ -1485,7 +1670,13 @@ function getHeartbeatContent(  )
     local vbatt = math.ceil( 1.68 * voltval )
     local ram = _G.collectgarbage("count")
     local flash = rtos.get_fs_free_size(0,1)
-    local SDInfo = rtos.get_fs_free_size(1,1)
+    -- local SDInfo = rtos.get_fs_free_size(1,1)
+    local Status = 0
+
+    if powerManage.setGpio11Fnc() == 1 then
+        -- body
+        Status = 1
+    end
 
     local heartBeat = {
         IMEI = misc.getImei(),
@@ -1493,16 +1684,22 @@ function getHeartbeatContent(  )
         CCID = sim.getIccid(),
         CSQ = net.getRssi(),
         GPS = gpsStr,
+        Status = Status,
         lngType = nvm.get("lngType"),
         latType = nvm.get("latType"),
         LastGPSLocTime = nvm.get("gpsTime") ,
         Power = vbatt,
         RamInfo = ram..","..flash,
-        SDInfo = SDInfo,
         SoftVersion = _G.VERSION,
         HeartTimeInterval =  nvm.get("heartbeatInterval"),
         CntVersion =  nvm.get("localCntVersion"),
         pumbStatus = nvm.get("pumbStatus"),
+        newPumbModel = nvm.get("newPumbModel"),
+        newPumbNumber = nvm.get("newPumbNumber"),
+        oldPumbModel = nvm.get("oldPumbModel"),
+        oldPumbNumber = nvm.get("oldPumbNumber"),
+        sensorNumber = nvm.get("sensorNumber"),
+        msgid = devTool.guid(),
         time = os.time()
     }
     return heartBeat
@@ -1554,11 +1751,13 @@ function checkNetWorkHealth( msgType )
     local alarmType, alarmReason = "gateway", {}
     local adcval,voltval = adc.read(BAT_ADC_ID)
     local vbatt = math.ceil( 1.68 * voltval )
+
+    local lowBatThd = nvm.get("lowBatThd") or 3300
     if msgType then
         -- body
         table.insert(alarmReason, msgType)
     else
-        if vbatt < 3500 then
+        if vbatt < lowBatThd then
             -- body
             table.insert(alarmReason, "network_bat_lower")
         end
@@ -1592,12 +1791,12 @@ end)
 
 
 
-sys.timerLoopStart(checkPumbHeartbeatExtra,600000)
+sys.timerLoopStart(checkPumbHeartbeatExtra,60000)
 
 
 
 local heartbeatInterval = nvm.get("heartbeatInterval") or 600 
+-- 定时心跳
 sys.taskInit(function()
     sys.wait(5000)
     while true do

+ 57 - 0
mqtt_recieve.lua

@@ -1,5 +1,13 @@
 module(...,package.seeall)
 
+function table_leng(t)
+    local leng=0
+    for k, v in pairs(t) do
+      leng=leng+1
+    end
+    return leng;
+  end
+
 local DIR_PATH = {
     Users = "/sdcard0/common",
     Wrench = "/sdcard0/common",
@@ -141,7 +149,10 @@ function operateFs(op, cntType, cntVersion, content )
     local localVersion = nvm.get("localCntVersion")
     if cntVersion > localVersion then
         -- body
+        local dateObj = os.date("*t")
+        local updateTime = dateObj.year .. dateObj.month .. dateObj.day .. dateObj.hour .. dateObj.min .. dateObj.sec
         nvm.set("localCntVersion", cntVersion)
+        nvm.set("localCntUpdateTime", updateTime)
         log.info("nvm set success, value:", cntVersion)
     end
 
@@ -175,6 +186,14 @@ function proc(mqttClient)
 
         if result then
             local resData = json.decode(data.payload)
+            
+            log.info("origin mqttrec data:",data.payload)
+            if resData.msgid and resData.success then
+                -- body
+                log.info("three topic msgid:",resData.msgid, "type:", type(resData.msgid))
+                sys.publish("WAIT_UPDATA_RESP_SUCCESS", resData.msgid )
+                break
+            end
 
             local ack = {
                 Imei = misc.getImei(),
@@ -226,6 +245,12 @@ function proc(mqttClient)
                 param = json.decode(param)
                 if param.topic and param.data then
                     -- body
+
+                    -- if param.topic == "SHEGCL/IntelligenTool/UploadWorkRecordMA" or param.topic == "SHEGCL/IntelligenTool/UploadWorkRecordFA" or param.topic == "SHEGCL/IntelligenTool/Heart" then
+                    --     -- body
+                    --     upData.msgid = devTool.guid()
+                    -- end
+
                     local upData = param.data
                     upData.PublishVersion = nvm.get("localCntVersion")
                     upData.IMEI = misc.getImei()
@@ -246,3 +271,35 @@ end
 
 
 
+--定时上传因网络问题未上传的数据
+function uploadOfflineData(  )
+    sys.wait(5000)
+    -- body
+    while true do
+
+        if socket.isReady() then
+            -- body
+            local uploadData, cn, des = getBaseInfo_ununique("wait2upload", nil, "/sdcard0/common/temp")
+            if not uploadData then
+                -- body
+                log.info("wait2upload file is empty!", "count:", cn, "des:", des)
+            else
+                for k,v in pairs(uploadData) do
+                    sys.publish("LOCAL_PUB_MSG", json.encode(v) )
+                    local uploadRes,msgid = sys.waitUntil("WAIT_UPDATA_RESP_SUCCESS", 3000)
+                    if  uploadRes and msgid then
+                        local re,be,ce = delBaseInfo("wait2upload",msgid,"/sdcard0/common/temp")
+                    end
+                    sys.wait(500)
+                end
+
+            end
+        end
+
+        sys.wait(10000)
+    end
+end
+
+sys.taskInit(uploadOfflineData)
+
+

+ 6 - 10
powerManage.lua

@@ -16,25 +16,27 @@ local function powerInterrupt( msg )
     end
 end
 
-local setGpio11Fnc = pins.setup(pio.P0_11, powerInterrupt )
+setGpio11Fnc = pins.setup(pio.P0_11, powerInterrupt )
 
 function closePDs(  )
     -- body
     uart.close(1) --关闭串口1
-    pins.setup(pio.P0_18, 1) --断电GPS
+    -- pins.setup(pio.P0_18, 1) --断电GPS
     pins.setup(pio.P0_13, 1) --断电485
 end
 
 
 local function setRestartClock(  )
+
+    local restartInterval = nvm.get("restartInterval") or 86400
     -- body
     log.info("alarm test start")
     local t = os.date("*t")
     misc.setClock({year=t.year,month=t.month,day=t.day,hour=t.hour,min=t.min,sec=t.sec})
     sys.wait(2000)
     closePDs()
-    local onTimet = os.date("*t",os.time() + 3600)  --下次要开机的时间为1800秒后
-    log.info("alarm restart time", 3600)
+    local onTimet = os.date("*t",os.time() + restartInterval)  --下次要开机的时间为1800秒后
+    log.info("alarm restart time", restartInterval)
     rtos.set_alarm(1,onTimet.year,onTimet.month,onTimet.day,onTimet.hour,onTimet.min,onTimet.sec)   --设定闹铃
     --如果要测试关机闹钟,打开下面这2行代码
     sys.wait(200000)
@@ -45,12 +47,6 @@ local function powerTaskFnc(  )
     -- body
     sys.wait(10000)
 
-    if socket.isReady() then
-        -- body
-        local heartBeatData =modbusTT.getHeartbeatContent()
-        sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/Heart",["data"]=heartBeatData}))
-    end
-
     power24Flag = setGpio11Fnc()
     log.info("当前24V电平:", power24Flag)
 

+ 102 - 6
sdModuel.lua

@@ -331,7 +331,7 @@ end
         end
         filehandle:close() -- 关闭文件
     end
-    print(table_leng(selectRes),json.encode(selectRes))
+    -- print(table_leng(selectRes),json.encode(selectRes))
     if table_leng(selectRes) > 0 then
          --去重
         local result = table.unique(selectRes,true,'id')
@@ -406,7 +406,100 @@ function getBaseInfo_ununique( filename,param,dirPath)
         -- end
         filehandle:close() -- 关闭文件
     end
-    print(table_leng(selectRes),json.encode(selectRes))
+    -- print(table_leng(selectRes),json.encode(selectRes))
+    if table_leng(selectRes) > 0 then
+         --去重
+        local result = table.unique(selectRes,true,'id')
+        return result,count,'select success'
+    else
+        return false,count,'this data is not found'
+    end
+end
+
+-- 查询文件内容复数_模糊查询
+function getBaseInfo_ununique_dim( filename,param,dirPath)
+    local selectRes = {} --查询结果
+    local count = 0 --查询文件个数
+    if not filename then
+        log.error('func:getBaseInfo','filename not fount')
+        return false,count,'filename not fount'
+    end
+    if not dirPath then
+        log.error('func:getBaseInfo','dirPath not fount')
+        return false,count,'dirPath not fount'
+    end
+    --获取所有该文件及副本文件
+    local files,desc = getAllFiles(dirPath,filename)
+    local filevals = nil --文件内容
+    if not files then
+        return false,count,desc
+    end
+    for i,file in pairs(files) do
+        local path = dirPath..'/'..file
+        local filehandle = io.open(path, "r") -- 第一个参数是文件名,第二个是打开方式,'r'读模式,'w'写模式,对数据进行覆盖,'a'附加模式,'b'加在模式后面表示以二进制形式打开
+        if not filehandle then -- 判断文件是否存在
+            break --不存在 跳过 查询下个文件
+        end
+        fileval = filehandle:read("*all") -- 读出文件内容
+        -- print(fileval)
+        if not fileval then
+                break --空文件 跳过读取下一个文件
+        end
+        local filevaltable = split(fileval,delimiter)
+        local table_length = table_leng(filevaltable)
+        if table_length <= 1 then
+            break --无'-'标识符 跳过读取下一个文件
+        end
+        local isBreak = false
+
+        for a = 1,table_length-1 do
+            local val = json.decode(filevaltable[a])
+
+            if param then --有查询参数
+                local p_length = table_leng(param) --条件长度
+                local succ_cnt = 0; --比较成功个数
+                local pattern = ""
+                for p,s in pairs(param) do
+
+                    if succ_cnt > 19 then
+                        -- body
+                        break
+                    end
+
+
+                    local wholeStr = val[p]
+                    if type(val[p]) ~= "userdata" then
+                        -- body
+                        pattern = string.gsub(s, "[%[%]&=+%%%c%(%)%-%/%+]", function(c)
+                            return "%"..c
+                        end)
+                        local a,b = string.find(wholeStr,pattern) 
+                        local transMatchres = string.match(wholeStr,pattern)
+    
+                        
+                        if a and (b-a+1) == #transMatchres then
+                            succ_cnt = succ_cnt + 1
+                            table.insert(selectRes, val) 
+                        end
+                    end
+
+                end
+
+                -- if p_length == succ_cnt then --找到结果 停止继续查找下个文件
+                --     table.insert(selectRes, val) 
+                -- end
+                
+            else --无查询参数  查询所有
+                table.insert(selectRes, val)
+            end
+        end
+        count = i
+        -- if isBreak then --找到结果 停止继续查找下个文件
+        --     break;
+        -- end
+        filehandle:close() -- 关闭文件
+    end
+    -- print(table_leng(selectRes),json.encode(selectRes))
     if table_leng(selectRes) > 0 then
          --去重
         local result = table.unique(selectRes,true,'id')
@@ -466,6 +559,7 @@ function delBaseInfo(filename,id,dirPath)
         local newfileval = "" --删除后文件内容
         for a = 1,table_lenght-1 do
             local val = json.decode(filevaltable[a])
+
             if val.id ~= id then
                 data = json.encode(val)
                 if newfileval ~= "" then
@@ -501,6 +595,12 @@ function delBaseInfo(filename,id,dirPath)
         return false,count,'this data not found where id='..id
     end
 end
+
+function delOfflineCacheTemp( dirPath )
+    -- body
+    return   rtos.remove_dir(dirPath)
+end
+
 -- local res,cnt,desc = delBaseInfo('user',113,'/sdcard0/wind/12345')
 -- log.info('del result',res,cnt,desc)
 --修改基本信息
@@ -619,26 +719,3 @@ sys.taskInit(function()
 
 end)
 
-
-    -- local user = {id=112,name='小亮xxx',pwd='49BA59ABBE56E057',time=os.time()}  --password  md5加密 16位大写  123456
-    -- local res,desc= updateBaseInfo('user',user,'/sdcard0/wind/12345')
-    -- log.debug('update result',res,desc)