switch to zap for logging

This commit is contained in:
Jeffrey C. Ollie 2020-08-09 07:23:47 -05:00
parent 8b11809e80
commit bfcc7bf15b
Signed by: jeff
GPG key ID: 6F86035A6D97044E
7 changed files with 247 additions and 249 deletions

View file

@ -2,23 +2,20 @@ package cmd
import (
"context"
"fmt"
"log"
"os"
"sync"
"time"
"git.ocjtech.us/jeff/bluelisten/lib/bluetooth"
xiaomi_mijia "git.ocjtech.us/jeff/bluelisten/lib/xiaomi/mijia"
xiaomi_scale "git.ocjtech.us/jeff/bluelisten/lib/xiaomi/scale"
"github.com/currantlabs/ble"
"github.com/currantlabs/ble/linux"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/go-ble/ble"
"github.com/go-ble/ble/linux"
influxdb2 "github.com/influxdata/influxdb-client-go"
influxdb2_api "github.com/influxdata/influxdb-client-go/api"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uber.org/zap"
)
// listenCmd represents the listen command
@ -50,13 +47,19 @@ func init() {
var client influxdb2.Client
var writeAPI influxdb2_api.WriteAPI
var logger *zap.Logger
func listen(cmd *cobra.Command, args []string) {
d, err := linux.NewDevice()
logger, _ = zap.NewDevelopment()
defer logger.Sync()
logger.Debug("starting up")
d, err := linux.NewDevice(ble.OptDeviceID(0))
if err != nil {
log.Fatalf("can't new device : %s", err)
logger.Fatal("can't get new device",
zap.String("error", err.Error()))
}
ble.SetDefaultDevice(d)
serverURL := viper.GetString("influxdb2.server_url")
token := viper.GetString("influxdb2.token")
@ -67,7 +70,7 @@ func listen(cmd *cobra.Command, args []string) {
writeAPI = client.WriteAPI(organization, bucket)
ctx := ble.WithSigHandler(context.WithCancel(context.Background()))
chkErr(ble.listen(ctx, true, advHandler, nil))
chkErr(logger, d.Scan(ctx, true, advHandler))
writeAPI.Flush()
client.Close()
@ -76,143 +79,69 @@ func listen(cmd *cobra.Command, args []string) {
var tileUUID ble.UUID = []byte{0xed, 0xfe}
var nestUUID ble.UUID = []byte{0xaf, 0xfe}
var mux sync.Mutex
var mqttClient mqtt.Client
var detector, _ = os.Hostname()
func advHandler(a ble.Advertisement) {
func advHandler(advertisement ble.Advertisement) {
timestamp := time.Now()
description := bluetooth.GetDescription(advertisement.Addr())
// fmt.Printf("[%s] %3d:\n", a.Address(), a.RSSI())
// fmt.Printf("\n")
// if len(a.LocalName()) > 0 {
// fmt.Printf(" Name: %s\n", a.LocalName())
// }
// if len(a.Services()) > 0 {
// fmt.Printf(" Svcs: %v\n", a.Services())
// }
// if len(a.ManufacturerData()) > 0 {
// fmt.Printf(" MD: %v\n", a.ManufacturerData())
// }
// fmt.Printf("\n")
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
if description != "" {
point.AddTag("description", description)
}
point.AddTag("measurement_unit", "dBm")
point.AddField("rssi", advertisement.RSSI())
writeAPI.WritePoint(point)
if len(a.ServiceData()) > 0 {
for index, sd := range a.ServiceData() {
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "RSSI"),
zap.String("measurement_unit", "dBm"),
zap.Int("value", advertisement.RSSI()))
if len(advertisement.ServiceData()) > 0 {
for index, sd := range advertisement.ServiceData() {
switch {
case sd.UUID.Equal(xiaomi_scale.XiaomiScaleV1UUID):
xiaomi_scale.ParseXiaomiScaleV1(&mux, &writeAPI, a, index, sd)
xiaomi_scale.ParseXiaomiScaleV1(&writeAPI, logger, timestamp, detector, description, advertisement, index, sd)
case sd.UUID.Equal(xiaomi_scale.XiaomiScaleV2UUID):
xiaomi_scale.ParseXiaomiScaleV2(&mux, &writeAPI, a, index, sd)
xiaomi_scale.ParseXiaomiScaleV2(&writeAPI, logger, timestamp, detector, description, advertisement, index, sd)
case sd.UUID.Equal(xiaomi_mijia.XiaomiMijiaHTV1UUID):
xiaomi_mijia.ParseXiaomiMijiaSensorData(&mux, &writeAPI, a, index, sd)
xiaomi_mijia.ParseXiaomiMijiaSensorData(&writeAPI, logger, timestamp, detector, description, advertisement, index, sd)
case sd.UUID.Equal(tileUUID):
timestamp := time.Now()
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
detector, _ := os.Hostname()
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", a.Address().String())
description := bluetooth.GetDescription(a.Address())
if description != "" {
point.AddTag("description", description)
}
point.AddField("rssi", a.RSSI())
writeAPI.WritePoint(point)
// mux.Lock()
// fmt.Printf("*******************************************\n")
// fmt.Printf("Tile\n")
// if len(a.LocalName()) > 0 {
// fmt.Printf(" Name: %s\n", a.LocalName())
// }
// if len(a.Services()) > 0 {
// fmt.Printf(" Svcs: %v\n", a.Services())
// }
// if len(a.ManufacturerData()) > 0 {
// fmt.Printf(" MD: %v\n", a.ManufacturerData())
// }
// fmt.Printf("[%s] %3d:\n", a.Address(), a.RSSI())
// fmt.Printf("%d %v %v %d\n", index, sd.UUID, sd.Data, len(sd.Data))
// fmt.Printf("*******************************************\n")
// mux.Unlock()
case sd.UUID.Equal(nestUUID):
timestamp := time.Now()
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
detector, _ := os.Hostname()
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", a.Address().String())
description := bluetooth.GetDescription(a.Address())
if description != "" {
point.AddTag("description", description)
}
point.AddField("rssi", a.RSSI())
writeAPI.WritePoint(point)
// mux.Lock()
// fmt.Printf("*******************************************\n")
// fmt.Printf("Nest\n")
// if len(a.LocalName()) > 0 {
// fmt.Printf(" Name: %s\n", a.LocalName())
// }
// if len(a.Services()) > 0 {
// fmt.Printf(" Svcs: %v\n", a.Services())
// }
// if len(a.ManufacturerData()) > 0 {
// fmt.Printf(" MD: %v\n", a.ManufacturerData())
// }
// fmt.Printf("[%s] %3d:\n", a.Address(), a.RSSI())
// fmt.Printf("%d %v %v %d\n", index, sd.UUID, sd.Data, len(sd.Data))
// fmt.Printf("*******************************************\n")
// mux.Unlock()
default:
timestamp := time.Now()
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
point.AddTag("address", a.Address().String())
description := bluetooth.GetDescription(a.Address())
if description != "" {
point.AddTag("description", description)
}
point.AddField("rssi", a.RSSI())
writeAPI.WritePoint(point)
mux.Lock()
fmt.Printf("*******************************************\n")
fmt.Printf("Unknown\n")
if len(a.LocalName()) > 0 {
fmt.Printf(" Name: %s\n", a.LocalName())
}
if len(a.Services()) > 0 {
fmt.Printf(" Svcs: %v\n", a.Services())
}
if len(a.ManufacturerData()) > 0 {
fmt.Printf(" MD: %v\n", a.ManufacturerData())
}
fmt.Printf("[%s] %3d:\n", a.Address(), a.RSSI())
fmt.Printf("%d %v %v %d\n", index, sd.UUID, sd.Data, len(sd.Data))
fmt.Printf("*******************************************\n")
mux.Unlock()
logger.Debug("unknown service data type",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("name", advertisement.LocalName()),
zap.String("uuid", sd.UUID.String()))
}
}
}
}
func chkErr(err error) {
func chkErr(logger *zap.Logger, err error) {
logger.Debug("chkErr")
switch errors.Cause(err) {
case nil:
case context.DeadlineExceeded:
fmt.Printf("done\n")
logger.Debug("done")
case context.Canceled:
fmt.Printf("canceled\n")
logger.Debug("canceled")
default:
log.Fatalf(err.Error())
logger.Fatal("error",
zap.String("error", err.Error()))
}
}

5
go.mod
View file

@ -3,14 +3,13 @@ module git.ocjtech.us/jeff/bluelisten
go 1.14
require (
github.com/currantlabs/ble v0.0.0-20171229162446-c1d21c164cf8
github.com/eclipse/paho.mqtt.golang v1.2.0
github.com/go-ble/ble v0.0.0-20200407180624-067514cd6e24
github.com/influxdata/influxdb-client-go v1.4.0
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab // indirect
github.com/mitchellh/go-homedir v1.1.0
github.com/pkg/errors v0.9.1
github.com/spf13/cobra v1.0.0
github.com/spf13/viper v1.7.1
go.uber.org/zap v1.15.0
golang.org/x/net v0.0.0-20200707034311-ab3426394381 // indirect
)

28
go.sum
View file

@ -34,9 +34,8 @@ github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3Ee
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/currantlabs/ble v0.0.0-20171229162446-c1d21c164cf8 h1:eo7L0zxxFowLpF4FNlLijrAMVNlq9h8sicNwMfzauM8=
github.com/currantlabs/ble v0.0.0-20171229162446-c1d21c164cf8/go.mod h1:MGpIf7cfnYPFaMIcD8LoSgCr8Jsa4rUcV5Nb9temsYw=
github.com/cyberdelia/templates v0.0.0-20141128023046-ca7fffd4298c/go.mod h1:GyV+0YP4qX0UQ7r2MoYZ+AvYDp12OF5yg4q8rGnyNh4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@ -45,13 +44,13 @@ github.com/deepmap/oapi-codegen v1.3.6 h1:Wj44p9A0V0PJ+AUg0BWdyGcsS1LY18U+0rCuPQ
github.com/deepmap/oapi-codegen v1.3.6/go.mod h1:aBozjEveG+33xPiP55Iw/XbVkhtZHEGLq3nxlX0+hfU=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/eclipse/paho.mqtt.golang v1.2.0 h1:1F8mhG9+aO5/xpdtFkW4SxOJB67ukuDC3t2y2qayIX0=
github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/getkin/kin-openapi v0.2.0/go.mod h1:V1z9xl9oF5Wt7v32ne4FmiF1alpS4dM6mNzoywPOXlk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-ble/ble v0.0.0-20200407180624-067514cd6e24 h1:6St0uI/mfzuJX/y596wl2dJmA1VfdBSqopaUfS29z24=
github.com/go-ble/ble v0.0.0-20200407180624-067514cd6e24/go.mod h1:nwmyxHsP2cqjashMTTAl3A5t6V3vzev1rLgMb/pZ7jc=
github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
@ -121,6 +120,7 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
@ -148,6 +148,7 @@ github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2y
github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10=
github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab h1:n8cgpHzJ5+EDyDri2s/GC7a9+qK3/YEGnBsd0uS/8PY=
@ -163,7 +164,9 @@ github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0Qu
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
@ -187,6 +190,7 @@ github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/raff/goble v0.0.0-20190909174656-72afc67d6a99/go.mod h1:CxaUhijgLFX0AROtH5mluSY71VqpjQBw9JXE2UKZmc4=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
@ -211,8 +215,6 @@ github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb6
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
github.com/spf13/viper v1.7.0 h1:xVKxvI7ouOI5I+U9s2eeiUfMaWBVoXA3AWskkrqK0VM=
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk=
github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@ -225,6 +227,7 @@ github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
@ -235,9 +238,19 @@ github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.15.0 h1:ZZCA22JRF2gQE5FoNmhmrf7jeJJ2uhqDUNRYKm8dvmM=
go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@ -309,6 +322,7 @@ golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191115151921-52ab43148777/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191126131656-8a8471f7e56d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@ -333,6 +347,8 @@ golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgw
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View file

@ -3,7 +3,7 @@ package bluetooth
import (
"fmt"
"github.com/currantlabs/ble"
"github.com/go-ble/ble"
"github.com/spf13/viper"
)

View file

@ -3,18 +3,15 @@ package mijia
import (
"encoding/binary"
"fmt"
"os"
"sync"
"time"
"git.ocjtech.us/jeff/bluelisten/lib/bluetooth"
"github.com/currantlabs/ble"
"github.com/go-ble/ble"
influxdb2 "github.com/influxdata/influxdb-client-go"
influxdb2_api "github.com/influxdata/influxdb-client-go/api"
"go.uber.org/zap"
)
var debug = false
// XiaomiMijiaHTV1UUID is the Bluetooth UUID for Xiaomi Mijia BLE sensor data
var XiaomiMijiaHTV1UUID ble.UUID = []byte{0x95, 0xfe}
@ -29,8 +26,8 @@ const (
)
// ParseXiaomiMijiaSensorData parses
func ParseXiaomiMijiaSensorData(mux *sync.Mutex, writeAPI *influxdb2_api.WriteAPI, advertisement ble.Advertisement, index int, sd ble.ServiceData) {
timestamp := time.Now()
func ParseXiaomiMijiaSensorData(writeAPI *influxdb2_api.WriteAPI, logger *zap.Logger, timestamp time.Time, detector string, description string, advertisement ble.Advertisement, index int, sd ble.ServiceData) {
var sensorData struct {
frameControl uint16
isFactoryNew bool
@ -97,9 +94,7 @@ func ParseXiaomiMijiaSensorData(mux *sync.Mutex, writeAPI *influxdb2_api.WriteAP
sensorData.capabilityData.io = sensorData.capabilities & ((1 << 3) | (1 << 4)) // != 0
}
if sensorData.isEncrypted {
if debug {
fmt.Printf("Need to decrypt!\n")
}
logger.Warn("packet is encrypted")
return
}
if sensorData.hasEvent {
@ -114,74 +109,188 @@ func ParseXiaomiMijiaSensorData(mux *sync.Mutex, writeAPI *influxdb2_api.WriteAP
sensorData.eventData.eventType = binary.LittleEndian.Uint16(sd.Data[eventOffset:])
sensorData.eventData.eventLength = uint8(sd.Data[eventOffset+2])
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
detector, _ := os.Hostname()
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Address().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
description := bluetooth.GetDescription(advertisement.Address())
if description != "" {
point.AddTag("description", description)
}
point.AddField("rssi", advertisement.RSSI())
switch sensorData.eventData.eventType {
case temperatureEvent:
sensorData.eventData.temperature = float64(int16(binary.LittleEndian.Uint16(sd.Data[eventOffset+3:]))) / 10.0
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
description := bluetooth.GetDescription(advertisement.Addr())
if description != "" {
point.AddTag("description", description)
}
point.AddTag("temperature_unit", "°C")
point.AddField("temperature", sensorData.eventData.temperature)
(*writeAPI).WritePoint(point)
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "temperature"),
zap.String("measurement_unit", "°C"),
zap.Float64("value", sensorData.eventData.temperature))
case humidityEvent:
sensorData.eventData.humidity = float64(binary.LittleEndian.Uint16(sd.Data[eventOffset+3:])) / 10.0
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
if description != "" {
point.AddTag("description", description)
}
point.AddTag("humidity_unit", "%")
point.AddField("humidity", sensorData.eventData.humidity)
(*writeAPI).WritePoint(point)
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "humidity"),
zap.String("measurement_unit", "%"),
zap.Float64("value", sensorData.eventData.humidity))
case illuminanceEvent:
sensorData.eventData.illuminance = uint(sd.Data[eventOffset+3]) + uint(sd.Data[eventOffset+4])<<8 + uint(sd.Data[eventOffset+5])<<16
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
if description != "" {
point.AddTag("description", description)
}
point.AddTag("illuminance_unit", "lx")
point.AddField("illuminance", sensorData.eventData.illuminance)
(*writeAPI).WritePoint(point)
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "illuminance"),
zap.String("measurement_unit", "lx"),
zap.Uint("value", sensorData.eventData.illuminance))
case moistureEvent:
sensorData.eventData.moisture = int8(sd.Data[eventOffset+3])
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
if description != "" {
point.AddTag("description", description)
}
point.AddTag("moisture_unit", "%")
point.AddField("moisture", sensorData.eventData.moisture)
(*writeAPI).WritePoint(point)
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "moisture"),
zap.String("measurement_unit", "%"),
zap.Int8("value", sensorData.eventData.moisture))
case conductivityEvent:
sensorData.eventData.conductivity = int16(binary.LittleEndian.Uint16(sd.Data[eventOffset+3:]))
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
if description != "" {
point.AddTag("description", description)
}
point.AddTag("conductivity_unit", "µS/cm")
point.AddField("conductivity", sensorData.eventData.conductivity)
(*writeAPI).WritePoint(point)
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "RSSI"),
zap.String("measurement_unit", "µS/cm"),
zap.Int16("value", sensorData.eventData.conductivity))
case batteryEvent:
sensorData.eventData.battery = uint8(sd.Data[eventOffset+3])
if debug {
fmt.Printf("battery: %d\n", sensorData.eventData.battery)
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
if description != "" {
point.AddTag("description", description)
}
point.AddTag("battery_unit", "%")
point.AddField("battery", sensorData.eventData.battery)
(*writeAPI).WritePoint(point)
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "battery"),
zap.String("measurement_unit", "%"),
zap.Uint8("value", sensorData.eventData.battery))
case temperatureAndHumidityEvent:
sensorData.eventData.temperature = float64(int16(binary.LittleEndian.Uint16(sd.Data[eventOffset+3:]))) / 10.0
sensorData.eventData.humidity = float64(binary.LittleEndian.Uint16(sd.Data[eventOffset+5:])) / 10.0
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
if description != "" {
point.AddTag("description", description)
}
point.AddTag("temperature_unit", "°C")
point.AddField("temperature", sensorData.eventData.temperature)
(*writeAPI).WritePoint(point)
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "temperature"),
zap.String("measurement_unit", "°C"),
zap.Float64("value", sensorData.eventData.temperature))
sensorData.eventData.humidity = float64(binary.LittleEndian.Uint16(sd.Data[eventOffset+5:])) / 10.0
point = influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Addr().String())
point.AddTag("product_id", fmt.Sprintf("%x", sensorData.productID))
if description != "" {
point.AddTag("description", description)
}
point.AddTag("humidity_unit", "%")
point.AddField("humidity", sensorData.eventData.humidity)
(*writeAPI).WritePoint(point)
logger.Debug("sending sensor reading",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("measurement", "humidity"),
zap.String("measurement_unit", "%"),
zap.Float64("value", sensorData.eventData.humidity))
default:
if debug {
fmt.Printf("Unknown event type: %d\n", sensorData.eventData.eventType)
logger.Warn("unknown event type",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.Uint16("event_type", sensorData.eventData.eventType))
}
}
(*writeAPI).WritePoint(point)
}
if debug {
mux.Lock()
fmt.Printf("*******************************************\n")
fmt.Printf("*******************************************\n")
mux.Unlock()
}
}

