12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871 |
- --- 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 = ""
-
- -- log.info(str)
- if type(str) == "userdata" then
- -- body
- str = "\0"
- end
- 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 conds = table.concat(queryCondRegValue)
- local wnum = ""
- if #conds == 10 then
- wnum = getByte2AsciiStr(conds:sub(1, 10))
- end
- local result, count, desc
- if wnum ~= "" then
- -- body
- result, count, desc = getBaseInfo_ununique_dim("Wind", {number=wnum}, "/sdcard0/common")
- else
- result, count, desc = getBaseInfo_ununique_dim("Wind", nil, "/sdcard0/common")
- end
- 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 200
- print("aaaaaaaaaaaa")
- if not result then
- --无全风场列表显示上次作业风场
- -- body
- print("bbbbbbbbbbb")
- result = getBaseInfo("Wind", {number=lastWorkField}, "/sdcard0/common")
- else
- if gpsTime == 0 or gpsTime == "0" or wnum ~= "" then
- --有风场列表,但GPS未定位成功过显示上次作业风场
- -- body
- table.sort(result, function(l,t)
- return l.number < t.number
- 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, json.encode(v))
- -- if dist < fieldDisplayRadius then
- -- -- body
- -- -- log.info("cicle",v.lat)
- -- v.dist = dist
- -- table.insert(fitWindTable, v)
- -- end
- -- end
- fitWindTable = result
- 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")
- table.sort(fitWindTable, function(l,t)
- return l.dist < t.dist
- end)
- 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("namehex:",v.nameHex, "numberhex:",v.numberHex, "dist:", v.dist, "number", v.number, "name:", v.name)
- 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)
- if #ucs2Bytes > 20 then
- -- body
- ucs2Bytes = ucs2Bytes:sub(1, 20)
- end
- 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")
- local result, count, desc = getBaseInfo_ununique("WorkingPosition", { Parts=Parts }, "/sdcard0/common")
- -- log.info("ddddddddddddddddddddddd--------",json.encode(result))
- 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)
- if #ucs2Bytes > 40 then
- -- body
- ucs2Bytes = ucs2Bytes:sub(1, 40)
- end
- 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/UploadWorkRecordFA",["data"]=upTable,["id"]=msgid}, "/sdcard0/common/temp")
- logModuel.debug_log("保存本地待上传作业记录FA, msgid:"..msgid)
- -- 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/UploadWorkRecordMA",["data"]=upTable,["id"]=msgid}, "/sdcard0/common/temp")
- logModuel.debug_log("保存本地待上传作业记录MA, msgid:"..msgid)
- -- 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
- }
- 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
- 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 msgid = devTool.guid()
- 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
- msgid = msgid,
- netWorkSaveTime = os.time(),
- id = msgid
- }
- -- 待上传 upTable 全部
- local result = saveBaseInfo("wait2upload", {["topic"]="SHEGCL/IntelligenTool/UploadWorkRecordSimple",["data"]=upTable,["id"]=msgid}, "/sdcard0/common/temp")
-
- queryFlagReg["006e"] = "0000"
- if not result then
- -- body
- queryFlagResReg[respRegAddress] = "0002"
- logModuel.debug_log("上传维护模式操作(仅次数)记录--写本地工作记录文件失败, desc:"..desc)
- else
- logModuel.debug_log("保存本地待上传作业记录SA, msgid:"..msgid)
- 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)
- if #ucs2Bytes > 40 then
- -- body
- ucs2Bytes = ucs2Bytes:sub(1, 40)
- end
-
- 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)
- if #wname > 40 then
- -- body
- wname = wname:sub(1, 40)
- end
- if #parts > 20 then
- -- body
- parts = parts:sub(1, 20)
- end
- if #work > 40 then
- -- body
- work = work:sub(1, 40)
- end
- 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(6000)
- 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)
|