Translations:Modbus RTU в виде custom protocol/10/en
Материал из WebHMI Wiki
-- SENDING REQUEST
if not (sendBytes(request)) then DEBUG("Can't send bytes") return false end -- RECEIVING REPLY --- local respHead, respData, respCRC = {}, {}, {} -- read Header with length respHead = readBytes(3) if (respHead == false) then DEBUG("Can't read response") return false end if (respHead[1] ~= request[1]) then ERROR("Wrong slaveID in response!") return false end if (respHead[2] ~= request[2]) then if (respHead[2] >= 0x81) then ERROR("EXCEPTION: "..EXCEPTIONS[bit.band(respHead[2], 0x0F)]) readBytes(2) -- read till the end else ERROR("Wrong Func Code in response") end return false; end local resp_Lentgh = respHead[3]; respData = readBytes(resp_Lentgh) if (respData == false) then DEBUG("Can't read response"); return false; end -- check CRC in reply local tmpResponseTab = {} for i,v in ipairs(respHead) do table.insert(tmpResponseTab, v) end for i,v in ipairs(respData) do table.insert(tmpResponseTab, v) end crc = GetCRC(tmpResponseTab, 0) crcLo = GetLoByte(crc) crcHi = GetHiByte(crc) respCRC = readBytes(2) if (respCRC == false) then DEBUG("Can't read response"); return false; end if (respCRC[1] ~= crcLo) or (respCRC[2] ~= crcHi) then DEBUG("Wrong CRC in reply! "..string.format("%X", crcLo).." "..string.format("%X", crcHi)); return false; end if (device.name == "DI") or (device.name == "C") then if (resp_Lentgh ~= count) then ERROR("Wrong length in response"); return false; end else if (resp_Lentgh ~= count*2) then ERROR("Wrong length in response"); return false; end end -- RETURN DATA -- return GetHexFromTable(respData)