View file

@ -1,50 +1,21 @@
package scale
import (
"fmt"
"os"
"sync"
"time"
"git.ocjtech.us/jeff/bluelisten/lib/bluetooth"
"github.com/currantlabs/ble"
influxdb2 "github.com/influxdata/influxdb-client-go"
"github.com/go-ble/ble"
influxdb2_api "github.com/influxdata/influxdb-client-go/api"
"go.uber.org/zap"
)
// XiaomiScaleV1UUID is BLE UUID for Xiaomi Scale V1
var XiaomiScaleV1UUID ble.UUID = []byte{0x1d, 0x18}
// ParseXiaomiScaleV1 parses V1 scale service data
func ParseXiaomiScaleV1(mux *sync.Mutex, writeAPI *influxdb2_api.WriteAPI, advertisement ble.Advertisement, index int, sd ble.ServiceData) {
timestamp := time.Now()
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(timestamp)
detector, _ := os.Hostname()
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Address().String())
description := bluetooth.GetDescription(advertisement.Address())
if description != "" {
point.AddTag("description", description)
}
point.AddField("rssi", advertisement.RSSI())
(*writeAPI).WritePoint(point)
mux.Lock()
fmt.Printf("*******************************************\n")
fmt.Printf("Xiaomi V1 Scale\n")
if len(advertisement.LocalName()) > 0 {
fmt.Printf(" Name: %s\n", advertisement.LocalName())
}
if len(advertisement.Services()) > 0 {
fmt.Printf(" Svcs: %v\n", advertisement.Services())
}
if len(advertisement.ManufacturerData()) > 0 {
fmt.Printf(" MD: %v\n", advertisement.ManufacturerData())
}
fmt.Printf(" %d %v %v\n", index, sd.UUID, sd.Data)
fmt.Printf("*******************************************\n")
mux.Unlock()
func ParseXiaomiScaleV1(writeAPI *influxdb2_api.WriteAPI, logger *zap.Logger, timestamp time.Time, detector string, description string, advertisement ble.Advertisement, index int, sd ble.ServiceData) {
logger.Debug("xiaomi v1 scale",
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.String("name", advertisement.LocalName()),
zap.String("uuid", sd.UUID.String()))
}

