LogicMachine Forum
Best way to decode Modbus - Printable Version

+- LogicMachine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Scripting (https://forum.logicmachine.net/forumdisplay.php?fid=8)
+--- Thread: Best way to decode Modbus (/showthread.php?tid=3450)



Best way to decode Modbus - gtsamis - 29.06.2021

Hi,

I have a DSE7320 power generator controller and i need to read some alerts.
I use Modbus mapper to store the alert registers to virtual objects and then decode them with script.
   
Code:
dword ='0x'.. event.datahex myobject = grp.find(event.dstraw) function getbit(value, nr)   value = bit.rshift(value, nr)   return bit.band(value, 1) end for i = 0, 15, 4 do   obj=math.floor((i+1)/4)   msg=''   val=''   for x = 0, 3, 1 do     ix=i+x       val = getbit(dword,ix)..val   end   bin = string.reverse(val)     local sum = 0     for i = 1, string.len(bin) do       num = string.sub(bin, i,i) == "1" and 1 or 0         sum = sum + num * math.pow(2, i-1)     end     msg=msg .. ' Bin:'..val..' Dec:'.. sum     obj=obj..msg   alert(myobject.name..'-'..obj) end

   
   

Can someone please verify if this is the most eficient way or sugest something better?

Thank you in advance
George


RE: Best way to decode Modbus - admin - 30.06.2021

The most correct way to do this is via bit shifts (bit.rshift and bit.band) but since you need to split the value into 4 bit values you can simply use the datahex string:
Code:
value = event.datahex values = {} for i = 1, 4 do   char = value:sub(i, i)   values[ i ] = tonumber(char, 16) end log(values)