Files
smartmeter/app/helpers/InSyncState.rb
2013-06-26 17:46:21 -04:00

59 lines
1.9 KiB
Ruby

class InSyncState < StatePattern::State
END_OF_FRAME = "!\n"
def handle_byte_stream(bytes)
idx = 0
#sync_pattern_length = Synchronizer::SYNC_PATTERN.length
sync_pattern_length = END_OF_FRAME.length
#p "Sync length: #{sync_length}"
frame = ""
while (idx+sync_pattern_length < bytes.length && !new_frame_starts(bytes,idx,sync_pattern_length)) do
frame = frame + bytes[idx]
idx = idx +1
end
# did we reach the end of the frame?
if new_frame_starts(bytes,idx,sync_pattern_length)
p "------ FRAME -----"
frame_lines = frame.split("\n")
p frame_lines
p "##################"
handle_frame(frame_lines)
return bytes[idx+sync_pattern_length..-1]
else
return nil
end
end
private
def new_frame_starts(bytes,idx,sync_pattern_length)
#return bytes[idx..idx+sync_pattern_length-1].eql?(Synchronizer::SYNC_PATTERN)
return bytes[idx..idx+sync_pattern_length-1].eql?(END_OF_FRAME)
end
def handle_frame(frame_lines)
frame_lines.each {| line|
if line.match(/1.8.1/)
total_kwh_consumed_high = line.split(/1-0:1.8.1\(|\*kWh\)/).join.to_f
p "Total kwh consumed (high): #{total_kwh_consumed_high}."
end
if line.match(/1.8.2/)
total_kwh_consumed_high = line.split(/1-0:1.8.2\(|\*kWh\)/).join.to_f
p "Total kwh consumed (low): #{total_kwh_consumed_high}."
end
if line.match(/2.8.1/)
total_kwh_produced_high = line.split(/1-0:2.8.1\(|\*kWh\)/).join.to_f
p "Total kwh consumed (high): #{total_kwh_produced_high}."
end
if line.match(/2.8.2/)
total_kwh_produced_low = line.split(/1-0:2.8.2\(|\*kWh\)/).join.to_f
p "Total kwh consumed (low): #{total_kwh_produced_low}."
end
}
end
end