Compare commits
15 Commits
v0.0.9
...
pu/Improve
Author | SHA1 | Date | |
---|---|---|---|
30c66efffd | |||
78241d8e5a | |||
8e95443548 | |||
dc5d066698 | |||
e02af3c353 | |||
5045802242 | |||
6f319cf6dd | |||
f21e4ff1d6 | |||
3f0fa81f18 | |||
91b94bd230 | |||
4a66fc4566 | |||
12098aec70 | |||
4cf22e75c4 | |||
b9539d6db9 | |||
f2066c7de6 |
101
build.sh
Executable file
101
build.sh
Executable file
@@ -0,0 +1,101 @@
|
||||
#!/bin/bash
|
||||
|
||||
APP=mqttListener
|
||||
|
||||
# expand PATH for go tools
|
||||
export PATH=$PATH:~/go/bin
|
||||
|
||||
|
||||
RED='\e[0;31m'
|
||||
GREEN='\e[0;32m'
|
||||
LIGHT_YELLOW='\e[93m'
|
||||
NC='\e[0m' # No Color
|
||||
BOLD='\e[1m'
|
||||
NORMAL='\e[21m'
|
||||
|
||||
#######################################################################################
|
||||
# defaults
|
||||
GO_BUILD_OPTIONS=-v
|
||||
#GO_BUILD_OPTIONS="-a -v"
|
||||
DEFAULT_TARGET=amd64
|
||||
|
||||
#######################################################################################
|
||||
# functions
|
||||
|
||||
die() { echo -e "\n${RED}$@${NC}" 1>&2 ; exit 1; }
|
||||
|
||||
usage() {
|
||||
echo "usage: `basename $0` [<TARGET>] [all]"
|
||||
}
|
||||
|
||||
|
||||
#######################################################################################
|
||||
# build functions
|
||||
|
||||
build_linux_amd64() {
|
||||
echo -e "\nBuilding for Linux amd64:"
|
||||
|
||||
env GOOS=linux GOARCH=amd64 go build ${GO_BUILD_OPTIONS} -ldflags "$(govvv -flags)" -o ${APP}-linux-amd64
|
||||
echo -e "\t\t${GREEN}... done${NC}"
|
||||
}
|
||||
|
||||
build_linux_arm() {
|
||||
echo -e "\nBuilding for arm:"
|
||||
|
||||
# setup environment
|
||||
export CGO_ENABLED=1
|
||||
export PATH=$PATH:/opt/devel/ptu4/buildrootBuild/host/usr/bin
|
||||
export CC=arm-linux-gcc
|
||||
export PKG_CONFIG_PATH=/opt/devel/ptu4/buildrootBuild/host/usr/lib/pkgconfig
|
||||
|
||||
env GOOS=linux GOARCH=arm go build ${GO_BUILD_OPTIONS} -ldflags "$(govvv -flags)" -o ${APP}-linux-arm
|
||||
echo -e "\t\t${GREEN}... done${NC}"
|
||||
|
||||
echo -e "\nstipping arm binary:"
|
||||
strip -o ${APP}-linux-arm-stripped ${APP}-linux-arm
|
||||
echo -e "\t\t${GREEN}... done${NC}"
|
||||
}
|
||||
|
||||
#######################################################################################
|
||||
# checks
|
||||
|
||||
echo -e "${NC}\n "
|
||||
|
||||
|
||||
if [ ! command -v govvv &> /dev/null ] ; then
|
||||
die "govvv is not installed"
|
||||
fi
|
||||
|
||||
|
||||
if [ $# -eq 0 ] ; then
|
||||
echo -e "\nbuilding for default TARGET ${DEFAULT_TARGET}..."
|
||||
TARGET=${DEFAULT_TARGET}
|
||||
else
|
||||
TARGET=$1
|
||||
fi
|
||||
|
||||
#######################################################################################
|
||||
# build
|
||||
|
||||
#cd /src
|
||||
|
||||
|
||||
if [ "$2" == "all" ] ; then
|
||||
echo -e "\nforce rebuilding of all packages..."
|
||||
GO_BUILD_OPTIONS="-a -v"
|
||||
fi
|
||||
|
||||
|
||||
case "${TARGET}" in
|
||||
"arm"|"ARM")
|
||||
build_linux_arm
|
||||
;;
|
||||
"amd64"|"AMD64")
|
||||
build_linux_amd64
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
die "Target ${TARGET} is not defined"
|
||||
;;
|
||||
esac
|
||||
|
10
env/env.go
vendored
10
env/env.go
vendored
@@ -26,6 +26,14 @@ func (env *Env) DevicesIndex(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
for _, device := range devices {
|
||||
fmt.Fprintf(w, "%s, %s, %s, £%.2f\n", device.ID, device.MAC, device.SN, device.LastMsg)
|
||||
fmt.Fprintf(w, "%s, %s, %s, %s, %s, %s, %s\n",
|
||||
device.TOPIC,
|
||||
device.CustomerID,
|
||||
device.DeviceID,
|
||||
device.ProjectName,
|
||||
device.MAC,
|
||||
device.SN,
|
||||
device.LastMsg,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
1
go.mod
1
go.mod
@@ -3,6 +3,7 @@ module mqttListener
|
||||
go 1.14
|
||||
|
||||
require (
|
||||
github.com/ahmetb/govvv v0.3.0 // indirect
|
||||
github.com/eclipse/paho.mqtt.golang v1.2.0
|
||||
github.com/mattn/go-sqlite3 v1.14.2
|
||||
github.com/mmcdole/gofeed v1.0.0
|
||||
|
51
main.go
51
main.go
@@ -6,18 +6,64 @@ import (
|
||||
"mqttListener/models"
|
||||
"mqttListener/mqtt"
|
||||
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Following variables will be statically linked at the time of compiling
|
||||
|
||||
// GitCommit holds short commit hash of source tree
|
||||
var GitCommit string
|
||||
|
||||
// GitBranch holds current branch name the code is built off
|
||||
var GitBranch string
|
||||
|
||||
// GitState shows whether there are uncommitted changes
|
||||
var GitState string
|
||||
|
||||
// GitSummary holds output of git describe --tags --dirty --always
|
||||
var GitSummary string
|
||||
|
||||
// BuildDate holds RFC3339 formatted UTC date (build time)
|
||||
var BuildDate string
|
||||
|
||||
// Version holds contents of ./VERSION file, if exists, or the value passed via the -version option
|
||||
var Version string
|
||||
|
||||
// PrintVersion prints version information
|
||||
func PrintVersion() {
|
||||
var versionString string = GitSummary
|
||||
fmt.Println("\n--------------------------------------------------------")
|
||||
fmt.Println(filepath.Base(os.Args[0]), " Version Information: ")
|
||||
fmt.Println("\tVersion:\t", versionString)
|
||||
fmt.Println("\tBranch:\t\t", GitBranch)
|
||||
fmt.Println("\tCommit-ID:\t", GitCommit)
|
||||
fmt.Println("\tBuilt:\t\t", BuildDate)
|
||||
fmt.Println("\n--------------------------------------------------------")
|
||||
fmt.Println("")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
func main() {
|
||||
|
||||
versionFlagPtr := flag.Bool("v", false, "print version")
|
||||
flag.Parse()
|
||||
if *versionFlagPtr {
|
||||
PrintVersion()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
PrintVersion()
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
@@ -34,11 +80,12 @@ func main() {
|
||||
log.Panic(err)
|
||||
}
|
||||
|
||||
env := &env.Env{db, config}
|
||||
env := &env.Env{DB: db, Config: config}
|
||||
|
||||
mqtt.Setup(env)
|
||||
mqtt.Connect()
|
||||
go mqtt.Listen()
|
||||
go mqtt.Listen("/ATB/#")
|
||||
go mqtt.Listen("ATB/#")
|
||||
|
||||
http.HandleFunc("/devices", env.DevicesIndex)
|
||||
go http.ListenAndServe(":3000", nil)
|
||||
|
@@ -24,7 +24,13 @@ func NewDB(dataSourceName string) (*DB, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlStmt := "CREATE TABLE IF NOT EXISTS devices (id TEXT not null primary key, mac TEXT, sn TEXT, lastMsg TEXT);"
|
||||
sqlStmt := `CREATE TABLE IF NOT EXISTS devices (topic TEXT not null primary key,
|
||||
customerID TEXT,
|
||||
deviceID TEXT,
|
||||
projectName TEXT,
|
||||
mac TEXT,
|
||||
sn TEXT,
|
||||
lastMsg TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`
|
||||
_, err = db.Exec(sqlStmt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@@ -2,13 +2,17 @@ package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Device struct {
|
||||
ID string
|
||||
MAC string
|
||||
SN string
|
||||
LastMsg string
|
||||
TOPIC string
|
||||
CustomerID string
|
||||
DeviceID string
|
||||
ProjectName string
|
||||
MAC string
|
||||
SN string
|
||||
LastMsg string
|
||||
}
|
||||
|
||||
func (db *DB) AllDevices() ([]*Device, error) {
|
||||
@@ -21,28 +25,58 @@ func (db *DB) AllDevices() ([]*Device, error) {
|
||||
devices := make([]*Device, 0)
|
||||
for rows.Next() {
|
||||
device := new(Device)
|
||||
err := rows.Scan(&device.ID, &device.MAC, &device.SN, &device.LastMsg)
|
||||
err := rows.Scan(&device.TOPIC, &device.CustomerID, &device.DeviceID, &device.ProjectName, &device.MAC, &device.SN, &device.LastMsg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
device.ProjectName, err = db.GetProjectName(device.CustomerID)
|
||||
devices = append(devices, device)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return devices, nil
|
||||
}
|
||||
|
||||
func (db *DB) InsertDevice(device *Device) error {
|
||||
sqlStmt := `INSERT OR REPLACE INTO devices (id, mac, sn, lastMsg)
|
||||
VALUES($1, $2, $3, $4);`
|
||||
_, err := db.Exec(sqlStmt, device.ID, device.MAC, device.SN, device.LastMsg)
|
||||
|
||||
timeStamp := time.Now().Format(time.RFC3339)
|
||||
// DEBUG
|
||||
fmt.Printf("Timestamp: %s\n", timeStamp)
|
||||
|
||||
sqlStmt := `INSERT OR REPLACE INTO devices (topic, customerID, deviceID, projectName, mac, sn)
|
||||
VALUES($1, $2, $3, $4, $5, $6);`
|
||||
_, err := db.Exec(sqlStmt, device.TOPIC, device.CustomerID, device.DeviceID, device.ProjectName, device.MAC, device.SN)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// DEBUG
|
||||
fmt.Printf("Sucessfully inserted device with ID %s to database\n", device.ID)
|
||||
fmt.Printf("Sucessfully inserted device with ID %s to database\n", device.TOPIC)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (db *DB) GetProjectName(projectNumber string) (string, error) {
|
||||
|
||||
projectNameRows, err := db.Query("SELECT projectName FROM projects WHERE projectNumber = $1", projectNumber)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer projectNameRows.Close()
|
||||
|
||||
projectName := ""
|
||||
for projectNameRows.Next() {
|
||||
err := projectNameRows.Scan(&projectName)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if err = projectNameRows.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return projectName, err
|
||||
|
||||
}
|
||||
|
28
mqtt/mqtt.go
28
mqtt/mqtt.go
@@ -40,7 +40,7 @@ func Connect() {
|
||||
fmt.Println("connected to broker, topic = ", topic)
|
||||
}
|
||||
|
||||
func Listen() {
|
||||
func Listen(topic string) {
|
||||
if !client.IsConnected() {
|
||||
log.Fatal("Client is not connected")
|
||||
return
|
||||
@@ -82,8 +82,6 @@ func Setup(environment *env.Env) {
|
||||
//fmt.Println("customer: ", *customer)
|
||||
//fmt.Println("device: ", *device)
|
||||
|
||||
topic = "/ATB/#"
|
||||
|
||||
opts = createClientOptions(ev.Config.BrokerClientID, uri)
|
||||
|
||||
}
|
||||
@@ -124,10 +122,15 @@ var subscriptionHandler = func(client MQTT.Client, msg MQTT.Message) {
|
||||
|
||||
//-------------------------------------------------------------------
|
||||
// create ID from topic
|
||||
regexpWithType := "\\/ATB\\/[A-Z]+\\/[0-9]+\\/[0-9]+\\/mo"
|
||||
regexpDefault := "\\/ATB\\/[0-9]+\\/[0-9]+\\/[0-9]+\\/[0-9]+\\/mo"
|
||||
regexpWithType := "ATB\\/[A-Z]+\\/[\\-]*[0-9]+\\/[\\-]*[0-9]+\\/mo"
|
||||
regexpDefault := "ATB\\/[0-9]+\\/[\\-]*[0-9]+\\/[\\-]*[0-9]+\\/[0-9]+\\/mo"
|
||||
|
||||
topicSlice := strings.Split(msg.Topic(), "/")
|
||||
|
||||
// remove a possible empty element (-> handle '/ATB/#' and 'ATB/#'
|
||||
if (len(topicSlice[0]) == 0) {
|
||||
topicSlice = topicSlice[1:]
|
||||
}
|
||||
|
||||
matchedWithType, err := regexp.MatchString(regexpWithType, msg.Topic())
|
||||
if err != nil {
|
||||
@@ -138,13 +141,16 @@ var subscriptionHandler = func(client MQTT.Client, msg MQTT.Message) {
|
||||
log.Printf("ERROR: matchedDefault: %s", err.Error())
|
||||
}
|
||||
|
||||
var customerID string
|
||||
var deviceID string
|
||||
if matchedWithType {
|
||||
fmt.Printf("Topic matched regexpWithType\n")
|
||||
deviceID = topicSlice[2] + "_" + topicSlice[3] + "_" + topicSlice[4]
|
||||
customerID = topicSlice[2]
|
||||
deviceID = topicSlice[3]
|
||||
} else if matchedDefault {
|
||||
fmt.Printf("Topic matched regexpDefault\n")
|
||||
deviceID = topicSlice[2] + "_" + topicSlice[3] + "_" + topicSlice[4] + "_" + topicSlice[5]
|
||||
customerID = topicSlice[1]
|
||||
deviceID = topicSlice[4]
|
||||
} else {
|
||||
log.Printf("ERROR: no matching topic: %s", msg.Topic())
|
||||
return
|
||||
@@ -153,7 +159,11 @@ var subscriptionHandler = func(client MQTT.Client, msg MQTT.Message) {
|
||||
fmt.Printf("Generated deviceID = %s\n", deviceID)
|
||||
|
||||
var device models.Device
|
||||
device.ID = deviceID
|
||||
device.TOPIC = msg.Topic()
|
||||
device.CustomerID = customerID
|
||||
device.DeviceID = deviceID
|
||||
device.ProjectName = "projectName t.b.d."
|
||||
|
||||
device.MAC = "t.b.d."
|
||||
device.SN = "t.b.d."
|
||||
device.LastMsg = "t.b.d"
|
||||
@@ -174,7 +184,7 @@ var subscriptionHandler = func(client MQTT.Client, msg MQTT.Message) {
|
||||
fmt.Printf("Device MAC = %s\n", device.MAC)
|
||||
fmt.Printf("Device SN = %s\n", device.SN)
|
||||
|
||||
// TODO: store this device in database
|
||||
// store this device in database
|
||||
err = ev.DB.InsertDevice(&device)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
|
Reference in New Issue
Block a user