|
| 1 | +// example that demonstrates how to create a BLE peripheral device with the Battery Service. |
| 2 | +package main |
| 3 | + |
| 4 | +import ( |
| 5 | + "math/rand" |
| 6 | + "time" |
| 7 | + |
| 8 | + "tinygo.org/x/bluetooth" |
| 9 | +) |
| 10 | + |
| 11 | +var adapter = bluetooth.DefaultAdapter |
| 12 | + |
| 13 | +var ( |
| 14 | + localName = "TinyGo Battery" |
| 15 | + |
| 16 | + batteryLevel uint8 = 75 // 75% |
| 17 | + battery bluetooth.Characteristic |
| 18 | +) |
| 19 | + |
| 20 | +func main() { |
| 21 | + println("starting") |
| 22 | + must("enable BLE stack", adapter.Enable()) |
| 23 | + adv := adapter.DefaultAdvertisement() |
| 24 | + must("config adv", adv.Configure(bluetooth.AdvertisementOptions{ |
| 25 | + LocalName: localName, |
| 26 | + ServiceUUIDs: []bluetooth.UUID{bluetooth.ServiceUUIDBattery}, |
| 27 | + })) |
| 28 | + must("start adv", adv.Start()) |
| 29 | + |
| 30 | + must("add service", adapter.AddService(&bluetooth.Service{ |
| 31 | + UUID: bluetooth.ServiceUUIDBattery, |
| 32 | + Characteristics: []bluetooth.CharacteristicConfig{ |
| 33 | + { |
| 34 | + Handle: &battery, |
| 35 | + UUID: bluetooth.CharacteristicUUIDBatteryLevel, |
| 36 | + Value: []byte{byte(batteryLevel)}, |
| 37 | + Flags: bluetooth.CharacteristicReadPermission | bluetooth.CharacteristicNotifyPermission, |
| 38 | + }, |
| 39 | + }, |
| 40 | + })) |
| 41 | + |
| 42 | + for { |
| 43 | + println("tick", time.Now().Format("04:05.000")) |
| 44 | + |
| 45 | + // random variation in batteryLevel |
| 46 | + batteryLevel = randomInt(65, 85) |
| 47 | + |
| 48 | + // and push the next notification |
| 49 | + battery.Write([]byte{batteryLevel}) |
| 50 | + |
| 51 | + time.Sleep(time.Second) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +func must(action string, err error) { |
| 56 | + if err != nil { |
| 57 | + panic("failed to " + action + ": " + err.Error()) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// Returns an int >= min, < max |
| 62 | +func randomInt(min, max int) uint8 { |
| 63 | + return uint8(min + rand.Intn(max-min)) |
| 64 | +} |
0 commit comments