Payload - green-ecolution/backend GitHub Wiki
Once The Things Stack Cloud has decoded the raw LoRaWAN data, it produces a JSON payload that our backend can easily interpret. This JSON contains sensor readings such as temperature, humidity, location, and battery voltage. Below is an example of the decoded payload:
{
"data": {
"messageType": "normal",
"temperature": 25.5,
"waterContent": 0.45,
"latitude": 52.123456,
"longitude": 4.56789,
"timeTaken": 1697385600,
"batteryVoltage": 3.7,
"WM30_Resistance": 1200,
"WM30_CB": 500,
"WM60_Resistance": 1500,
"WM60_CB": 600,
"WM90_Resistance": 1800,
"WM90_CB": 700,
"deviceName": "Sensor_123"
}
}
In our backend, we subscribe to TTN’s MQTT topic to receive this JSON. Once received, we process it with a function that extracts and converts the data into a structured format that aligns with our backend domain model. The extracted data is mapped into the MqttPayload
struct, which standardizes sensor values and allows for further processing within our system.
type Watermark struct {
Centibar int
Resistance int
Depth int
}
type MqttPayload struct {
Device string `validate:"required"`
Battery float64
Humidity float64
Temperature float64
Latitude float64 `validate:"omitempty,min=-90,max=90"`
Longitude float64 `validate:"omitempty,min=-180,max=180"`
Watermarks []Watermark
}
To handle incoming messages, the system runs the convertToMqttPayloadResponse
function, which converts the raw MQTT payload into the MqttPayload
struct before passing it for further processing:
payload := &sensor.MqttPayloadResponse{
Device: deviceName,
Battery: batteryVoltage,
Humidity: waterContent,
Temperature: temperature,
Latitude: latitude,
Longitude: longitude,
Watermarks: []sensor.WatermarkResponse{
{
Resistance: int(wm30Res),
Centibar: int(wm30Cb),
Depth: 30,
},
{
Resistance: int(wm60Res),
Centibar: int(wm60Cb),
Depth: 60,
},
{
Resistance: int(wm90Res),
Centibar: int(wm90Cb),
Depth: 90,
},
},
}
This function extracts sensor values, including temperature, humidity, location, battery voltage, and watermark sensor readings. Once mapped into the MqttPayload
struct, the data is validated and stored in the database, ensuring seamless integration between TTN’s MQTT messages and our backend system.