|
| 1 | +//go:build tinygo && nrf52840 |
| 2 | + |
| 3 | +package ble |
| 4 | + |
| 5 | +import ( |
| 6 | + k "machine/usb/hid/keyboard" |
| 7 | + |
| 8 | + "tinygo.org/x/bluetooth" |
| 9 | +) |
| 10 | + |
| 11 | +var tx = &bluetooth.Characteristic{} |
| 12 | + |
| 13 | +type bleSplitKeyboard struct { |
| 14 | + keyboard |
| 15 | + Name string |
| 16 | + report [9]byte |
| 17 | + pressed []k.Keycode |
| 18 | + connected bool |
| 19 | +} |
| 20 | + |
| 21 | +func NewSplitKeyboard(name string) *bleSplitKeyboard { |
| 22 | + return &bleSplitKeyboard{ |
| 23 | + Name: name, |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +//// SetConnectHandler sets a handler function to be called whenever the adaptor connects |
| 28 | +//// or disconnects. You must call this before you call adaptor.Connect() for centrals |
| 29 | +//// or adaptor.Start() for peripherals in order for it to work. |
| 30 | +//func (a *Adapter) SetConnectHandler(c func(device Address, connected bool)) { |
| 31 | +// a.connectHandler = c |
| 32 | +//} |
| 33 | + |
| 34 | +func (k *bleSplitKeyboard) Connect() error { |
| 35 | + var err error |
| 36 | + |
| 37 | + name := k.Name |
| 38 | + if len(name) > 14 { |
| 39 | + name = name[:14] |
| 40 | + } |
| 41 | + adapter.SetConnectHandler(func(device bluetooth.Address, connected bool) { |
| 42 | + println("connected:", connected) |
| 43 | + }) |
| 44 | + |
| 45 | + adv := adapter.DefaultAdvertisement() |
| 46 | + err = adv.Configure(bluetooth.AdvertisementOptions{ |
| 47 | + LocalName: name, |
| 48 | + }) |
| 49 | + err = adv.Start() |
| 50 | + if err != nil { |
| 51 | + return err |
| 52 | + } |
| 53 | + |
| 54 | + adapter.AddService(&bluetooth.Service{ |
| 55 | + UUID: bluetooth.ServiceUUIDNordicUART, |
| 56 | + Characteristics: []bluetooth.CharacteristicConfig{ |
| 57 | + { |
| 58 | + Handle: tx, |
| 59 | + UUID: bluetooth.CharacteristicUUIDUARTTX, |
| 60 | + Value: k.report[:3], |
| 61 | + Flags: bluetooth.CharacteristicReadPermission | bluetooth.CharacteristicNotifyPermission, |
| 62 | + }, |
| 63 | + }, |
| 64 | + }) |
| 65 | + return nil |
| 66 | +} |
| 67 | + |
| 68 | +func (k *bleSplitKeyboard) Up(c k.Keycode) error { |
| 69 | + for i, p := range k.pressed { |
| 70 | + if c == p { |
| 71 | + k.pressed = append(k.pressed[:i], k.pressed[i+1:]...) |
| 72 | + row := byte(c >> 8) |
| 73 | + col := byte(c) |
| 74 | + _, err := tx.Write([]byte{0x55, byte(row), byte(col)}) |
| 75 | + return err |
| 76 | + } |
| 77 | + } |
| 78 | + return nil |
| 79 | +} |
| 80 | + |
| 81 | +func (k *bleSplitKeyboard) Down(c k.Keycode) error { |
| 82 | + found := false |
| 83 | + for _, p := range k.pressed { |
| 84 | + if c == p { |
| 85 | + found = true |
| 86 | + } |
| 87 | + } |
| 88 | + if !found { |
| 89 | + k.pressed = append(k.pressed, c) |
| 90 | + row := byte(c >> 8) |
| 91 | + col := byte(c) |
| 92 | + _, err := tx.Write([]byte{0xAA, byte(row), byte(col)}) |
| 93 | + return err |
| 94 | + } |
| 95 | + return nil |
| 96 | +} |
0 commit comments