diff --git a/main.go b/main.go index 0ed1369..379ac62 100644 --- a/main.go +++ b/main.go @@ -15,15 +15,15 @@ import ( type Payload struct { T string `json:"t"` - Dt1 int `json:"dt1"` - Dt2 int `json:"dt2"` - Rt1 int `json:"rt1"` - Rt2 int `json:"rt2"` + Dt1 *int `json:"dt1"` + Dt2 *int `json:"dt2"` + Rt1 *int `json:"rt1"` + Rt2 *int `json:"rt2"` D int `json:"d"` R int `json:"r"` F int `json:"f"` Fl int `json:"fl"` - G int `json:"g"` + G *int `json:"g"` V1 int `json:"v1"` V2 int `json:"v2"` V3 int `json:"v3"` @@ -88,6 +88,18 @@ func main() { select {} } +var prevDt1, prevDt2, prevRt1, prevRt2, prevG int + +func updateFieldIfChanged(currentValue *int, previousValue *int) *int { + if currentValue != nil && *currentValue == *previousValue { + return nil // No change, so we prepare to insert a NULL + } else if currentValue != nil { + *previousValue = *currentValue // Update the previous value to the current one + return currentValue + } + return currentValue // Return the original value if it's nil +} + func mqttMessageHandler(client mqtt.Client, msg mqtt.Message) { // Parse JSON payload var payload Payload @@ -104,6 +116,12 @@ func mqttMessageHandler(client mqtt.Client, msg mqtt.Message) { return } + payload.Dt1 = updateFieldIfChanged(payload.Dt1, &prevDt1) + payload.Dt2 = updateFieldIfChanged(payload.Dt2, &prevDt2) + payload.Rt1 = updateFieldIfChanged(payload.Rt1, &prevRt1) + payload.Rt2 = updateFieldIfChanged(payload.Rt2, &prevRt2) + payload.G = updateFieldIfChanged(payload.G, &prevG) + // Insert data into PostgreSQL err = insertData(timestamp, payload) if err != nil {