-
Notifications
You must be signed in to change notification settings - Fork 2
/
mask.go
490 lines (392 loc) · 12.2 KB
/
mask.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package mask
import (
"encoding/binary"
"encoding/hex"
"fmt"
"strings"
"time"
logrus "github.com/sirupsen/logrus"
"tinygo.org/x/bluetooth"
)
type uploadBuffer struct {
bitmap []byte
colorArray []byte
completeBuffer []byte
totalLen uint16
bytesSent uint16
packetCount byte
}
var uploadRunning bool
var currentUpload uploadBuffer
var adapter = bluetooth.DefaultAdapter
var btDevice *bluetooth.Device
var genralBtChar *bluetooth.DeviceCharacteristic
var uploadNotificationBtChar *bluetooth.DeviceCharacteristic
var uploadBtChar *bluetooth.DeviceCharacteristic
const btMaxPacketSize int = 100 //packets above this size are not accepted by the mask, relevant for text upload
const btPaddedPacketSize byte = 16
var log logrus.Logger
// InitAndConnect searches and connects to a mask over BLE
// BLE must be enabled
// Blocking until a mask is found
// MoreLogging is showing debug output
func InitAndConnect(MoreLogging bool) error {
log = *logrus.New()
if MoreLogging {
log.SetLevel(logrus.InfoLevel)
} else {
log.SetLevel(logrus.WarnLevel)
}
// Enable BLE interface.
must("enable BLE stack", adapter.Enable())
// Start scanning.
ch := make(chan bluetooth.ScanResult, 1)
log.Info("scanning...")
err := adapter.Scan(func(adapter *bluetooth.Adapter, device bluetooth.ScanResult) {
log.Trace("found device: ", device.Address.String(), device.RSSI, device.LocalName())
if strings.HasPrefix(device.LocalName(), "MASK") {
log.Info("found mask: ", device.LocalName())
adapter.StopScan()
ch <- device
}
})
must("start scan", err)
select {
case result := <-ch:
btDevice, err = adapter.Connect(result.Address, bluetooth.ConnectionParams{})
if err != nil {
log.Error("connection abort: ", err.Error())
return err
}
log.Info("connected to ", result.Address.String())
}
// get services
log.Info("discovering services/characteristics")
//mask service
maskUUID, err := bluetooth.ParseUUID("0000fff0-0000-1000-8000-00805f9b34fb")
must("ParseUUID", err)
srvcs, err := btDevice.DiscoverServices([]bluetooth.UUID{maskUUID})
must("discover services", err)
maskService := srvcs[0]
log.Info("mask svcs", maskService.String())
//setup needed chars
generalUUID, err := bluetooth.ParseUUID("d44bc439-abfd-45a2-b575-925416129600")
must("ParseUUID", err)
uploadNotifyUUID, err := bluetooth.ParseUUID("d44bc439-abfd-45a2-b575-925416129601")
must("ParseUUID", err)
uploadUUID, err := bluetooth.ParseUUID("d44bc439-abfd-45a2-b575-92541612960a")
must("ParseUUID", err)
chars, err := maskService.DiscoverCharacteristics(nil)
if err != nil {
log.Error("disc chars: ", err)
return err
}
for i := range chars {
dc := &chars[i]
log.Info(chars[i].String())
if dc.UUID().String() == generalUUID.String() {
genralBtChar = dc
} else if dc.UUID().String() == uploadNotifyUUID.String() {
uploadNotificationBtChar = dc
} else if dc.UUID().String() == uploadUUID.String() {
uploadBtChar = dc
}
}
if genralBtChar == nil || uploadBtChar == nil || uploadNotificationBtChar == nil {
log.Error("one of the bt chars is nil!")
return fmt.Errorf("bt char is nil")
}
log.Info("generall ", genralBtChar.String())
err = uploadNotificationBtChar.EnableNotifications(maskUploadCallback)
must("mask notify", err)
//reset state
uploadRunning = false
currentUpload = uploadBuffer{}
return nil
}
// disconnects the bt device
func Shutdown() {
if btDevice != nil {
btDevice.Disconnect()
time.Sleep(1 * time.Second)
}
}
// IsConnected checks if a mask is connected
func IsConnected() bool {
return btDevice != nil
}
// Sets the scroll mode
// 01 = steady
// 02 = blink
// 03 = scroll left
// 04 = scroll right
// 05 = steady
func SetMode(mode byte) error {
modeStr := []byte("MODE")
buf := []byte{}
buf = append(buf, 5) //len
buf = append(buf, modeStr...)
buf = append(buf, mode)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// Sets how bright the thing is
func SetLight(brightness byte) error {
modeStr := []byte("LIGHT")
buf := []byte{}
buf = append(buf, 6) //len
buf = append(buf, modeStr...)
buf = append(buf, brightness)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// Sets a static predefined image
func SetImage(image byte) error {
modeStr := []byte("IMAG")
buf := []byte{}
buf = append(buf, 6) //len
buf = append(buf, modeStr...)
buf = append(buf, image)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// Sets static predefined animation
func SetAnimation(image byte) error {
modeStr := []byte("ANIM")
buf := []byte{}
buf = append(buf, 6) //len
buf = append(buf, modeStr...)
buf = append(buf, image)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// Sets DIY iamge
func SetDIYImage(image byte) error {
modeStr := []byte("PLAY")
buf := []byte{}
buf = append(buf, 6) //len
buf = append(buf, modeStr...)
buf = append(buf, byte(1))
buf = append(buf, image)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// Sets speed, range 0-255
func SetTextSpeed(speed byte) error {
modeStr := []byte("SPEED")
buf := []byte{}
buf = append(buf, 6) //len
buf = append(buf, modeStr...)
buf = append(buf, speed)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// For text mode: sets special backgrounds
// mode:
// 00-03= text gradients ()
// 04-07= background image (4 = x mask, 5 = christmas, 6 = love, 7 = scream)
func SetTextColorMode(enable byte, mode byte) error {
modeStr := []byte("M")
buf := []byte{}
buf = append(buf, 3) //len
buf = append(buf, modeStr...)
buf = append(buf, enable)
buf = append(buf, mode)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// Sets a foreground text color in RGB
func SetTextFrontColor(enable byte, r byte, g byte, b byte) error {
modeStr := []byte("FC")
buf := []byte{}
buf = append(buf, 6) //len
buf = append(buf, modeStr...)
buf = append(buf, enable)
buf = append(buf, r)
buf = append(buf, g)
buf = append(buf, b)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// Sets a background text color in RGB
func SetTextBackgroundColor(enable byte, r byte, g byte, b byte) error {
modeStr := []byte("BG")
buf := []byte{}
buf = append(buf, 6) //len
buf = append(buf, modeStr...)
buf = append(buf, enable)
buf = append(buf, r)
buf = append(buf, g)
buf = append(buf, b)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("out: ", buf)
return SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// UPLOAD
/*
UPLOAD PROCESS:
DATS > Mask
Mask > DATSOKP
per packet
Upload ...
Mask > REOK
DATCP > Mask
Mask > DATCPOK
*/
// Comfort function that generates an image/bitmap from an string and starts the upload to the mask
// Text Color=White
func SetText(text string) error {
pixelMap := GetTextImage(text)
bitmap, err := EncodeBitmapForMask(pixelMap)
if err != nil {
return err
}
colorArray := EncodeColorArrayForMask(len(pixelMap))
log.Infof("For text %s: bitmap len %d, color array len %d", text, len(bitmap), len(colorArray))
return InitUpload(bitmap, colorArray)
}
// InitUpload starts the bitmap upload process
func InitUpload(bitmap []byte, colorArray []byte) error {
if !IsConnected() {
return fmt.Errorf("not connected")
}
if uploadRunning {
log.Warn("Mask upload is already running!")
return fmt.Errorf("mask upload already running")
}
//prep struct
currentUpload = uploadBuffer{}
currentUpload.bitmap = bitmap
currentUpload.colorArray = colorArray
currentUpload.totalLen = uint16(len(currentUpload.bitmap) + len(currentUpload.colorArray))
currentUpload.bytesSent = 0
currentUpload.completeBuffer = make([]byte, 0)
currentUpload.completeBuffer = append(currentUpload.completeBuffer, currentUpload.bitmap...)
currentUpload.completeBuffer = append(currentUpload.completeBuffer, currentUpload.colorArray...)
log.Debug("bitmap: ", currentUpload.bitmap)
log.Debug("colorArray: ", currentUpload.colorArray)
//log.Debug("completeBuffer: ", currentUpload.completeBuffer)
//09DATS - 2 byte total len - 2 byte bitmap len
modeStr := []byte("DATS")
buf := []byte{}
buf = append(buf, 9)
buf = append(buf, modeStr...)
intBytes := make([]byte, 2)
binary.BigEndian.PutUint16(intBytes, currentUpload.totalLen)
buf = append(buf, intBytes...)
binary.BigEndian.PutUint16(intBytes, uint16(len(currentUpload.bitmap)))
buf = append(buf, intBytes...)
buf = append(buf, byte(0))
buf = padByteArray(buf, btPaddedPacketSize)
log.Infof("Upload Init upload totlen %d, bit len %d out: %v", currentUpload.totalLen, len(currentUpload.bitmap), buf)
err := SendDataToBtChar(genralBtChar, EncryptAes128(buf))
if err == nil {
uploadRunning = true
}
return err
}
func maskUploadCallback(encBuffer []byte) {
buf := DecryptAes128Ecb(encBuffer)
strLen := buf[0]
resp := string(buf[1 : strLen+1])
log.Infof("Callback data: %v, hex: %s, parsed resp %s", buf, hex.EncodeToString(buf), resp)
if resp == "DATSOK" {
//ok, we can start to send
maskUploadPart()
} else if resp == "REOK" {
if currentUpload.bytesSent < currentUpload.totalLen {
maskUploadPart()
} else {
maskFinishUpload()
}
} else if resp == "DATCPOK" {
//yay we are done
uploadRunning = false
} else if resp == "PLAYOK" {
//do nothing, resp to diy image
} else {
log.Warnf("unknown notify response: %s", resp)
}
}
func maskUploadPart() {
if currentUpload.bytesSent == currentUpload.totalLen {
return
}
var maxSize uint16 = uint16(btMaxPacketSize) - 2
var data []byte
var bytesToSend byte
if currentUpload.bytesSent+maxSize < currentUpload.totalLen {
bytesToSend = byte(maxSize)
} else {
bytesToSend = byte(currentUpload.totalLen - currentUpload.bytesSent)
}
data = make([]byte, bytesToSend)
copy(data, currentUpload.completeBuffer[currentUpload.bytesSent:currentUpload.bytesSent+uint16(bytesToSend)])
buf := []byte{}
buf = append(buf, bytesToSend+1) //len
buf = append(buf, currentUpload.packetCount)
buf = append(buf, data...)
//buf = padByteArray(buf, 100)
log.Infof("upload data pkt %d: len %d, data %s", currentUpload.packetCount, bytesToSend, hex.EncodeToString(buf))
SendDataToBtChar(uploadBtChar, buf)
currentUpload.bytesSent += uint16(bytesToSend)
currentUpload.packetCount += 1
}
func maskFinishUpload() {
modeStr := []byte("DATCP")
buf := []byte{}
buf = append(buf, 5) //len
buf = append(buf, modeStr...)
buf = padByteArray(buf, btPaddedPacketSize)
log.Debug("finish upload out: ", buf)
SendDataToBtChar(genralBtChar, EncryptAes128(buf))
}
// always returns a byte array with specified len
func padByteArray(array []byte, len byte) []byte {
//filling with zeros are a bad pratice, but then again the mask is using aes-ecb lol
out := make([]byte, len)
copy(out, array)
return out
}
// SendRawData sends a byte buffer to genralBtChar (UUID 0x9600)
func SendRawData(sendbuf []byte) error {
return SendDataToBtChar(genralBtChar, sendbuf)
}
// SendRawData sends a byte buffer to the specifed char, breaking it up if the buffer is to big
func SendDataToBtChar(device *bluetooth.DeviceCharacteristic, sendbuf []byte) error {
if device == nil {
log.Error("bt char is not connected or usable")
return fmt.Errorf("bt char is not connected or usable")
}
log.Debugf("sendStuff (len %d): %v\n", len(sendbuf), sendbuf)
// Send the sendbuf after breaking it up in pieces.
for len(sendbuf) != 0 {
// Chop off up to 20 bytes from the sendbuf.
partlen := btMaxPacketSize
if len(sendbuf) < btMaxPacketSize {
partlen = len(sendbuf)
}
part := sendbuf[:partlen]
sendbuf = sendbuf[partlen:]
// This performs a "write command" aka "write without response".
_, err := device.WriteWithoutResponse(part)
if err != nil {
log.Error("could not send: ", err)
return err
}
}
return nil
}
func must(action string, err error) {
if err != nil {
panic("failed to " + action + ": " + err.Error())
}
}