View file

@ -3,23 +3,20 @@ package scale
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"os"
"sync"
"time"
"github.com/currantlabs/ble"
"github.com/go-ble/ble"
influxdb2 "github.com/influxdata/influxdb-client-go"
influxdb2_api "github.com/influxdata/influxdb-client-go/api"
"go.uber.org/zap"
)
// XiaomiScaleV2UUID is BLE UUID for Xiaomi Scale V2
var XiaomiScaleV2UUID ble.UUID = []byte{0x1b, 0x18}
// ParseXiaomiScaleV2 parses V2 scale service data
func ParseXiaomiScaleV2(mux *sync.Mutex, writeAPI *influxdb2_api.WriteAPI, advertisement ble.Advertisement, index int, sd ble.ServiceData) {
timestamp := time.Now()
func ParseXiaomiScaleV2(writeAPI *influxdb2_api.WriteAPI, logger *zap.Logger, timestamp time.Time, detector string, description string, advertisement ble.Advertisement, index int, sd ble.ServiceData) {
var scaleData struct {
RawUnit uint8
@ -76,50 +73,27 @@ func ParseXiaomiScaleV2(mux *sync.Mutex, writeAPI *influxdb2_api.WriteAPI, adver
point := influxdb2.NewPointWithMeasurement("sensor")
point.SetTime(scaleTimestamp)
hostname, _ := os.Hostname()
if hostname != "" {
point.AddTag("detector", hostname)
if detector != "" {
point.AddTag("detector", detector)
}
point.AddTag("address", advertisement.Address().String())
point.AddTag("address", advertisement.Addr().String())
point.AddTag("weight_unit", "kg")
point.AddTag("original_weight_unit", originalUnit)
point.AddField("rssi", advertisement.RSSI())
point.AddField("time_difference", difference.Seconds())
point.AddField("weight", weight)
if hasImpedance {
point.AddField("impedance", scaleData.Impedance)
}
(*writeAPI).WritePoint(point)
mux.Lock()
fmt.Printf("*******************************************\n")
fmt.Printf("Xiaomi V2 Scale\n")
fmt.Printf("[%s] %3d:\n", advertisement.Address(), advertisement.RSSI())
if len(advertisement.LocalName()) > 0 {
fmt.Printf(" Name: %s\n", advertisement.LocalName())
}
if len(advertisement.Services()) > 0 {
fmt.Printf(" Svcs: %v\n", advertisement.Services())
}
if len(advertisement.ManufacturerData()) > 0 {
fmt.Printf(" MD: %v\n", advertisement.ManufacturerData())
}
fmt.Printf(" rawUnit: %d\n", scaleData.RawUnit)
fmt.Printf(" Control byte: %d %b\n", scaleData.ControlByte, scaleData.ControlByte)
fmt.Printf(" Control byte X: %d\n", scaleData.ControlByte&^(1<<5)&^(1<<1))
fmt.Printf(" Is stabilized: %v\n", isStabilized)
fmt.Printf(" Has impedance: %v\n", hasImpedance)
fmt.Printf(" Year: %d\n", scaleData.Year)
fmt.Printf(" Month: %d\n", scaleData.Month)
fmt.Printf(" Day: %v\n", scaleData.Day)
fmt.Printf(" Hour: %d\n", scaleData.Hour)
fmt.Printf(" Minute: %d\n", scaleData.Minute)
fmt.Printf(" Second: %d\n", scaleData.Second)
fmt.Printf(" Measurement taken %s ago\n", difference)
fmt.Printf(" Impedance: %d\n", scaleData.Impedance)
fmt.Printf(" Raw weight: %d\n", scaleData.RawWeight)
fmt.Printf(" Weight: %f %s\n", weight, originalUnit)
fmt.Printf("*******************************************\n")
mux.Unlock()
logger.Debug("xiaomi v2 scale",
zap.String("name", advertisement.LocalName()),
zap.String("source", advertisement.Addr().String()),
zap.String("description", description),
zap.Bool("is_stabilized", isStabilized),
zap.Bool("has_impedance", hasImpedance),
zap.Float64("weight", weight))
}
}