Extract data from mqtt json payload

This commit is contained in:
Siegfried Siegert 2020-08-31 07:01:40 +02:00
parent 985b4e8fde
commit 8f7a285289
2 changed files with 39 additions and 3 deletions

17
models/mo.go Normal file
View File

@ -0,0 +1,17 @@
package models
type Mo struct {
ID MoID `json:"id"`
MO MoMO `json:"mo"`
}
type MoID struct {
PTU4_MAC string
PTU4_SN string
}
type MoMO struct {
Action string `json:"action"`
Description string `json:"description"`
Number string `json:"number"`
}

View File

@ -2,19 +2,20 @@ package mqtt
import (
"crypto/tls"
//"crypto/x509"
"fmt"
"log"
"net/url"
"strconv"
"strings"
MQTT "github.com/eclipse/paho.mqtt.golang"
//"os"
"mqttListener/Config"
"mqttListener/models"
"regexp"
"time"
MQTT "github.com/eclipse/paho.mqtt.golang"
"encoding/json"
)
/*
@ -126,6 +127,8 @@ var subscriptionHandler = func(client MQTT.Client, msg MQTT.Message) {
fmt.Printf("MSG: \n%s\n", msg.Payload())
//fmt.Printf("* [%s] %s\n", msg.Topic(), string(msg.Payload()))
//-------------------------------------------------------------------
// create ID from topic
regexpWithType := "\\/ATB\\/[A-Z]+\\/[0-9]+\\/[0-9]+\\/mo"
regexpDefault := "\\/ATB\\/[0-9]+\\/[0-9]+\\/[0-9]+\\/[0-9]+\\/mo"
@ -160,5 +163,21 @@ var subscriptionHandler = func(client MQTT.Client, msg MQTT.Message) {
device.SN = "t.b.d."
device.LastMsg = "t.b.d"
//-------------------------------------------------------------------
// extract data from payload
bytes := []byte(msg.Payload())
mo := models.Mo{}
err = json.Unmarshal(bytes, &mo)
if err != nil {
fmt.Println(err.Error())
return
}
device.MAC = mo.ID.PTU4_MAC
device.SN = mo.ID.PTU4_SN
fmt.Printf("Device MAC = %s\n", device.MAC)
fmt.Printf("Device SN = %s\n", device.SN)
// TODO: store this device in database
}