-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwavesharecloud.go
500 lines (460 loc) · 13.2 KB
/
wavesharecloud.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
491
492
493
494
495
496
497
498
499
500
package wavesharecloud
import (
"bytes"
"encoding/binary"
"fmt"
"image"
"image/color"
"io"
"net"
"strconv"
"strings"
"github.com/MaxHalford/halfgone"
"github.com/disintegration/imaging"
)
// NewLoggingConn returns a new connection that will optionally log all traffic.
func NewLoggingConn(conn net.Conn, debug bool) *LoggingConn {
return &LoggingConn{
Connection: conn,
Debug: debug,
}
}
// LoggingConn is a connection that will optionally log all traffic.
type LoggingConn struct {
Connection net.Conn
Debug bool
}
// Read reads raw data from the connection.
func (lc *LoggingConn) Read(b []byte) (n int, err error) {
n, err = lc.Connection.Read(b)
if lc.Debug {
fmt.Println("< " + string(b))
}
return n, err
}
// Write writes raw data to the connection.
func (lc *LoggingConn) Write(b []byte) (n int, err error) {
if lc.Debug {
fmt.Println("> " + string(b))
}
return lc.Connection.Write(b)
}
// Close closes the connection.
func (lc *LoggingConn) Close() error {
return lc.Connection.Close()
}
// NewDisplay returns a new display, using a width of 400 and a height of 300. If the password is left empty, it is assumed that the display if unlocked.
func NewDisplay(conn io.ReadWriteCloser, password string) *Display {
display := &Display{
Connection: conn,
unlocked: password != "",
Width: 400,
Height: 300,
}
if !display.unlocked {
display.Unlock(password)
}
return display
}
// Display represents the physical display.
type Display struct {
Connection io.ReadWriteCloser
unlocked bool
Width int
Height int
}
// SendCommand sends a command to the display.
func (display *Display) SendCommand(command string) (err error) {
var check uint32
for i := 0; i < len(command); i++ {
check = check ^ uint32(command[i])
}
_, err = display.Connection.Write([]byte(";" + command + "/" + string(rune(check))))
if err != nil {
return err
}
return nil
}
// SendImageBytes displays an array of bytes on the screen.
func (display *Display) SendImageBytes(data []byte) (err error) {
if !display.unlocked {
return fmt.Errorf("display is locked")
}
if len(data) != (display.Width*display.Height)/8 {
return fmt.Errorf("data length does not match display size")
}
err = display.SendCommand("F")
if err != nil {
return err
}
err = display.ReadBlindlyAndIgnore()
if err != nil {
return err
}
var count uint8
for i := 0; i < len(data); i += 1024 {
to := i + 1024
if to > len(data) {
to = len(data)
}
err = display.SendFrame(uint32(i), uint8((uint32(i)%4096)/1024), data[i:to])
if err != nil {
return err
}
err = display.ReadBlindlyAndIgnore()
if err != nil {
return err
}
count++
}
err = display.SendCloseFrame()
if err != nil {
return err
}
err = display.SendCommand("D")
if err != nil {
return err
}
err = display.ReadBlindlyAndIgnore()
if err != nil {
return err
}
return nil
}
// CloseFrame is the last frame to be sent to the display when drawing an image. It is completely empty.
var closeFrame = []byte{
0x57,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0x00,
}
// SendCloseFrame sends the last frame to the display
func (display *Display) SendCloseFrame() (err error) {
if !display.unlocked {
return fmt.Errorf("display is locked")
}
_, err = display.Connection.Write(closeFrame)
if err != nil {
return err
}
// We do not need to know the checksum: it does not matter to displaying the image here.
err = display.ReadBlindlyAndIgnore()
if err != nil {
return err
}
return nil
}
// SendImage converts an image into bytes, then sends it to the display. If the image is not 400x300, it will crop it from the top left. This requires the display to be unlocked.
func (display *Display) SendImage(img image.Image) (err error) {
if !display.unlocked {
return fmt.Errorf("display is locked")
}
var resizedImage image.Image
if (img.Bounds().Dx() < display.Width) || (img.Bounds().Dy() < display.Height) {
return fmt.Errorf("image is too small for cropping, try SendImageScaled")
}
resizedImage, err = cropImage(img, image.Rect(0, 0, display.Width, display.Height))
if err != nil {
return err
}
imageBytes, err := loadImage(resizedImage)
if err != nil {
return err
}
return display.SendImageBytes(imageBytes)
}
// SendImageScaled converts an image into bytes, then sends it to the display. If the image is not 400x300, it will resize it. This requires the display to be unlocked.
func (display *Display) SendImageScaled(img image.Image) (err error) {
if !display.unlocked {
return fmt.Errorf("display is locked")
}
var resizedImage image.Image
resizedImage, err = resizeImage(img, display.Width, display.Height)
if err != nil {
return err
}
imageBytes, err := loadImage(resizedImage)
if err != nil {
return err
}
return display.SendImageBytes(imageBytes)
}
// SendFrame sends a frame of image data to the display. This requires the display to be in data mode.
func (display *Display) SendFrame(addr uint32, num uint8, data []byte) (err error) {
if !display.unlocked {
return fmt.Errorf("display is locked")
}
if len(data) > 1024 {
return fmt.Errorf("data too large, maximum size is 1024")
}
frame := new(bytes.Buffer)
// This is the header of the frame. It includes:
// 0x57 - data identifier
err = binary.Write(frame, binary.BigEndian, uint8(0x57))
if err != nil {
return err
}
// 4 byte addr
err = binary.Write(frame, binary.BigEndian, addr)
if err != nil {
return err
}
// 4 bytes len
err = binary.Write(frame, binary.BigEndian, uint32(1024))
if err != nil {
return err
}
// 1 byte num
err = binary.Write(frame, binary.BigEndian, num)
if err != nil {
return err
}
// This is the data of the frame. It is after the header.
err = binary.Write(frame, binary.BigEndian, data)
if err != nil {
return err
}
// If there are bytes missing in a frame, fill them with 0xFF.
// This should be expected on the final frame, as the avalible pixels on the screen do not divide into 1024 prefectly.
if remaining := 1024 - len(data); remaining > 0 {
remainder := make([]byte, remaining)
for i := 0; i < len(remainder); i++ {
remainder[i] = 0xFF
}
err = binary.Write(frame, binary.BigEndian, remainder)
if err != nil {
return err
}
}
// Calculate the checksum of the frame
var check byte
payload := frame.Bytes()
// The first byte is the 0x57 identifier, so we skip it.
for i := 1; i < len(payload[1:])+1; i++ {
// CheckSum8 Xor
check ^= payload[i]
}
// The checksum byte is the last byte of the frame. It is stored as BigEndian.
err = binary.Write(frame, binary.BigEndian, check)
if err != nil {
return err
}
// Write out the full frame to the display.
display.Connection.Write(frame.Bytes())
return nil
}
// ReceiveCommandOutput receives a previously sent command's output from the display.
func (display *Display) ReceiveCommandOutput(sentCommand string) (data string, err error) {
// The first set of data is the previous command repeated back.
buf := make([]byte, 64)
_, err = display.Connection.Read(buf)
if err != nil {
return "", err
}
command := string(buf)
command = formatTransmissionString(command)
if !strings.Contains(command, sentCommand) {
return "", fmt.Errorf("command mismatch: expected %s, got %v", sentCommand, command)
}
// The second set of data is the output from calling the command.
buf = make([]byte, 64)
_, err = display.Connection.Read(buf)
if err != nil {
return "", err
}
data = string(buf)
data = formatTransmissionString(data)
return data, nil
}
// ReadBlindlyAndIgnore mindlessly reads data from the display and does not do anything wth it.
func (display *Display) ReadBlindlyAndIgnore() (err error) {
buf := make([]byte, 64)
_, err = display.Connection.Read(buf)
if err != nil {
return err
}
return nil
}
// ReadBlindly reads any avalible data from the display and returns it (after formatting).
func (display *Display) ReadBlindly() (data string, err error) {
buf := make([]byte, 64)
_, err = display.Connection.Read(buf)
if err != nil {
return "", err
}
command := string(buf)
command = formatTransmissionString(command)
return command, nil
}
// Restart sends a command to the display to restart it. This requires the device to be unlocked.
func (display *Display) Restart() (err error) {
if !display.unlocked {
return fmt.Errorf("display is locked")
}
display.SendCommand("R")
return nil
}
// GetBatteryLevel sends a command to the display to get its battery level. This requires the device to be unlocked.
func (display *Display) GetBatteryLevel() (batteryLevel int, err error) {
if !display.unlocked {
return 0, fmt.Errorf("display is locked")
}
err = display.SendCommand("b")
if err != nil {
return 0, err
}
batteryLevelString, err := display.ReceiveCommandOutput("b")
if err != nil {
return 0, err
}
batteryLevel, err = strconv.Atoi(batteryLevelString)
if err != nil {
return 0, err
}
return batteryLevel, nil
}
// Shutdown sends a command to the display to shut it down. This requires the device to be unlocked.
func (display *Display) Shutdown() (err error) {
if !display.unlocked {
return fmt.Errorf("display is locked")
}
display.SendCommand("S")
return nil
}
// Disconnect closes the connection to the display
func (display *Display) Disconnect() {
display.Connection.Close()
}
// GetID gets the ID of the display
func (display *Display) GetID() (ID string, err error) {
err = display.SendCommand("G")
if err != nil {
return "", err
}
data, err := display.ReceiveCommandOutput("G")
if err != nil {
return "", err
}
return data, nil
}
// GetLocked gets whether the display is locked with a password
func (display *Display) GetLocked() (unlocked bool, err error) {
err = display.SendCommand("C")
if err != nil {
return false, err
}
data, err := display.ReceiveCommandOutput("C")
if err != nil {
return false, err
}
bytedata := []byte(data)
bytedata = bytes.Trim(bytedata, "\x00")
unlocked, err = strconv.ParseBool(string(bytedata))
if err != nil {
return false, err
}
return unlocked, nil
}
// Unlock unlocks the display with a password. It will error if the display is already unlocked.
func (display *Display) Unlock(password string) (err error) {
err = display.SendCommand("C")
if err != nil {
return err
}
data, err := display.ReceiveCommandOutput("C")
if err != nil {
return err
}
if strings.Contains(data, "1") {
err = display.SendCommand("N" + password)
if err != nil {
return err
}
err = display.ReadBlindlyAndIgnore()
if err != nil {
return err
}
data, err = display.ReadBlindly()
if err != nil {
return err
}
if strings.Contains(data, "1") {
display.unlocked = true
return nil
} else {
return fmt.Errorf("wrong password")
}
} else {
display.unlocked = true
return fmt.Errorf("display is already unlocked")
}
}
// convertImageToBits converts a black and white image to a list of bytes.
func convertImageToBits(img image.Image) []byte {
wh := img.Bounds()
b := make([]byte, (wh.Max.X*wh.Max.Y)/8)
for y := 0; y < wh.Max.Y; y++ {
for x := 0; x < wh.Max.X; x++ {
if r, g, b, _ := img.At(x, y).RGBA(); r == 0 && g == 0 && b == 0 {
continue
}
byteIndex := (y * wh.Max.X / 8) + (x / 8)
bitIndex := 7 - (x % 8)
b[byteIndex] |= (1 << bitIndex)
}
}
return b
}
// convertBitsToImage converts a list of bytes (and the size of the image from the bytes) to a black and white image.
func convertBitsToImage(b []byte, bounds image.Rectangle) (img *image.Gray) {
w, h := bounds.Dx(), bounds.Dy()
img = image.NewGray(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
byteIndex := (y * w / 8) + (x / 8)
bitIndex := x % 8
if hasBit(b[byteIndex], uint(bitIndex)) {
img.Set(x, y, color.White)
continue
}
img.Set(x, y, color.Black)
}
}
return img
}
func hasBit(n byte, pos uint) bool {
val := n & (1 << pos)
return (val > 0)
}
// loadImage takes an image and returns it as a list of black and white, dithered bytes.
func loadImage(img image.Image) (data []byte, err error) {
gray := halfgone.FloydSteinbergDitherer{}.Apply(halfgone.ImageToGray(img))
bytes := convertImageToBits(gray)
return bytes, nil
}
// formatTransmissionString extracts the data from the input and output by removing the leading and trailing characters
func formatTransmissionString(toFormat string) (formatted string) {
toFormat = strings.Replace(toFormat, "$", "", -1)
toFormat = strings.Replace(toFormat, "#", "", -1)
// When reciving the output from a command, there are trailing null caracters that need to be removed.
toFormat = strings.Replace(toFormat, "\x00", "", -1)
return toFormat
}
// resizeImage resizes an image to the given width and height
func resizeImage(img image.Image, width, height int) (resized image.Image, err error) {
resized = imaging.Resize(img, width, height, imaging.Lanczos)
return resized, nil
}
// cropImage takes an image and crops it to the specified rectangle.
func cropImage(img image.Image, crop image.Rectangle) (croppedImage image.Image, err error) {
type subImager interface {
SubImage(r image.Rectangle) image.Image
}
// img is an Image interface. This checks if the underlying value has a
// method called SubImage. If it does, then we can use SubImage to crop the
// image.
simg, ok := img.(subImager)
if !ok {
return nil, fmt.Errorf("image does not support cropping")
}
return simg.SubImage(crop), nil
}