This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm whether you accept or reject these cookies being set.

Best way to decode Modbus
#1
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
Reply
#2
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)
Reply


Forum Jump: