Skip to content

Commit

Permalink
improved raw mqtt parser that converts directly to the usual 'full' j…
Browse files Browse the repository at this point in the history
…son representation
  • Loading branch information
timcowlishaw committed Sep 25, 2024
1 parent a15267f commit 2b441bd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 15 deletions.
53 changes: 39 additions & 14 deletions app/grammars/raw_message.tt
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,47 @@ grammar RawMessage
rule message
'{' message_body '}' {
def to_hash
message_body.to_hash
{ data: [ message_body.to_hash ] }
end
}
end

rule message_body
(pairs:pair*) {
def to_hash
pairs.elements.inject({}) {|m, p| m.merge(p.to_hash) }
pairs.elements.inject({ recorded_at: nil, sensors: [] }) { |accum, pair_node|
pair = pair_node.to_value
if pair[:key] == :t
accum.merge(recorded_at: pair[:value])
else
new_sensors_list = accum[:sensors] + [{id: pair[:key], value: pair[:value]}]
accum.merge(sensors: new_sensors_list)
end
}
end
}
end

rule pair
key ':' value (','?) {
def to_hash
{ key.to_sym => value.to_number }
pair:(timestamp_pair / value_pair) ","? {
def to_value
pair.to_value
end
}
end

rule timestamp_pair
't:' timestamp {
def to_value
{ key: :t, value: timestamp.text_value }
end
}
end

rule key
key:(number / 't') {
def to_sym
key.text_value.to_sym
rule value_pair
number ':' value {
def to_value
{ key: number.text_value, value: value.text_value }
end
}
end
Expand All @@ -37,21 +53,30 @@ grammar RawMessage

rule float
float:(number decimal_part) {
def to_number
float.text_value.to_f
def to_value
float.text_value
end
}
end

rule number
number:[0-9]+ {
def to_number
number.text_value.to_i
number:[\-0-9]+ {
def to_value
number.text_value
end
}
end

rule decimal_part
'.' number
end

rule timestamp
timestamp:([0-9] 4..4 '-' [0-9] 2..2 '-' [0-9] 2..2 'T' [0-9] 2..2 ':' [0-9] 2..2 ':' [0-9] 2..2 'Z') {
def to_value
Time.parse(timestamp.text_value)
end
}
end

end
2 changes: 1 addition & 1 deletion app/lib/raw_mqtt_message_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def initialize
end

def parse(message)
parser.parse(self.convert_to_ascii(message)).to_hash
parser.parse(self.convert_to_ascii(message))&.to_hash
end

private
Expand Down

0 comments on commit 2b441bd

Please sign in to comment.