Skip to content

Commit

Permalink
ensure null values are elided
Browse files Browse the repository at this point in the history
  • Loading branch information
timcowlishaw committed Oct 11, 2024
1 parent 39a52e3 commit 49c96d0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
24 changes: 19 additions & 5 deletions app/grammars/raw_message.tt
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ grammar RawMessage
pair = pair_node.to_value
if pair[:key] == :t
accum.merge(recorded_at: pair[:value])
else
elsif pair && pair[:value]
new_sensors_list = accum[:sensors] + [{id: pair[:key], value: pair[:value]}]
accum.merge(sensors: new_sensors_list)
else
accum
end
}
end
Expand All @@ -34,23 +36,35 @@ grammar RawMessage
rule timestamp_pair
't' whitespace ':' timestamp {
def to_value
{ key: :t, value: timestamp.text_value }
{ key: :t, value: timestamp.to_value }
end
}
end

rule value_pair
number whitespace ':' whitespace value {
number whitespace ':' whitespace optional_value {
def to_value
{ key: number.text_value, value: value.text_value }
{ key: number.to_value, value: optional_value.to_value }
end
}
end

rule optional_value
value / null
end

rule value
float / number
end

rule null
"null" {
def to_value
nil
end
}
end

rule float
float:(number decimal_part) {
def to_value
Expand All @@ -74,7 +88,7 @@ grammar RawMessage
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)
timestamp.text_value
end
}
end
Expand Down
6 changes: 6 additions & 0 deletions spec/lib/raw_mqtt_message_parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@
expect(parsed).to eq({ data: [ { recorded_at: "2024-09-25T13:19:38Z", sensors: [{id: "100", value: "-2000.12345"}, { id: "21", value: "12345.23450"}] }]})
end

it "strips null vales from messages" do
message = "{t:2024-09-25T13:19:38Z,100:-2000.12345,21:null}"
parsed = parser.parse(message)
expect(parsed).to eq({ data: [ { recorded_at: "2024-09-25T13:19:38Z", sensors: [{id: "100", value: "-2000.12345"}] }]})
end

it "returns nil if no valid message parsed" do
message = "ceci n'est pas un message"
parsed = parser.parse(message)
Expand Down

0 comments on commit 49c96d0

Please sign in to comment.