1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819 |
- --- modbus模块功能
- -- @module modbus
- -- @author Dozingfiretruck
- -- @license MIT
- -- @copyright openLuat
- -- @release 2020.12.17
- module(...,package.seeall)
- require"utils"
- require"common"
- require"pm"
- require"pins"
- -- require "sdModuel"
- -- require "logModuel"
- --保持系统处于唤醒状态,此处只是为了测试需要,所以此模块没有地方调用pm.sleep("testUart")休眠,不会进入低功耗休眠状态
- --在开发“要求功耗低”的项目时,一定要想办法保证pm.wake("modbusrtu")后,在不需要串口时调用pm.sleep("testUart")
- local uart_id = 1
- -- local uart_baud = 9600
- local uart_baud = 115200
- -- pmd.ldoset(2,pmd.LDO_VMMC)
- local BAT_ADC_ID = 2
- adc.open(BAT_ADC_ID)
- local queryCondReg = nil --1000
- local queryCondRegValue = {} --
- local queryFlagReg = {}
- queryFlagReg["0064"] = "0000"
- queryFlagReg["0065"] = "0000"
- queryFlagReg["0066"] = "0000"
- queryFlagReg["0067"] = "0000"
- queryFlagReg["0068"] = "0000"
- queryFlagReg["0069"] = "0000"
- queryFlagReg["006a"] = "0000"
- queryFlagReg["006b"] = "0000"
- queryFlagReg["006c"] = "0000"
- queryFlagReg["006d"] = "0000"
- queryFlagReg["006e"] = "0000"
- queryFlagReg["006f"] = "0000"
- queryFlagReg["0070"] = "0000"
- local queryFlagResReg = {} -- 200
- queryFlagResReg["00c8"] = "0000"
- queryFlagResReg["00c9"] = "0000"
- queryFlagResReg["00ca"] = "0000"
- queryFlagResReg["00cb"] = "0000"
- queryFlagResReg["00cc"] = "0000"
- queryFlagResReg["00cd"] = "0000"
- queryFlagResReg["00ce"] = "0000"
- queryFlagResReg["00cf"] = "0000"
- queryFlagResReg["00d0"] = "0000"
- queryFlagResReg["00d1"] = "0000"
- 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)
- local leng=0
- for k, v in pairs(t) do
- leng=leng+1
- end
- return leng;
- end
- -- 将sting字节流转为字符串57 53 2D 54 2E 36 2D 30 35 31 00 34
- function getByte2AsciiStr( data )
- -- body
- local str = ""
- for i=1,#data, 2 do
- if string.char(data:byte(i)) == "\0" then
- -- body
- if string.char(data:byte(i+1)) == "\0" then
- -- body
- else
- str = str..string.char(data:byte(i+1))
- end
- break
- end
- str = str.. string.char(data:byte(i+1)) .. string.char(data:byte(i)) -- 011003E8000A14727731653332353437363938003700000000000000003774
- end
- return str
- end
- -- 将utf8str转16进制字符串,按宽度补0
- 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
- hexStr = hexStr .. string.format("%02x", string.byte("\0")) ..string.format("%02x", str:byte(i))
- break
- end
- hexStr = hexStr .. string.format("%02x", str:byte(i+1)) .. string.format("%02x", str:byte(i))
- end
-
- if (width - #str) > 0 then
- -- body
- local clen = 0
- if not IsOuNumber(#str) then
- clen = width - #str -1
- else
- clen = width - #str
- end
-
- for i=1,clen do
-
- hexStr = hexStr .. string.format("%02x", 0)
- end
- end
- return hexStr
- end
- -- 获取格式化日期时间
- function getDateTimeStr( )
- local tm = os.date("*t")
- return string.format("%04d%02d%02d%02d%02d%02d", tm.year, tm.month, tm.day, tm.hour, tm.min, tm.sec)
- end
- function IsOuNumber(num)
- local num1,num2=math.modf(num/2)--返回整数和小数部分
- if(num2==0)then
- return true
- else
- return false
- end
- end
- function ucs2deleteZero( ucs2Byte )
- -- body
- local ustr = ""
- for i=1,#ucs2Byte, 2 do
- local ascii1, ascii2 = ucs2Byte:byte(i),ucs2Byte:byte(i+1)
- if ascii1 == 0 and ascii2 ==0 then
- -- body
- break
- else
- ustr = ustr..common.ucs2beToUtf8(ucs2Byte:sub(i, i+1))
- end
- end
- return ustr
- end
- local function handlePumbHeart( startAddress, regNumber, data )
- local startAddDec = tonumber(startAddress, 16)
- local regNumberDec = tonumber(regNumber, 16)
- -- 01 10 0191 0001 02 0001 6bd1
- for i=1, 2*regNumberDec , 2 do
- local value = tonumber(data:sub(i,i+1):toHex(), 16)
- if startAddDec == 401 then
- -- body
- -- log.info("pumbStatus", startAddDec, value)
- if nvm.get("pumbStatus") ~= value then
- -- body
- nvm.set("pumbStatus", value)
- end
- end
- if startAddDec == 410 then
- -- body
- -- log.info("hydOil", startAddDec, value)
- if nvm.get("hydOil") ~= value then
- -- body
- nvm.set("hydOil", value)
- end
-
- end
- if startAddDec == 411 then
- -- body
- -- log.info("scaleValve", startAddDec, value)
- if nvm.get("scaleValve") ~= value then
- -- body
- nvm.set("scaleValve", value)
- end
- end
- if startAddDec == 412 then
- -- body
- -- log.info("dianci", startAddDec, value)
- if nvm.get("elecValve") ~= value then
- -- body
- 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
- end
- local function mobBussErrSend (slaveAdd, functionCode, errcode )
- -- body
- local errRespData, errRespCrc
- errRespData = (slaveAdd..functionCode..errcode):fromHex()
- errRespCrc = pack.pack('<h', crypto.crc16("MODBUS",errRespData))
-
- logModuel.debug_log("send 485:"..(errRespData..errRespCrc):toHex() )
- uart.write(uart_id, errRespData..errRespCrc)
- end
- -- 处理接收到的数据
- local function proc( data )
- -- body 010600CF00017835
- orginDataHex =string.toHex(data)
- if not orginDataHex then
- -- body
- return false
- end
- if #data < 8 then
- -- body
- return false
- end
- if not crc16Compare(orginDataHex) then
- -- body
- logModuel.debug_log("data:"..orginDataHex..",CRC check failed!")
- return false
- end
- local slaveAdd = string.format("%02x",data:byte(1))
- local functionCode = string.format("%02x",data:byte(2))
- local startRegAddress = string.format("%02x",data:byte(3)) ..string.format("%02x",data:byte(4))
- local multiRespData = ""
- local respCrc = ""
- local errFunctionCode = ""
- if not slaveAdd or not functionCode then
- -- body
- logModuel.debug_log("data:"..orginDataHex..",没有从机码和功能码!")
- return false
- end
- if functionCode ~= "06" and functionCode ~= "10" and functionCode ~= "03" then
- -- body
- if not tonumber(functionCode) then
- -- body
- errFunctionCode = functionCode
- else
- errFunctionCode = tonumber(functionCode) + 80
- end
- multiRespData = (slaveAdd..errFunctionCode.."01"):fromHex()
- respCrc = pack.pack('<h', crypto.crc16("MODBUS",multiRespData))
- uart.write(uart_id, multiRespData..respCrc)
- logModuel.debug_log("data:"..orginDataHex..",非 03, 06, 10功能码,不允许操作!")
- return false
- end
- local regAddHex = tonumber(startRegAddress, 16)
- if functionCode == "06" then
- -- body
- local value = string.format("%02x",data:byte(5)).. string.format("%02x",data:byte(6))
- if not value then
- -- body
- mobBussErrSend(slaveAdd, "86", "03")
- return false
- end
- if regAddHex >= 100 and regAddHex < 200 then
- -- body
- queryFlagReg[startRegAddress] = "0001"
- setQueryFlagData(startRegAddress, data)
- end
- if regAddHex >= 200 and regAddHex < 300 then
- mobBussErrSend(slaveAdd, "86", "01")
- return false
- end
- if regAddHex >= 1400 then
- mobBussErrSend(slaveAdd, "86", "01")
- return false
- end
- multiRespData = (slaveAdd..functionCode..startRegAddress..value):fromHex()
- respCrc = pack.pack('<h', crypto.crc16("MODBUS",multiRespData))
- uart.write(uart_id, multiRespData..respCrc)
- end
-
- if functionCode == "10" then
- -- body
- if #data < 11 then
- -- body
- mobBussErrSend(slaveAdd, "90", "01")
- return false
- end
-
- local regNumber = string.format("%02x",data:byte(5)) .. string.format("%02x",data:byte(6))
- if regAddHex >= 1000 and regAddHex < 1400 then
- -- body 01 10 03e8 0001 02 0000 aaaa
- setQueryCondRegData(startRegAddress, data)
- end
- if regAddHex >= 100 and regAddHex < 200 then
- -- body
- if regAddHex > 212 then
- -- body
- mobBussErrSend(slaveAdd, "90", "01")
- return false
- end
- queryFlagReg[startRegAddress] = "0001"
- setQueryFlagData(startRegAddress, data)
- end
- if regAddHex >= 200 and regAddHex < 300 then
- -- body
- mobBussErrSend(slaveAdd, "90", "01")
- return false
- end
-
- if regAddHex >= 400 and regAddHex < 500 then --泵心跳相关
- -- queryFlagResReg[startRegAddress] = data
- local byteCount = string.format("%02x",data:byte(7))
- handlePumbHeart(startRegAddress, regNumber,data:sub(8, tonumber(byteCount, 16)+7))
- end
- if regAddHex >= 1400 then
- mobBussErrSend(slaveAdd, "90", "01")
- return false
- end
-
- multiRespData = (slaveAdd..functionCode..startRegAddress..regNumber):fromHex()
- respCrc = pack.pack('<h', crypto.crc16("MODBUS",multiRespData))
- logModuel.debug_log("send 485:"..(multiRespData..respCrc):toHex())
- uart.write(uart_id, multiRespData..respCrc)
- end
- if functionCode == "03" then
- -- body
- local regNumber = string.format("%02x",data:byte(5)) .. string.format("%02x",data:byte(6))
- local respValue = ""
- log.info("regAddHex:", regAddHex, "startAdd:",startRegAddress)
- if regAddHex >= 100 and regAddHex < 200 then
- -- body
- respValue = queryFlagReg[startRegAddress]
- if not respValue then
- -- body
- mobBussErrSend(slaveAdd, "83", "01")
- return false
- end
- byteCount = "02"
- 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
- if regAddHex >= 200 and regAddHex < 300 then
- -- body
-
- respValue = queryFlagResReg[startRegAddress]
- if not respValue then
- -- body
- mobBussErrSend(slaveAdd, "83", "01")
- return false
- end
- byteCount = "02"
- 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
- if regAddHex >= 1400 then
- -- body
- if tonumber(regNumber, 16) == 1 then
- -- body
- log.info("startRegAddress:",startRegAddress, "value:", queryRespData[startRegAddress])
- respValue = queryRespData[startRegAddress]
- if not respValue then
- -- body
- mobBussErrSend(slaveAdd, "83", "01")
- return false
- end
- else
- local regNumberDec,startRegAddressDec = tonumber(regNumber,16), tonumber(startRegAddress,16)
- if regNumberDec > table_leng(queryRespData) then
- -- body
- logModuel.debug_log("read regNumber > store queryRespData table length!")
- mobBussErrSend(slaveAdd, "83", "03")
- return false
- end
- for i=startRegAddressDec, (startRegAddressDec + regNumberDec-1) do
- local regHex = string.format("%04x", i)
- if queryRespData[regHex] then
- -- body
- respValue = respValue..queryRespData[regHex]
- else
- logModuel.debug_log("for in regNumber > store queryRespData table max regNumber!")
- 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)
- return
- 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
- 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
- -- 工具可以自定义
- -- 机位号
- -- 所属部件
- -- 工作位置
- -- 设置查询条件相关寄存器数据
- function setQueryCondRegData( startRegAddress, data )
- -- body
- if queryCondReg and tonumber(startRegAddress, 16) <= tonumber(queryCondReg, 16) then
- -- body
- initRegVariable()
- log.info("queryReg variable init!")
- end
- queryCondReg = startRegAddress
- local byteCount = string.format("%02x",data:byte(7))
- table.insert(queryCondRegValue, data:sub(8, tonumber(byteCount, 16)+7))
- log.info("queryCondRegValue first:", queryCondRegValue[1]:toHex() )
- end
- -- 设置查询标识寄存器数据
- function setQueryFlagData( startRegAddress, data )
- -- body
- -- queryFlagReg = string.format("%02x",data:byte(8)) .. string.format("%02x",data:byte(9))
- if startRegAddress then
- -- body
- sys.publish("pub_queryflag_reg", startRegAddress)
- end
-
- log.info("quryflag wrote done:", startRegAddress)
- end
- -- crc16校验
- function crc16Compare( wholeData )
- -- body
- -- local crc16get = string.format("%02x",wholeData:byte(-2))..string.format("%02x",wholeData:byte(-1))
- local crc16get = string.sub(wholeData, -4 )
- local dataExceptCrc =string.sub(wholeData, 1, -5 )
- log.info("dataExceptCrc :", dataExceptCrc)
- local caculateCrc = pack.pack('<h', crypto.crc16("MODBUS",dataExceptCrc:fromHex()))
- if crc16get:fromHex() ~= caculateCrc then
- -- body
- log.info("crc16 compare, crc16get =",crc16get,",caculateCrc=",string.toHex(caculateCrc) )
- return false
- end
- return true
- end
- -- 寄存器相关变量初始化
- function initRegVariable( )
- -- body
- queryCondReg = nil
- queryCondRegValue = {} --
- queryFlagReg["0064"] = "0000"
- queryFlagReg["0065"] = "0000"
- queryFlagReg["0066"] = "0000"
- queryFlagReg["0067"] = "0000"
- queryFlagReg["0068"] = "0000"
- queryFlagReg["0069"] = "0000"
- queryFlagReg["006a"] = "0000"
- queryFlagReg["006b"] = "0000"
- queryFlagReg["006c"] = "0000"
- queryFlagReg["006d"] = "0000"
- queryFlagReg["006e"] = "0000"
- queryFlagReg["006f"] = "0000"
- queryFlagReg["0070"] = "0000"
- queryFlagResReg["00c8"] = "0000"
- queryFlagResReg["00c9"] = "0000"
- queryFlagResReg["00ca"] = "0000"
- queryFlagResReg["00cb"] = "0000"
- queryFlagResReg["00cc"] = "0000"
- queryFlagResReg["00cd"] = "0000"
- queryFlagResReg["00ce"] = "0000"
- queryFlagResReg["00cf"] = "0000"
- queryFlagResReg["00d0"] = "0000"
- queryFlagResReg["00d1"] = "0000"
- queryFlagResReg["00d2"] = "0000"
- queryFlagResReg["00d3"] = "0000"
- queryFlagResReg["00d4"] = "0000" -- 1400
- queryRespData = {}
- end
- local function modbus_read()
- local cacheData = ""
- while true do
- local s = uart.read(uart_id,1)
- if s == "" then
- -- if not sys.waitUntil("UART_RECEIVE",35000/uart_baud) then
- if not sys.waitUntil("UART_RECEIVE",35000/uart_baud) then
- -- 3.5个字符的时间间隔,只是用在RTU模式下面,因为RTU模式没有开始符和结束符,
- -- 两个数据包之间只能靠时间间隔来区分,Modbus定义在不同的波特率下,间隔时间是不一样的,
- -- 所以就是3.5个字符的时间,波特率高,这个时间间隔就小,波特率低,这个时间间隔相应就大
- -- 4800 = 7.297ms
- -- 9600 = 3.646ms
- -- 19200 = 1.771ms
- -- 38400 = 0.885ms
- --uart接收数据,如果 35000/uart_baud 毫秒没有收到数据,则打印出来所有已收到的数据,清空数据缓冲区,等待下次数据接收
- --注意:
- --因为在整个GSM模块软件系统中,软件定时器的精确性无法保证,例如本demo配置的是100毫秒,在系统繁忙时,实际延时可能远远超过100毫秒,达到200毫秒、300毫秒、400毫秒等
- --设置的延时时间越短,误差越大
- if cacheData:len()>0 then
- local a,_ = string.toHex(cacheData)
- logModuel.debug_log("read 485:"..a)
- --用户逻辑处理代码
- --
- local resp = proc(cacheData)
- cacheData = ""
-
- end
- end
- else
- cacheData = cacheData..s
- end
- end
- end
- local function writeOk()
- log.info("testUart.writeOk")
- end
-
- --10 写多个寄存器
- local function writeMultiReg( slaveaddr, functionCode, startAddress, regNumber, values )
- -- body
- local byteCount = 2*regNumber
- local prefix = (string.format("%02x",slaveaddr)..string.format("%02x",functionCode)..string.format("%04x",startAddress)..string.format("%04x",regNumber)..string.format("%04x",byteCount)):fromHex()
- local valueHex = ""
- for i=1,math.ceil(values:len()/4) do
- local t = "0x"..string.sub(values, (i-1)*4+1, 4*i)
- valueHex = valueHex.. string.format("%04x", t)
- end
-
- local data = prefix..valueHex:fromHex()
- local modbus_crc_data= pack.pack('<h', crypto.crc16("MODBUS",data))
- local data_tx = data..modbus_crc_data
- log.info("uart2Task.write",data_tx)
- uart.write(uart_id,data_tx)
- end
- --06 写单个寄存器
- local function writeSingleReg( slaveaddr, functionCode, regAddress, value )
- -- body
- local data = (string.format("%02x",slaveaddr)..string.format("%02x",functionCode)..string.format("%04x",regAddress)..string.format("%04x",value)):fromHex()
- local modbus_crc_data= pack.pack('<h', crypto.crc16("MODBUS",data))
- local data_tx = data..modbus_crc_data
- log.info("uart2Task.write",data_tx)
- uart.write(uart_id,data_tx)
- end
- -- 查询扳手信息并写入结果寄存器
- local function query0064Res()
- -- body
- respRegAddress = "00c8"
- local conds = table.concat(queryCondRegValue)
- if #conds < 20 then
- -- body
- queryFlagReg["0064"] = "0000"
- return false
- end
- local number = getByte2AsciiStr(conds:sub(1, 20))--查询条件
- local result, count, desc = getBaseInfo("Wrench", {number=number} , "/sdcard0/common")
- queryFlagReg["0064"] = "0000"
- queryCondRegValue = {}--清空查询条件
- if not result then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- log.info("查询扳手信息失败, desc:", desc)
- logModuel.debug_log("查询扳手信息失败,count:"..count..",desc:"..desc..",querycond_number:"..number)
- return false
- end
- local singleRes = result[1]
- local minnj = pack.pack('>I', singleRes.mint)
- local maxnj = pack.pack('>I', singleRes.maxt)
- local fbl = pack.pack('>I', singleRes.angres)
- local resT = {
- string.format("%04x", singleRes.qualified),
- string.format("%04x", singleRes.type),
- string.format("%04x", singleRes.minp),
- string.format("%04x", singleRes.maxp),
- minnj:sub(3, 4):toHex() .. minnj:sub(1, 2):toHex(),
- maxnj:sub(3, 4):toHex() .. maxnj:sub(1, 2):toHex(),
- fbl:sub(3, 4):toHex() .. fbl:sub(1, 2):toHex(),
- 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
- local regHex = string.format("%04x", i)
- queryRespData[regHex] = string.sub(res64Hex, j, j+3)
- j = j+4
- end
- log.info("queryRespData lenth:", table_leng(queryRespData))
- queryFlagResReg[respRegAddress] = "0001"
- end
- -- 查询法兰历史紧固数据并写入结果寄存器
- local function query0065Res()
- -- body
- respRegAddress = "00c9"
- local conds = table.concat(queryCondRegValue)
- if #conds < 90 then
- -- body
- queryFlagReg["0065"] = "0000"
- return false
- end
- local cond = {
- wnum = getByte2AsciiStr(conds:sub(1, 10)),
- fnum = getByte2AsciiStr(conds:sub(11, 30)),
- fmodel = getByte2AsciiStr(conds:sub(31, 50)),
- parts = ucs2deleteZero(conds:sub(51, 70)),
- work = ucs2deleteZero(conds:sub(71, 110))
- }
- log.info("wnum:", cond.wnum, "wnum_hex:", conds:sub(1, 10):toHex())
- log.info("record cond:",json.encode(cond))
- local result, count, desc = getBaseInfo("WorkRecord", cond , "/sdcard0/"..cond.wnum .."/".. cond.fnum)
- queryFlagReg["0065"] = "0000"
- queryCondRegValue = {}--清空查询条件
- if not result then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("法兰历史紧固记录查询失败,count:"..count..",desc:"..desc..",querycond:"..json.encode(cond))
- return false
- end
-
- -- WorkRecord
- local res = result[1]
- local regValueHex = ""
- local total = string.format("%04x", res.bnum)
- local lsnj = pack.pack('>I', res.torque)
-
- regValueHex = total.. lsnj:sub(3, 4):toHex() .. lsnj:sub(1, 2):toHex()
- -- queryRespData["057c"] = pack.pack('>I', 100)
- -- queryRespData["057d"] = pack.pack('>I', 500)
- local j = 1
- for i=1400,1402 do
- local regHex = string.format("%04x", i)
- queryRespData[regHex] = regValueHex:sub(j, j+3)
- j = j+4
- end
- queryFlagResReg[respRegAddress] = "0001"
- end
- -- 用户查询认证
- local function query0066Res()
- -- body
- respRegAddress = "00ca"
- -- "0001" 用户名错误 "0002" 密码错误
- -- "000a" 操作员 "000b" 管理员
- local conds = table.concat(queryCondRegValue)
- if #conds < 40 then
- -- body
- queryFlagReg["0066"] = "0000"
- return false
- end
- local username = getByte2AsciiStr(conds:sub(1, 20))--查询条件--用户名
- local password = getByte2AsciiStr(conds:sub(21, 40))--查询条件--密码
- local ures, count, desc = getBaseInfo("Users", {name=username} , "/sdcard0/common")
- queryFlagReg["0066"] = "0000"
- queryCondRegValue = {}--清空查询条件
- if not ures then
- -- body
- logModuel.debug_log("用户名查询失败,count:"..count..",desc:"..desc..",querycond:"..json.encode({name=username}))
- queryFlagResReg[respRegAddress] = "0001"
- return false
- end
- local result, rcount, rdesc = getBaseInfo("Users", {name=username, pwd=password} , "/sdcard0/common")
- if not result then
- -- body
- logModuel.debug_log("用户查询认证失败,密码不匹配,count:"..rcount..",desc:"..rdesc..",querycond:"..json.encode({name=username, pwd=password}))
- queryFlagResReg[respRegAddress] = "0002"
- return false
- end
- queryFlagResReg[respRegAddress] = string.format("%04x", result[1].perm)
- end
- -- 查询风场列表并写入结果寄存器
- local function query0067Res()
- -- body
- respRegAddress = "00cb"
- local result, count, desc = getBaseInfo_ununique("Wind", nil, "/sdcard0/common")
- queryFlagReg["0067"] = "0000"
- queryCondRegValue = {}--清空查询条件
- local lastWorkField = nvm.get("lastWorkField")
- if not result and lastWorkField == "" then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("查询风场列表失败,count:"..count..",desc:"..desc)
- return false
- end
- local fitWindTable, gpsLng, gpsLat, gpsTime = {}, nvm.get("gpsLng"), nvm.get("gpsLat"), nvm.get("gpsTime")
-
- local fieldDisplayRadius = nvm.get("fieldDisplayRadius") or 20
- print("aaaaaaaaaaaa")
- log.info("lastWorkField",lastWorkField)
- if not result then
- --无全风场列表显示上次作业风场
- -- body
- print("bbbbbbbbbbb")
- result = getBaseInfo("Wind", {number=lastWorkField}, "/sdcard0/common")
- else
- if gpsTime == 0 or gpsTime == "0" then
- --有风场列表,但GPS未定位成功过显示上次作业风场
- -- body
- print("cccccccccccccc")
- if lastWorkField ~= "" then
- -- body
- print("dddddddddddddd")
- result = getBaseInfo("Wind", {number=lastWorkField}, "/sdcard0/common")
- end
-
- else
- print("eeeeeeeeeeeeeee")
- for k,v in pairs(result) do
- --过滤风场列表中不在方圆20Km内的风场
- local dist = devTool.getDistance( v.lat, v.lon, gpsLat, gpsLng)
- log.info("dist:",dist)
- if dist < fieldDisplayRadius then
- -- body
- -- log.info("cicle",v.lat)
- table.insert(fitWindTable, v)
- end
- end
- if table_leng(fitWindTable) == 0 then
- --若过滤后无风场则显示上次作业风场
- -- body
- print("fffffffffffffffff")
- if lastWorkField ~= "" then
- -- body
- print("ggggggggggggggggggg")
- result = getBaseInfo("Wind", {number=lastWorkField}, "/sdcard0/common")
- end
- else
- print("hhhhhhhhhhhhhhhhhhhhhhhh")
- result = fitWindTable
- log.info("fittable:", json.encode(fitWindTable))
- end
- end
- end
- print("iiiiiiiiiiiiiiiiiii")
- if not result then
- -- body
- print("jjjjjjjjjjjjjjj")
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("查询风场列表失败过滤逻辑之后")
- return false
- end
-
-
- queryRespData["0578"] = string.format("%04x", table_leng(result))
- local regValueHex = ""
- 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)
- regValueHex = regValueHex..numberHex..nameHex
- end
- local j = 1
- for i=1410, 1409 + 25*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
- -- 查询风机型号列表并写入结果寄存器
- local function query0068Res()
- -- body
- respRegAddress = "00cc"
- local conds = table.concat(queryCondRegValue)
- if #conds < 10 then
- -- body
- queryFlagReg["0068"] = "0000"
- return false
- end
- local wnum = getByte2AsciiStr(conds:sub(1, 10)) --查询条件
- local result, count, desc = getBaseInfo_ununique("FanModel", {wnum=wnum} , "/sdcard0/"..wnum)
-
- queryFlagReg["0068"] = "0000"
- queryCondRegValue = {}--清空查询条件
- if not result then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("查询风机型号列表失败,count:"..count..",desc:"..desc..",querycond_wnum:"..wnum)
- return false
- end
- queryRespData["0578"] = string.format("%04x", table_leng(result))
- local regHexValue = ""
- for k, v in pairs(result) do
- regHexValue = regHexValue .. getAscii2StringHexBe(v.model, 20)
- end
- local j = 1
- for i=1410,1409 + table_leng(result) * 10 do
- local regHex = string.format("%04x", i)
- queryRespData[regHex] = string.sub(regHexValue, j, j+3)
- j = j+4
- end
- queryFlagResReg[respRegAddress] = "0001"
- end
- -- 查询风机机位号列表并写入结果寄存器
- local function query0069Res()
- -- body
- respRegAddress = "00cd"
- local conds = table.concat(queryCondRegValue)
- if #conds < 10 then
- -- body
- queryFlagReg["0069"] = "0000"
- return false
- end
- local wnum = getByte2AsciiStr(conds:sub(1, 10)) --查询条件
- -- local result, count, desc = getBaseInfo("Fan", {wnum=wnum} , "/sdcard0/"..wnum)
- local result, count, desc = getBaseInfo_ununique("Fan", {wnum=wnum} , "/sdcard0/"..wnum)
- queryFlagReg["0069"] = "0000"
- queryCondRegValue = {}--清空查询条件
- if not result then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("查询机位列表失败,count:"..count..",desc:"..desc..",querycond_number:"..wnum)
- return false
- end
- queryRespData["0578"] = string.format("%04x", table_leng(result))
- local regValueHex = ""
- for k,v in pairs(result) do
- local number = v.number
- if type(number) =="number" then
- -- body
- number = tostring(number)
- end
- local numberHex = getAscii2StringHexBe(number, 20)
- regValueHex = regValueHex..numberHex
- 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
- -- 查询部件列表并写入结果寄存器
- local function query006aRes()
- -- body
- respRegAddress = "00ce"
- local result, count, desc = getBaseInfo_ununique("WorkingParts", nil, "/sdcard0/common")
- queryFlagReg["006a"] = "0000"
- queryCondRegValue = {}--清空查询条件
- if not result then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("查询部件列表失败,count:"..count..",desc:"..desc)
- return false
- end
- -- local result = {
- -- {id=123, name="测试部件1"},
- -- {id=124, name="测试部件2"},
- -- {id=125, name="测试部件3"}
- -- }
- queryRespData["0578"] = string.format("%04x", table_leng(result))
- local regValueHex = ""
- for k,v in pairs(result) do
- local ucs2Bytes = common.utf8ToUcs2be(v.name)
- local nameHex = ucs2Bytes:toHex()..getAscii2StringHexBe("\0", 20-#ucs2Bytes)
- regValueHex = regValueHex..nameHex
- 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
- -- 查询工作位置并写入结果寄存器
- local function query006bRes()
- respRegAddress = "00cf"
- -- query body
- local conds = table.concat(queryCondRegValue)
- if #conds < 40 then
- -- body
- queryFlagReg["006b"] = "0000"
- return false
- end
- local fmdel = getByte2AsciiStr(conds:sub(1, 20))
- local ucs2Byte = conds:sub(21, 40)
- local Parts = ucs2deleteZero(ucs2Byte)
- local result, count, desc = getBaseInfo_ununique("WorkingPosition", { fmodel=fmdel, Parts=Parts }, "/sdcard0/common")
- queryFlagReg["006b"] = "0000"
- 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
- queryRespData["0578"] = string.format("%04x", table_leng(result))
-
- local regValueHex = ""
- for k,v in pairs(result) do
- local ucs2Bytes = common.utf8ToUcs2be(v.name)
- local nameHex = ucs2Bytes:toHex()..getAscii2StringHexBe("\0", 40-#ucs2Bytes)
- regValueHex = regValueHex..nameHex
- end
- local j = 1
- for i=1410, 1409 + 20*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
- -- 查询自定义的3各文件中是否存在,不存在则新增一个
- local function queryCustomAndAdd( fanNumber, part, workPos , pt )
- -- body
- local fanExist = getBaseInfo("Fan", {wnmu=pt.WindFieldNumber, number=fanNumber,model=pt.Model}, "/sdcard0/"..pt.WindFieldNumber)
- if not fanExist then
- -- body
- saveBaseInfo("Fan",{id=0,wnmu=pt.WindFieldNumber, number=fanNumber,model=pt.Model}, "/sdcard0/"..pt.WindFieldNumber)
- end
- local partExist = getBaseInfo("WorkingParts", {name=part}, "/sdcard0/common")
- if not partExist then
- -- body
- saveBaseInfo("WorkingParts",{id=0,name=part}, "/sdcard0/common")
- end
- local workPosExist = getBaseInfo("WorkingPosition", {Parts=part,fmodel=pt.Model, name=workPos}, "/sdcard0/common")
- if not workPosExist then
- -- body
- saveBaseInfo("WorkingPosition",{id=0,Parts=part,fmodel=pt.Model, name=workPos}, "/sdcard0/common")
- end
- end
- -- 上传紧固模式操作记录
- local function query006cRes( )
- respRegAddress = "00d0"
- local conds = table.concat(queryCondRegValue)
- if #conds < 180 then
- -- body
- queryFlagReg["006c"] = "0000"
- return false
- end
- local msgid = devTool.guid()
- local upTable = {
- Username =getByte2AsciiStr(conds:sub(1, 20)), --用户名 string
- WrenchNumber = getByte2AsciiStr(conds:sub(21, 40)), --扳手编号 string
- WindFieldNumber = getByte2AsciiStr(conds:sub(41, 50)), --风场编号 string
- TurbineNumber = getByte2AsciiStr(conds:sub(51, 70)), --机位号 string 自定义
- Model = getByte2AsciiStr(conds:sub(71, 90)), --风机型号 string
- -- PartNumber = common.ucs2beToUtf8(conds:sub(91, 110)), --部件号 Unicode 自定义
- PartNumber = ucs2deleteZero(conds:sub(91, 110)), --部件号 Unicode 自定义
- -- WorkPos = common.ucs2beToUtf8(conds:sub(111, 130)), --工作位置 Unicode 自定义
- WorkPos = ucs2deleteZero(conds:sub(111, 150)), --工作位置 Unicode 自定义
- BoltModel = getByte2AsciiStr(conds:sub(151, 160)), --螺栓型号 string
- BoltTotal = tonumber(conds:sub(161, 162):toHex(), 16), --螺栓总数 u16
- BoltNumber = tonumber(conds:sub(163, 164):toHex(), 16), --当前螺栓编号 u16
- SetTorque = tonumber(conds:sub(167,168):toHex()..conds:sub(165,166):toHex(), 16), --设定扭矩Nm u32
- FasteningTorque = tonumber(conds:sub(171,172):toHex()..conds:sub(169,170):toHex(), 16), --紧固扭矩Nm u32
- 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
- netWorkSaveTime = os.time(),
- msgid = msgid,
- id = msgid
- }
- -- 查询自定义的3字段是否存在,不存在则新增一个
- queryCustomAndAdd(upTable.TurbineNumber, upTable.PartNumber, upTable.WorkPos, {Model=upTable.Model, WindFieldNumber = upTable.WindFieldNumber})
- -- 待上传 upTable 全部
- -- 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 = {
- id = upTable.WindFieldNumber..upTable.TurbineNumber..upTable.Model..upTable.PartNumber..upTable.WorkPos,
- wnum = upTable.WindFieldNumber,
- fnum = upTable.TurbineNumber,
- fmodel = upTable.Model,
- parts = upTable.PartNumber,
- work = upTable.WorkPos,
- bnum = upTable.BoltTotal,
- torque = upTable.FasteningTorque
- }
-
- log.info("local record", json.encode(localRecord))
- local result,count, desc = updateBaseInfo("WorkRecord", localRecord, "/sdcard0/"..localRecord.wnum .."/".. localRecord.fnum)
- if not result or desc:sub(1, 29) == "this data not found where id=" then
- -- body
- result, desc = saveBaseInfo("WorkRecord", localRecord, "/sdcard0/"..localRecord.wnum .."/".. localRecord.fnum )
- end
- log.info("local result", result)
- queryFlagReg["006c"] = "0000"
- if not result then
- -- body
- logModuel.debug_log("上传紧固模式操作记录--写本地工作记录文件失败, desc:"..desc)
- queryFlagResReg[respRegAddress] = "0002"
- else
- nvm.set("lastWorkField", localRecord.wnum)
- queryFlagResReg[respRegAddress] = "0001" --结果置1表示操作成功
- end
- end
- -- 上传维护模式操作记录
- local function query006dRes()
- respRegAddress = "00d1"
-
- local conds = table.concat(queryCondRegValue)
- if #conds < 162 then
- -- body
- 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
- WindFieldNumber = getByte2AsciiStr(conds:sub(41, 50)), --风场编号 string
- TurbineNumber = getByte2AsciiStr(conds:sub(51, 70)), --机位号 string 自定义
- Model = getByte2AsciiStr(conds:sub(71, 90)), --风机型号 string
- -- PartNumber = common.ucs2beToUtf8(conds:sub(91, 110)), --部件号 Unicode 自定义
- PartNumber = ucs2deleteZero(conds:sub(91, 110)), --部件号 Unicode 自定义
- -- WorkPos = common.ucs2beToUtf8(conds:sub(111, 130)), --工作位置 Unicode 自定义
- WorkPos = ucs2deleteZero(conds:sub(111, 150)), --工作位置 Unicode 自定义
- BoltModel = getByte2AsciiStr(conds:sub(151, 160)), --螺栓型号 string
- BoltTotal = tonumber(conds:sub(161, 162):toHex(), 16), --螺栓总数 u16
- BoltNumber = tonumber(conds:sub(163, 164):toHex(), 16), --当前螺栓编号 u16
- SetTorque = tonumber(conds:sub(167,168):toHex()..conds:sub(165,166):toHex(), 16), --设定扭矩Nm u32
- FasteningTorque = tonumber(conds:sub(171,172):toHex()..conds:sub(169,170):toHex(), 16), --紧固扭矩Nm u32
- 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
- WrenchAngle = tonumber(conds:sub(181,182):toHex(), 16), --扳手转动角度 u16
- netWorkSaveTime = os.time(),
- msgid = msgid,
- id = msgid
- }
- -- 查询自定义的3字段是否存在,不存在则新增一个
- queryCustomAndAdd(upTable.TurbineNumber, upTable.PartNumber, upTable.WorkPos, {Model=upTable.Model, WindFieldNumber = upTable.WindFieldNumber})
- -- 待上传 upTable 全部
- -- 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 = {
- id = upTable.WindFieldNumber..upTable.TurbineNumber..upTable.Model..upTable.PartNumber..upTable.WorkPos,
- wnum = upTable.WindFieldNumber,
- fnum = upTable.TurbineNumber,
- fmodel = upTable.Model,
- parts = upTable.PartNumber,
- work = upTable.WorkPos,
- bnum = upTable.BoltTotal,
- torque = upTable.FasteningTorque
- }
- log.info("local record", json.encode(localRecord))
- local result,count, desc = updateBaseInfo("WorkRecord", localRecord, "/sdcard0/"..localRecord.wnum )
- if not result and desc:sub(1, 29) == "this data not found where id=" then
- -- body
- log.info("oooooooooooooooo")
- result, desc = saveBaseInfo("WorkRecord", localRecord, "/sdcard0/"..localRecord.wnum )
- end
- log.info("local result", result)
- queryFlagReg["006d"] = "0000"
- if not result then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("上传维护模式操作记录--写本地工作记录文件失败, desc:"..desc)
- else
- nvm.set("lastWorkField", localRecord.wnum)
- queryFlagResReg[respRegAddress] = "0001" --结果置1表示操作成功
- end
- end
- -- 上传维护模式操作记录
- local function query006eRes()
- respRegAddress = "00d2"
-
- local conds = table.concat(queryCondRegValue)
- if #conds < 24 then
- -- body
- queryFlagReg["006e"] = "0000"
- return false
- end
- local upTable = {
- Username =getByte2AsciiStr(conds:sub(1, 20)), --用户名 string
- SetStress = tonumber(conds:sub(21,22):toHex(), 16), --设定压力bar u16
- FasteningStress = tonumber(conds:sub(23,24):toHex(), 16) --紧固压力bar u16
- }
- -- 待上传 upTable 全部
- local result
- if socket.isReady() then
- -- body
- sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordSimple",["data"]=upTable}))
- result = true
- else
- result = saveBaseInfo(" ", {["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordSimple",["data"]=upTable}, "/sdcard0/common")
- end
- queryFlagReg["006e"] = "0000"
- if not result then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("上传维护模式操作(仅次数)记录--写本地工作记录文件失败, desc:"..desc)
- else
- queryFlagResReg[respRegAddress] = "0001" --结果置1表示操作成功
- end
- end
- -- 获取任务编号列表
- local function query006fRes()
- -- body
- respRegAddress = "00d3"
- 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
- queryRespData["0578"] = string.format("%04x", table_leng(result))
- local regValueHex = ""
- for k,v in pairs(result) do
- local pnum = getAscii2StringHexBe(v.pnum, 20)
- local ucs2Bytes = common.utf8ToUcs2be(v.info)
- local info = ucs2Bytes:toHex()..getAscii2StringHexBe("\0", 40-#ucs2Bytes)
- log.info("pnum:", pnum, "info:", info)
- regValueHex = regValueHex..pnum..info
- end
- local j = 1
- for i=1410, 1409 + 30*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
- -- 获取任务编号内容
- local function query0070Res()
- -- body
- respRegAddress = "00d4"
- queryFlagResReg[respRegAddress] = "0002"
- local conds = table.concat(queryCondRegValue)
- if #conds < 20 then
- -- body
- queryFlagReg["0070"] = "0000"
- return false
- end
- local cond = getByte2AsciiStr(conds:sub(1,20))
- local result, count, desc = getBaseInfo("WorkPlan", {pnum=cond}, "/sdcard0/common")
-
- queryFlagReg["0070"] = "0000"
- queryCondRegValue = {}--清空查询条件
- if not result then
- -- body
- logModuel.debug_log("查询任务具体详情失败,count:"..count..",desc:"..desc,",cond_pnum="..cond)
- return false
- end
- local singleRes = result[1]
- local lt = pack.pack('>I', singleRes.lt)
- local torque = pack.pack('>I', singleRes.torque)
- local wname = common.utf8ToUcs2be(singleRes.wname)
- local parts = common.utf8ToUcs2be(singleRes.parts)
- local work = common.utf8ToUcs2be(singleRes.work)
- local resT = {
- getAscii2StringHexBe(singleRes.wnum, 10),
- wname:toHex()..getAscii2StringHexBe("\0", 40-#wname),
- getAscii2StringHexBe(singleRes.fnum, 20),
- getAscii2StringHexBe(singleRes.fmodel, 20),
- parts:toHex()..getAscii2StringHexBe("\0", 20-#parts),
- work:toHex()..getAscii2StringHexBe("\0", 40-#work),
- getAscii2StringHexBe(singleRes.bm, 20),
- string.format("%04x", singleRes.bn),
- string.format("%04x", singleRes.tm),
- string.format("%04x", singleRes.bias),
- lt:sub(3, 4):toHex() .. lt:sub(1, 2):toHex(),
- torque:sub(3, 4):toHex() .. torque:sub(1, 2):toHex()
- }
- local resValueHex = table.concat(resT)
- local j = 1
-
- for i=1400,1491 do
- local regHex = string.format("%04x", i)
- queryRespData[regHex] = string.sub(resValueHex, j, j+3)
- j = j+4
- end
- 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)
- queryRespData = {}--清空之前的查询结果
-
- if regAddress == "0064" then
- -- body
- query0064Res()
- end
- if regAddress == "0065" then
- -- body
- query0065Res()
- end
- if regAddress == "0066" then
- -- body
- query0066Res()
- end
- if regAddress == "0067" then
- -- body
- query0067Res()
- end
- if regAddress == "0068" then
- -- body
- query0068Res()
- end
- if regAddress == "0069" then
- -- body
- query0069Res()
- end
- if regAddress == "006a" then
- -- body
- query006aRes()
- end
- if regAddress == "006b" then
- -- body
- query006bRes()
- end
- if regAddress == "006c" then
- -- body
- query006cRes()
- end
- if regAddress == "006d" then
- -- body
- query006dRes()
- end
- if regAddress == "006e" then
- -- body
- query006eRes()
- end
- if regAddress == "006f" then
- -- body
- query006fRes()
- end
- if regAddress == "0070" then
- -- body
- query0070Res()
- end
- if regAddress == "0071" then
- -- body
- query0071Res()
- end
- end
- local function queryByQueryflag()
- while true do
- local result, regAddress = sys.waitUntil("pub_queryflag_reg", 1000)
-
- if result then
- -- body
- queryByRegAdd(regAddress)
- end
- end
- end
- pm.wake("modbusrtu")
- --注册串口的数据发送通知函数
- uart.on(uart_id,"receive",function() sys.publish("UART_RECEIVE") end)
- uart.on(uart_id,"sent",writeOk)
- --配置并且打开串口
- -- uart.setup(uart_id,uart_baud,8,uart.PAR_NONE,uart.STOP_1)
- uart.setup(uart_id,uart_baud,8,uart.PAR_NONE,uart.STOP_1,nil,1)
- uart.set_rs485_oe(uart_id, pio.P0_19)
- --启动串口数据接收任务
- sys.taskInit(modbus_read)
- sys.taskInit(queryByQueryflag)
- function getHeartbeatContent( )
- -- body
- local gpsStr = nvm.get("gpsLng")..","..nvm.get("gpsLat")
- -- local vbatt = readAdc() or "0"
- local adcval,voltval = adc.read(BAT_ADC_ID)
- 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 Status = 0
- if powerManage.setGpio11Fnc() == 1 then
- -- body
- Status = 1
- end
- local heartBeat = {
- IMEI = misc.getImei(),
- IMSI = sim.getImsi(),
- 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,
- 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
- end
- local function checkPumbHeartbeatExtra( )
- -- body
- local pumbStatus = nvm.get("pumbStatus")
- local hydOil, hydOilThr = nvm.get("hydOil"), nvm.get("hydOilThr")
- local scaleValve, scaleValveThr = nvm.get("scaleValve"), nvm.get("scaleValveThr")
- local elecValve, elecValveThr = nvm.get("elecValve"), nvm.get("elecValveThr")
-
- local alarmType, alarmReason = "device", {}
- if pumbStatus > 2 then
- -- body
- table.insert(alarmReason, "pumb_unusual_status")
- end
- if hydOil > hydOilThr then
- -- body
- table.insert(alarmReason, "low_oil")
- end
- if scaleValve > scaleValveThr then
- -- body
- table.insert(alarmReason, "low_scale_valve")
- end
- if elecValve > elecValveThr then
- -- body
- table.insert(alarmReason, "low_elec_valve")
- end
- if table_leng(alarmReason) == 0 then
- -- body
- return
- end
- local alarmData = {
- Type = alarmType,
- Reason = alarmReason,
- Data = {pumbStatus=pumbStatus, hydOil= hydOil, scaleValve=scaleValve,elecValve=elecValve},
- Time = os.time()
- }
-
- sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/UploadAlarmInfo",["data"]=alarmData}))
- end
- 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 < lowBatThd then
- -- body
- table.insert(alarmReason, "network_bat_lower")
- end
- end
- if table_leng(alarmReason) == 0 then
- -- body
- return
- end
- local alarmData = {
- Type = alarmType,
- Reason = alarmReason,
- Data = {battery=vbatt},
- Time = os.time()
- }
- sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/UploadAlarmInfo",["data"]=alarmData}))
- end
- sdcardMouted = false
- sys.taskInit(function( )
- -- body
- local result = sys.waitUntil("IO_SDCARD_MOUTED", 10000)
- if result then
- -- body
- sdcardMouted = true
- end
- end)
- sys.timerLoopStart(checkPumbHeartbeatExtra,60000)
- local heartbeatInterval = nvm.get("heartbeatInterval") or 600
- -- 定时心跳
- sys.taskInit(function()
- sys.wait(5000)
- while true do
- if socket.isReady() then --连上网再开始运行
- -- sys.waitUntil("pub_gps_location_success_msg", 120*1000)
- local heartBeatData = getHeartbeatContent()
- log.info("pblish heartbeat msg!!!")
- sys.publish("LOCAL_PUB_MSG", json.encode({["topic"]="SHEGCL/IntelligenTool/Heart",["data"]=heartBeatData}))
-
- sys.wait(1000)
- checkNetWorkHealth(nil)
- sys.wait(heartbeatInterval *1000)
- else --没连上网别忘了延时!不然会陷入while true死循环,导致模块无法运行其他代码
- -- log.info("socket not ready")
- sys.wait(5000) --等待5秒
- end
- end
- end)
|