This commit is contained in:
2017-02-06 09:29:32 +03:00
parent d52b9f5aa2
commit 0b43a68046
6 changed files with 284 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceRoot}",
"env": {},
"args": []
}
]
}
+41
View File
@@ -0,0 +1,41 @@
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
{
"version": "0.1.0",
// The command is tsc. Assumes that tsc has been installed using npm install -g typescript
"command": "go",
// The command is a shell script
"isShellCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "always",
"tasks": [
{
// TS build command is local.
"taskName": "build",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "always",
//"args": ["-o", "dict", "-v", "${workspaceRoot}/main.go"]
"args": ["-v"]
},
{
// TS build command is local.
"taskName": "run",
// Make this the default build command.
"isTestCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "always",
"args": ["-v", "${workspaceRoot}/main.go"]
}
]
}
Executable
BIN
View File
Binary file not shown.
+155
View File
@@ -0,0 +1,155 @@
package main
import (
"fmt"
"log"
"strings"
"time"
"github.com/currantlabs/gatt"
"github.com/currantlabs/gatt/examples/option"
)
var done = make(chan struct{})
func onStateChanged(d gatt.Device, s gatt.State) {
fmt.Println("State:", s)
switch s {
case gatt.StatePoweredOn:
fmt.Println("scanning...")
d.Scan([]gatt.UUID{}, false)
return
default:
d.StopScanning()
}
}
func onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int) {
ID := p.ID()
//xiaomi scale
if !strings.HasPrefix(ID, "88:0F:10") {
return
}
fmt.Printf("\nPeripheral ID:%s, NAME:(%s)\n", ID, p.Name())
fmt.Printf("%v+", a)
fmt.Println(" Local Name =", a.LocalName)
fmt.Println(" TX Power Level =", a.TxPowerLevel)
fmt.Println(" Manufacturer Data =", a.ManufacturerData)
fmt.Println(" Service Data =", a.ServiceData)
fmt.Println(" RSSI =", rssi)
p.Device().Connect(p)
}
func onPeriphConnected(p gatt.Peripheral, err error) {
var WEIGHT_MEASUREMENT_SERVICE = gatt.MustParseUUID("181d")
var WEIGHT_MEASUREMENT_HISTORY_CHARACTERISTIC = gatt.MustParseUUID("00002a2f-0000-3512-2118-0009af100700")
var WEIGHT_MEASUREMENT_TIME_CHARACTERISTIC = gatt.MustParseUUID("2a2b")
var WEIGHT_MEASUREMENT_CONFIG = gatt.MustParseUUID("2902")
fmt.Println("Connected")
defer p.Device().CancelConnection(p)
if err := p.SetMTU(500); err != nil {
fmt.Printf("Failed to set MTU, err: %s\n", err)
}
fmt.Printf("Set mtu done.\n")
// Discovery services
services, err := p.DiscoverServices(nil)
fmt.Printf("Services: %v+", services)
if err != nil {
fmt.Printf("Failed to discover services, err: %s\n", err)
return
}
service := getServiceByUUID(WEIGHT_MEASUREMENT_SERVICE, services)
fmt.Printf("Service Found %s\n", service.Name())
chars, _ := p.DiscoverCharacteristics(nil, service)
char := getCharByUUID(WEIGHT_MEASUREMENT_TIME_CHARACTERISTIC, chars)
b, err := p.ReadCharacteristic(char)
if err != nil {
fmt.Printf("Failed to read characteristic, err: %s\n", err)
return
}
fmt.Printf(" value %x | %q\n", b, b)
histChar := getCharByUUID(WEIGHT_MEASUREMENT_HISTORY_CHARACTERISTIC, chars)
descriptors, _ := p.DiscoverDescriptors(nil, histChar)
descriptor := getDescriptorByUUID(WEIGHT_MEASUREMENT_CONFIG, descriptors)
p.WriteDescriptor(descriptor, []byte{0x02, 0x00})
p.SetNotifyValue(histChar, func(c *gatt.Characteristic, b []byte, e error) {
log.Printf("Got back from %s: %#x\n", c.UUID(), b)
//weight :=
if len(b) == 20 {
first := b[0:10]
parseData(first)
second := b[10:20]
parseData(second)
} else if len(b) == 10 {
parseData(b)
}
})
p.WriteCharacteristic(histChar, []byte{0x02}, true)
fmt.Printf("Waiting for 5 seconds to get some notifiations, if any.\n")
time.Sleep(10 * time.Second)
}
func getDescriptorByUUID(uuid gatt.UUID, descriptors []*gatt.Descriptor) *gatt.Descriptor {
for _, descriptor := range descriptors {
if !descriptor.UUID().Equal(uuid) {
continue
}
return descriptor
}
return nil
}
func getServiceByUUID(uuid gatt.UUID, services []*gatt.Service) *gatt.Service {
for _, service := range services {
if !service.UUID().Equal(uuid) {
continue
}
return service
}
return nil
}
func getCharByUUID(uid gatt.UUID, chars []*gatt.Characteristic) *gatt.Characteristic {
for _, c := range chars {
if !c.UUID().Equal(uid) {
continue
}
return c
}
return nil
}
func onPeriphDisconnected(p gatt.Peripheral, err error) {
fmt.Println("Disconnected")
close(done)
}
func main() {
d, err := gatt.NewDevice(option.DefaultClientOptions...)
if err != nil {
log.Fatalf("Failed to open device, err: %s\n", err)
return
}
// Register handlers.
d.Handle(
gatt.PeripheralDiscovered(onPeriphDiscovered),
gatt.PeripheralConnected(onPeriphConnected),
gatt.PeripheralDisconnected(onPeriphDisconnected),
)
d.Init(onStateChanged)
<-done
fmt.Println("Done")
}
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"fmt"
"math"
"time"
)
func parseData(weightBytes []byte) *Weight {
ctrlByte := weightBytes[0]
isWeightRemoved := isBitSet(ctrlByte, 7)
isStabilized := isBitSet(ctrlByte, 5)
isLBSUnit := isBitSet(ctrlByte, 0)
isCattyUnit := isBitSet(ctrlByte, 4)
// fmt.Printf("IsWeightRemoved: %v\n", isWeightRemoved)
// fmt.Printf("6 LSB Unknown: %v\n", isBitSet(ctrlByte, 6))
// fmt.Printf("IsStabilized: %v\n", isStabilized)
// fmt.Printf("IsCattyOrKg: %v\n", isCattyUnit)
// fmt.Printf("3 LSB Unknown: %v\n", isBitSet(ctrlByte, 3))
// fmt.Printf("2 LSB Unknown: %v\n", isBitSet(ctrlByte, 2))
// fmt.Printf("1 LSB Unknown: %v\n", isBitSet(ctrlByte, 1))
// fmt.Printf("IsLBS: %v\n", isLBSUnit)
// // Only if the value is stabilized and the weight is *not* removed, the date is valid
if isStabilized && !isWeightRemoved {
wb4 := int(weightBytes[4])
wb3 := int(weightBytes[3])
year := (wb4<<8 | wb3)
month := int(weightBytes[5])
day := int(weightBytes[6])
hours := int(weightBytes[7])
min := int(weightBytes[8])
sec := int(weightBytes[9])
// Is the year plausible? Check if the year is in the range of 20 years...
now := time.Now()
if math.Abs(float64(now.Year()-year)) > 20 || year > now.Year() {
return nil
}
wb1 := int(weightBytes[1])
wb2 := int(weightBytes[2])
weightVal := 0.0
if isLBSUnit || isCattyUnit {
weightVal = float64(((wb2)<<8)|(wb1)) / 100.0
} else {
weightVal = float64(((wb2)<<8)|(wb1)) / 200.0
}
t := time.Date(year, time.Month(month), day, hours, min, sec, 0, time.Local)
weight := &Weight{Weight: weightVal, Time: t}
// fmt.Printf("Payload is: %#x\n", weightBytes)
fmt.Printf("[+] Year: %v, Month: %v, day: %v, hr: %v, min: %v, sec: %v = %v \n", year, month, day, hours, min, sec, weightVal)
return weight
}
return nil
}
func isBitSet(value byte, bit uint) bool {
return (value & (1 << bit)) != 0
}
+10
View File
@@ -0,0 +1,10 @@
package main
import (
"time"
)
type Weight struct {
Time time.Time
Weight float64
}