Skip to content

Commit 5d72f5f

Browse files
moznionbrocaar
authored andcommitted
Handle empty time string RXPK (#82)
Some gateway vendors send and empty `time` string instead of leaving this `time` key` out of the JSON object, or setting this to `null`.
1 parent 7fc9b2d commit 5d72f5f

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

internal/gateway/backend.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -445,7 +445,9 @@ func newRXPacketsFromRXPK(mac lorawan.EUI64, rxpk RXPK) ([]gw.RXPacketBytes, err
445445

446446
if rxpk.Time != nil {
447447
ts := time.Time(*rxpk.Time)
448-
rxPacket.RXInfo.Time = &ts
448+
if !ts.IsZero() {
449+
rxPacket.RXInfo.Time = &ts
450+
}
449451
}
450452

451453
if rxpk.Tmms != nil {

internal/gateway/structs.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,11 +316,19 @@ type CompactTime time.Time
316316

317317
// MarshalJSON implements the json.Marshaler interface.
318318
func (t CompactTime) MarshalJSON() ([]byte, error) {
319-
return []byte(time.Time(t).UTC().Format(`"` + time.RFC3339Nano + `"`)), nil
319+
t2 := time.Time(t)
320+
if t2.IsZero() {
321+
return []byte("null"), nil
322+
}
323+
return []byte(t2.UTC().Format(`"` + time.RFC3339Nano + `"`)), nil
320324
}
321325

322326
// UnmarshalJSON implements the json.Unmarshaler interface.
323327
func (t *CompactTime) UnmarshalJSON(data []byte) error {
328+
if string(data) == `""` {
329+
return nil
330+
}
331+
324332
t2, err := time.Parse(`"`+time.RFC3339Nano+`"`, string(data))
325333
if err != nil {
326334
return err

internal/gateway/structs_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,22 @@ func TestCompactTime(t *testing.T) {
7979
})
8080
})
8181
})
82+
83+
Convey("Given an empty string as date value", t, func() {
84+
Convey("UnmarshalJSON returns nil", func() {
85+
var ct CompactTime
86+
err := ct.UnmarshalJSON([]byte(`""`))
87+
So(err, ShouldBeNil)
88+
So(time.Time(ct).Equal(time.Time{}), ShouldBeTrue)
89+
})
90+
91+
Convey("MarshalJSON returns null", func() {
92+
ct := CompactTime(time.Time{})
93+
b, err := ct.MarshalJSON()
94+
So(err, ShouldBeNil)
95+
So(string(b), ShouldEqual, "null")
96+
})
97+
})
8298
}
8399

84100
func TestGetPacketType(t *testing.T) {

0 commit comments

Comments
 (0)