The use of the ESP8266 in the world of IoT

User avatar
By frank_dunn1
#15763 this is is experimental but works with codesys on rpi and simulator. function 3 and 6 works.



local crc
modadrptr = 0

holdingregs = {[0] = 0 , [1] = 0 , [2] = 0, [3] = 0 , [4] = 0}
modmsb = 0
modlsb = 0

local function initCrc()
crc = 0xffff
end

local function updCrc(byte)
crc= bit.bxor(crc, byte)
for i = 1,8 do
local j = bit.band(crc,1)
crc = bit.rshift(crc,1)
if j ~= 0 then
crc = bit.bxor(crc,0xa001)
end
end
end



local function getCrc(str)
initCrc()
for i = 1, #str do
updCrc(string.byte(str,i))

end
return crc
end


local function createHeader()
header = string.char(0,0,0,0,0,9)
end


local function func3(modadrptr)

modmsb = (bit.band(0xff,bit.rshift(holdingregs[modadrptr],8)))
modlsb = (bit.band(0xff,holdingregs[modadrptr]))
body = string.char(slaveId,3,modadrptr,modmsb,modlsb)
end

local function func6(payload)
modadrptr = string.byte(payload,10)
modmsb = string.byte(payload,11)
modlsb = string.byte(payload,12)
body = string.char(slaveId,6,0,0,modmsb,modlsb)
holdingregs[modadrptr] = (bit.bor(modlsb,bit.lshift(modmsb,8)))

end




srv=net.createServer(net.TCP)
srv:listen(502,function(conn)
conn:on("receive",function(conn,payload)
slaveId = string.byte(payload,7)
functionCode = string.byte(payload,8)
modadrptr = string.byte(payload,10)

if functionCode == 3 then func3(modadrptr) end
if functionCode == 6 then func6(payload) end

createHeader()
checksum =(getCrc(body))
checklsb = bit.band(checksum,0xff)
checkmsb = bit.rshift((bit.band(checksum,0xff00)),8)
checksumMsbLsb = string.char(checklsb,checkmsb)
conn:send(header..body..checksumMsbLsb)


if bit.band(holdingregs[0],1) == 1 then gpio.write(4,gpio.HIGH) end
if bit.band(holdingregs[0],1) == 0 then gpio.write(4,gpio.LOW) end
holdingregs[2] = node.readvdd33()
holdingregs[3] = holdingregs[3] + 1
holdingregs[4] = bit.band(gpio.read(3),1)
end)
end)