Extract data from mqtt json payload
This commit is contained in:
		
							
								
								
									
										25
									
								
								mqtt/mqtt.go
									
									
									
									
									
								
							
							
						
						
									
										25
									
								
								mqtt/mqtt.go
									
									
									
									
									
								
							@@ -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
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user