#!/usr/bin/ruby
#
# Indices into the parsed values array 'v'
# 
TS = 1
PLT = -24
TV = -23
BV = -22
PSI = -21
STAT = -13
VPE = -9
CLT = -5
MSTAT = -4
MCURR = -3
ENC = -2

# Array of label/index pairs for output
# 
vals = [
   ["PwrCnt", PLT],
   ["CommsCnt", CLT],
   ["T_Volt", TV],
   ["B_Volt", BV],
   ["EncPos", ENC],
   ["MxCurr", MCURR]
]

Signal.trap("INT") { STDOUT.flush(); puts("\nDone"); exit }

# Execute continuously or just once
# 
n = 0
while(1) do
   next unless (line = gets())

   # Examine every tenth line
   # 
   n += 1
   next unless (n >= 10) 

   n = 0
   # This parses the line using ',' as a separator.
   # Array 'v' contains the string values.
   # 
   v = line.split(',')

   # Write the labels and values
   # 
   vals.each do |i|
      STDOUT.write("#{i[0]}=#{v[i[1]].lstrip}  ")
   end

   # Now parse the bit field
   # 
   status = v[STAT].to_i

   state = status & 0b1111000000000
   state = state >> 9
   ta = "#{status[7]}-#{status[8]}"
   chg = status[2]
   mxp = status[5]
   mxe = status[6]

   # Print the labels and bit values
   # 
   puts("State=#{state}  Targ-Act=#{ta}  Charge=#{chg}  MxPwr=#{mxp}  MxEnable=#{mxe}")
   STDOUT.flush()

   #break  # Just once for now

end
