/
notecard.go
1528 lines (1313 loc) · 43.1 KB
/
notecard.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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 Blues Inc. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
package notecard
import (
"bytes"
"fmt"
"hash/crc32"
"io"
"net"
"os"
"os/user"
"strconv"
"strings"
"sync"
"time"
"github.com/blues/note-go/note"
"go.bug.st/serial"
)
// Debug serial I/O
var debugSerialIO = false
// InitialDebugMode is the debug mode that the context is initialized with
var InitialDebugMode = false
// InitialTraceMode is whether or not we will be entering trace mode, to prevent reservationsa
var InitialTraceMode = false
// InitialResetMode says whether or not we should reset the port on entry
var InitialResetMode = true
// Protect against multiple concurrent callers, because across different operating systems it is
// not at all clear that concurrency is allowed on a single I/O device. An exception is made
// for the I2C 'multiport' case (exposed by TransactionRequestToPort) where we allow multiple
// concurrent I2C transactions on a single device. (This capability was needed for the
// Notefarm, but it's unclear if anyone uses this multi-notecard concurrency capability anymore
// now that it's deprecated.)
var (
transLock sync.RWMutex
multiportTransLock [128]sync.RWMutex
)
// SerialTimeoutMs is the response timeout for Notecard serial communications.
var SerialTimeoutMs = 30000
// IgnoreWindowsHWErrSecs is the amount of time to ignore a Windows serial communiction error.
var IgnoreWindowsHWErrSecs = 2
// Module communication interfaces
const (
NotecardInterfaceSerial = "serial"
NotecardInterfaceI2C = "i2c"
NotecardInterfaceLease = "lease"
)
// The number of minutes that we'll round up so that notecard reservations don't thrash
const reservationModulusMinutes = 5
// CardI2CMax controls chunk size that's socially appropriate on the I2C bus.
// It must be 1-253 bytes as per spec (which allows space for the 2-byte header in a 255-byte read)
const CardI2CMax = 253
// The notecard is a real-time device that has a fixed size interrupt buffer. We can push data
// at it far, far faster than it can process it, therefore we push it in segments with a pause
// between each segment.
// CardRequestSerialSegmentMaxLen (golint)
const CardRequestSerialSegmentMaxLen = 250
// CardRequestSerialSegmentDelayMs (golint)
const CardRequestSerialSegmentDelayMs = 250
// CardRequestI2CSegmentMaxLen (golint)
const CardRequestI2CSegmentMaxLen = 250
// CardRequestI2CSegmentDelayMs (golint)
const CardRequestI2CSegmentDelayMs = 250
// RequestSegmentMaxLen (golint)
var RequestSegmentMaxLen = -1
// RequestSegmentDelayMs (golint)
var RequestSegmentDelayMs = -1
var DoNotReterminateJSON = false
// Transaction retry logic
const requestRetriesAllowed = 5
// IoErrorIsRecoverable is a configuration parameter describing library capabilities.
// Set this to true if the error recovery of the implementation supports re-open. On all implementations
// tested to date, I can't yet get the close/reopen working the way it does on microcontrollers. For
// example, on the go serial, I get a nil pointer dereference within the go library. This MAY have
// soemthing to do with the fact that we don't cleanly implement the shutdown/restart of the inputHandler
// in trace, in which case that should be fixed. In the meantime, this is disabled.
const IoErrorIsRecoverable = true
// Context for the port that is open
type Context struct {
// True to emit trace output
Debug bool
// Pretty-print trace output JSON
Pretty bool
// Disable generation of User Agent object
DisableUA bool
// Reset should be done on next transaction
resetRequired bool
reopenRequired bool
reopenBecauseOfOpen bool
// Sequence number
lastRequestSeqno int
// Class functions
PortEnumFn func() (allports []string, usbports []string, notecardports []string, err error)
PortDefaultsFn func() (port string, portConfig int)
CloseFn func(context *Context)
ReopenFn func(context *Context, portConfig int) (err error)
ResetFn func(context *Context, portConfig int) (err error)
TransactionFn func(context *Context, portConfig int, noResponse bool, reqJSON []byte) (rspJSON []byte, err error)
// Trace functions
traceOpenFn func(context *Context) (err error)
traceReadFn func(context *Context) (data []byte, err error)
traceWriteFn func(context *Context, data []byte)
// Port data
iface string
isLocal bool
port string
portConfig int
portIsOpen bool
// Serial instance state
isSerial bool
serialPort serial.Port
serialUseDefault bool
serialName string
serialConfig serial.Mode
// Serial I/O timeout helpers
ioStartSignal chan int
ioCompleteSignal chan bool
ioTimeoutSignal chan bool
// I2C
i2cMultiport bool
// Lease state
leaseScope string
leaseExpires int64
leaseLessor string
leaseDeviceUID string
leaseTraceConn net.Conn
}
// Report a critical card error
func cardReportError(context *Context, err error) {
if context == nil {
return
}
if context.Debug {
fmt.Printf("*** %s\n", err)
}
if IoErrorIsRecoverable {
time.Sleep(500 * time.Millisecond)
context.reopenRequired = true
}
}
// DebugOutput enables/disables debug output
func (context *Context) DebugOutput(enabled bool, pretty bool) {
context.Debug = enabled
context.Pretty = pretty
}
// EnumPorts returns the list of all available ports on the specified interface
func (context *Context) EnumPorts() (allports []string, usbports []string, notecardports []string, err error) {
if context.PortEnumFn == nil {
return
}
return context.PortEnumFn()
}
// PortDefaults gets the defaults for the specified port
func (context *Context) PortDefaults() (port string, portConfig int) {
if context.PortDefaultsFn == nil {
return
}
return context.PortDefaultsFn()
}
// Identify this Notecard connection
func (context *Context) Identify() (protocol string, port string, portConfig int) {
if context.isSerial {
return "serial", context.serialName, context.serialConfig.BaudRate
}
return "I2C", context.port, context.portConfig
}
// Defaults gets the default interface, port, and config
func Defaults() (moduleInterface string, port string, portConfig int) {
moduleInterface = NotecardInterfaceSerial
port, portConfig = serialDefault()
return
}
// Open the card to establish communications
func Open(moduleInterface string, port string, portConfig int) (context *Context, err error) {
if moduleInterface == "" {
moduleInterface, _, _ = Defaults()
}
switch moduleInterface {
case NotecardInterfaceSerial:
context, err = OpenSerial(port, portConfig)
context.isLocal = true
case NotecardInterfaceI2C:
context, err = OpenI2C(port, portConfig)
context.isLocal = true
case NotecardInterfaceLease:
context, err = OpenLease(port, portConfig)
default:
err = fmt.Errorf("unknown interface: %s", moduleInterface)
}
if err != nil {
cardReportError(nil, err)
err = fmt.Errorf("error opening port: %s %s", err, note.ErrCardIo)
return
}
context.iface = moduleInterface
return
}
// Reset serial to a known state
func cardResetSerial(context *Context, portConfig int) (err error) {
// Exit if not open
if !context.portIsOpen {
err = fmt.Errorf("port not open " + note.ErrCardIo)
cardReportError(context, err)
return
}
// In order to ensure that we're not getting the reply to a failed
// transaction from a prior session, drain any pending input prior
// to transmitting a command. Note that we use this technique of
// looking for a known reply to \n, rather than just "draining
// anything pending on serial", because the nature of read() is
// that it blocks (until timeout) if there's nothing available.
var length int
buf := make([]byte, 2048)
for {
if debugSerialIO {
fmt.Printf("cardResetSerial: about to write newline\n")
}
serialIOBegin(context)
_, err = context.serialPort.Write([]byte("\n"))
err = serialIOEnd(context, err)
if debugSerialIO {
fmt.Printf(" back with err = %v\n", err)
}
if err != nil {
err = fmt.Errorf("error transmitting to module: %s %s", err, note.ErrCardIo)
cardReportError(context, err)
return
}
time.Sleep(750 * time.Millisecond)
if debugSerialIO {
fmt.Printf("cardResetSerial: about to read up to %d bytes\n", len(buf))
}
readBeganMs := int(time.Now().UnixNano() / 1000000)
serialIOBegin(context)
length, err = context.serialPort.Read(buf)
err = serialIOEnd(context, err)
readElapsedMs := int(time.Now().UnixNano()/1000000) - readBeganMs
if debugSerialIO {
fmt.Printf(" back after %d ms with len = %d err = %v\n", readElapsedMs, length, err)
}
if readElapsedMs == 0 && length == 0 && err == io.EOF {
// On Linux, hardware port failures come back simply as immediate EOF
err = fmt.Errorf("hardware failure")
}
if err != nil {
err = fmt.Errorf("error reading from module after reset: %s %s", err, note.ErrCardIo)
cardReportError(context, err)
return
}
somethingFound := false
nonCRLFFound := false
for i := 0; i < length && !nonCRLFFound; i++ {
if false {
fmt.Printf("chr: 0x%02x '%c'\n", buf[i], buf[i])
}
if buf[i] != '\r' {
somethingFound = true
if buf[i] != '\n' {
nonCRLFFound = true
}
}
}
if somethingFound && !nonCRLFFound {
break
}
}
// Done
return
}
// Serial I/O timeout helper function for Windows
func serialTimeoutHelper(context *Context, portConfig int) {
for {
timeoutMs := <-context.ioStartSignal
timeout := false
select {
case <-context.ioCompleteSignal:
case <-time.After(time.Duration(timeoutMs) * time.Millisecond):
timeout = true
if debugSerialIO {
fmt.Printf("serialTimeoutHelper: timeout\n")
}
cardCloseSerial(context)
}
context.ioTimeoutSignal <- timeout
}
}
// Begin a serial I/O
func serialIOBegin(context *Context) {
timeoutMs := SerialTimeoutMs
context.ioStartSignal <- timeoutMs
if debugSerialIO {
if !context.portIsOpen {
fmt.Printf("serialIoBegin: WARNING: PORT NOT OPEN\n")
}
fmt.Printf("serialIOBegin: begin timeout of %d ms\n", timeoutMs)
}
}
// End a serial I/O
func serialIOEnd(context *Context, errIn error) (errOut error) {
errOut = errIn
context.ioCompleteSignal <- true
timeout := <-context.ioTimeoutSignal
select {
case <-context.ioCompleteSignal:
if debugSerialIO {
fmt.Printf("serialIOEnd: ioComplete ate the completed signal (timeout: %v)\n", timeout)
}
default:
if debugSerialIO {
fmt.Printf("serialIOEnd: ioComplete nothing to eat (timeout: %v)\n", timeout)
}
}
if timeout {
errOut = fmt.Errorf("serial I/O timeout %s", note.ErrCardIo)
}
return
}
// OpenSerial opens the card on serial
func OpenSerial(port string, portConfig int) (context *Context, err error) {
// Create the context structure
context = &Context{}
context.Debug = InitialDebugMode
context.port = port
context.portConfig = portConfig
context.lastRequestSeqno = 0
// Set up class functions
context.PortEnumFn = serialPortEnum
context.PortDefaultsFn = serialDefault
context.CloseFn = cardCloseSerial
context.ReopenFn = cardReopenSerial
context.ResetFn = cardResetSerial
context.TransactionFn = cardTransactionSerial
context.traceOpenFn = serialTraceOpen
context.traceReadFn = serialTraceRead
context.traceWriteFn = serialTraceWrite
// Record serial configuration, and whether or not we are using the default
context.isSerial = true
if port == "" {
context.serialUseDefault = true
context.serialName, context.serialConfig.BaudRate = serialDefault()
} else {
context.serialName = port
context.serialConfig.BaudRate = portConfig
}
// Set up I/O port close channels, because Windows needs a bit of help in timing out I/O's.
context.ioStartSignal = make(chan int, 1)
context.ioCompleteSignal = make(chan bool, 1)
context.ioTimeoutSignal = make(chan bool, 1)
go serialTimeoutHelper(context, portConfig)
// For serial, we defer the port open until the first transaction so that we can
// support the concept of dynamically inserted devices, as in "notecard -scan" mode.
context.reopenBecauseOfOpen = true
context.reopenRequired = true
// All set
return
}
// Reset I2C to a known good state
func cardResetI2C(context *Context, portConfig int) (err error) {
// Synchronize by guaranteeing not only that I2C works, but that we drain the remainder of any
// pending partial reply from a previously-aborted session.
chunklen := 0
for {
// Read the next chunk of available data
_, available, err2 := i2cReadBytes(chunklen, portConfig)
if err2 != nil {
err = fmt.Errorf("error reading chunk: %s %s", err2, note.ErrCardIo)
return
}
// If nothing left, we're ready to transmit a command to receive the data
if available == 0 {
break
}
// For the next iteration, reaad the min of what's available and what we're permitted to read
chunklen = available
if chunklen > CardI2CMax {
chunklen = CardI2CMax
}
}
// Done
return
}
// OpenI2C opens the card on I2C
func OpenI2C(port string, portConfig int) (context *Context, err error) {
// Create the context structure
context = &Context{}
context.Debug = InitialDebugMode
context.lastRequestSeqno = 0
// Open
context.portIsOpen = false
// Use default if not specified
if port == "" {
port, portConfig = i2cDefault()
}
context.port = port
context.portConfig = portConfig
// Set up class functions
context.PortEnumFn = i2cPortEnum
context.PortDefaultsFn = i2cDefault
context.CloseFn = cardCloseI2C
context.ReopenFn = cardReopenI2C
context.ResetFn = cardResetI2C
context.TransactionFn = cardTransactionI2C
// Open the I2C port
err = i2cOpen(port, portConfig)
if err != nil {
if false {
ports, _, _, _ := I2CPorts()
fmt.Printf("Available ports: %v\n", ports)
}
err = fmt.Errorf("i2c init error: %s", err)
return
}
// Open
context.portIsOpen = true
// Done
return
}
// Reset the port
func (context *Context) Reset(portConfig int) (err error) {
context.resetRequired = false
if context.ResetFn == nil {
return
}
return context.ResetFn(context, portConfig)
}
// Close the port
func (context *Context) Close() {
context.CloseFn(context)
}
// Close serial
func cardCloseSerial(context *Context) {
if !context.portIsOpen {
if debugSerialIO {
fmt.Printf("cardCloseSerial: port not open\n")
}
} else {
if debugSerialIO {
fmt.Printf("cardCloseSerial: closed\n")
}
context.serialPort.Close()
context.portIsOpen = false
}
}
// Close I2C
func cardCloseI2C(context *Context) {
i2cClose()
context.portIsOpen = false
}
// ReopenIfRequired reopens the port but only if required
func (context *Context) ReopenIfRequired(portConfig int) (err error) {
if context.reopenRequired {
err = context.ReopenFn(context, portConfig)
}
return
}
// Reopen the port
func (context *Context) Reopen(portConfig int) (err error) {
context.reopenRequired = false
err = context.ReopenFn(context, portConfig)
return
}
// Reopen serial
func cardReopenSerial(context *Context, portConfig int) (err error) {
// Close if open
cardCloseSerial(context)
// Handle deferred insertion
if context.serialUseDefault {
context.serialName, context.serialConfig.BaudRate = serialDefault()
}
if context.serialName == "" {
return fmt.Errorf("error opening serial port: serial device not available %s", note.ErrCardIo)
}
// Set default speed if not set
if context.serialConfig.BaudRate == 0 {
_, context.serialConfig.BaudRate = serialDefault()
}
// Open the serial port
if debugSerialIO {
fmt.Printf("cardReopenSerial: about to open '%s'\n", context.serialName)
}
context.serialPort, err = serial.Open(context.serialName, &context.serialConfig)
if debugSerialIO {
fmt.Printf(" back with err = %v\n", err)
}
if err != nil {
return fmt.Errorf("error opening serial port %s at %d: %s %s", context.serialName, context.serialConfig.BaudRate, err, note.ErrCardIo)
}
context.portIsOpen = true
// Done with the reopen
context.reopenRequired = false
// Unless we've been instructed not to reset on open, reset serial to a known good state
if context.reopenBecauseOfOpen && InitialResetMode {
err = cardResetSerial(context, portConfig)
}
context.reopenBecauseOfOpen = false
// Done
return err
}
// Reopen I2C
func cardReopenI2C(context *Context, portConfig int) (err error) {
fmt.Printf("error i2c reopen not yet supported since I can't test it yet\n")
return
}
// SerialDefaults returns the default serial parameters
func SerialDefaults() (port string, portConfig int) {
return serialDefault()
}
// I2CDefaults returns the default serial parameters
func I2CDefaults() (port string, portConfig int) {
return i2cDefault()
}
// SerialPorts returns the list of available serial ports
func SerialPorts() (allports []string, usbports []string, notecardports []string, err error) {
return serialPortEnum()
}
// I2CPorts returns the list of available I2C ports
func I2CPorts() (allports []string, usbports []string, notecardports []string, err error) {
return i2cPortEnum()
}
// TransactionRequest performs a card transaction with a Req structure
func (context *Context) TransactionRequest(req Request) (rsp Request, err error) {
return context.transactionRequest(req, false, 0)
}
// TransactionRequestToPort performs a card transaction with a Req structure, to a specified port
func (context *Context) TransactionRequestToPort(req Request, portConfig int) (rsp Request, err error) {
return context.transactionRequest(req, true, portConfig)
}
// transactionRequest performs a card transaction with a Req structure, to the current or specified port
func (context *Context) transactionRequest(req Request, multiport bool, portConfig int) (rsp Request, err error) {
reqJSON, err2 := note.JSONMarshal(req)
if err2 != nil {
err = fmt.Errorf("error marshaling request for module: %s", err2)
return
}
var rspJSON []byte
rspJSON, err = context.transactionJSON(reqJSON, multiport, portConfig)
if err != nil {
// Give transaction's error precedence, except that if we get an error unmarshaling
// we want to make sure that we indicate to the caller that there was an I/O error (corruption)
err2 := note.JSONUnmarshal(rspJSON, &rsp)
if err2 != nil {
err = fmt.Errorf("%s %s", err, note.ErrCardIo)
}
return
}
err = note.JSONUnmarshal(rspJSON, &rsp)
if err != nil {
err = fmt.Errorf("error unmarshaling reply from module: %s %s: %s", err, note.ErrCardIo, rspJSON)
}
return
}
// NewRequest creates a new request that is guaranteed to get a response
// from the Notecard. Note that this method is provided merely as syntactic sugar, as of the form
// req := notecard.NewRequest("note.add")
func NewRequest(reqType string) (req map[string]interface{}) {
return map[string]interface{}{
"req": reqType,
}
}
// NewCommand creates a new command that requires no response from the notecard.
func NewCommand(reqType string) (cmd map[string]interface{}) {
return map[string]interface{}{
"cmd": reqType,
}
}
// NewBody creates a new body. Note that this method is provided
// merely as syntactic sugar, as of the form
// body := note.NewBody()
func NewBody() (body map[string]interface{}) {
return make(map[string]interface{})
}
// Request performs a card transaction with a JSON structure and doesn't return a response
// (This is for semantic compatibility with other languages.)
func (context *Context) Request(req map[string]interface{}) (err error) {
_, err = context.Transaction(req)
return
}
// RequestResponse performs a card transaction with a JSON structure and doesn't return a response
// (This is for semantic compatibility with other languages.)
func (context *Context) RequestResponse(req map[string]interface{}) (rsp map[string]interface{}, err error) {
return context.Transaction(req)
}
// Response is used in rare cases where there is a transaction that returns multiple responses
func (context *Context) Response() (rsp map[string]interface{}, err error) {
return context.Transaction(nil)
}
// Transaction performs a card transaction with a JSON structure
func (context *Context) Transaction(req map[string]interface{}) (rsp map[string]interface{}, err error) {
// Handle the special case where we are just processing a response
var reqJSON []byte
if req == nil {
reqJSON = []byte("")
} else {
// Marshal the request to JSON
reqJSON, err = note.JSONMarshal(req)
if err != nil {
err = fmt.Errorf("error marshaling request for module: %s", err)
return
}
}
// Perform the transaction
rspJSON, err2 := context.TransactionJSON(reqJSON)
if err2 != nil {
err = fmt.Errorf("error from TransactionJSON: %s", err2)
return
}
// Unmarshal for convenience of the caller
err = note.JSONUnmarshal(rspJSON, &rsp)
if err != nil {
err = fmt.Errorf("error unmarshaling reply from module: %s %s: %s", err, note.ErrCardIo, rspJSON)
return
}
// Done
return
}
// ReceiveBytes receives arbitrary Bytes from the Notecard
func (context *Context) ReceiveBytes() (rspBytes []byte, err error) {
return context.receiveBytes(0)
}
// SendBytes sends arbitrary Bytes to the Notecard
func (context *Context) SendBytes(reqBytes []byte) (err error) {
// Only operate on port 0
portConfig := 0
// Only one caller at a time accessing the I/O port
lockTrans(false, portConfig)
// Reopen if error
err = context.ReopenIfRequired(portConfig)
if err != nil {
unlockTrans(false, portConfig)
return
}
// Do a reset if one was pending
if context.resetRequired {
context.Reset(portConfig)
}
// Do the send, with no response requested
_, err = context.TransactionFn(context, portConfig, true, reqBytes)
// Done
unlockTrans(false, portConfig)
return
}
// receiveBytes receives arbitrary Bytes from the Notecard, using the current or specified port
func (context *Context) receiveBytes(portConfig int) (rspBytes []byte, err error) {
// Only one caller at a time accessing the I/O port
lockTrans(false, portConfig)
// Reopen if error
err = context.ReopenIfRequired(portConfig)
if err != nil {
unlockTrans(false, portConfig)
if context.Debug {
fmt.Printf("%s\n", err)
}
return
}
// Do a reset if one was pending
if context.resetRequired {
context.Reset(portConfig)
}
// Request is empty
var reqBytes []byte
// Perform the transaction
rspBytes, err = context.TransactionFn(context, portConfig, false, reqBytes)
unlockTrans(false, portConfig)
// Done
return
}
// TransactionJSON performs a card transaction using raw JSON []bytes
func (context *Context) TransactionJSON(reqJSON []byte) (rspJSON []byte, err error) {
return context.transactionJSON(reqJSON, false, 0)
}
// TransactionJSONToPort performs a card transaction using raw JSON []bytes to a specified port
func (context *Context) TransactionJSONToPort(reqJSON []byte, portConfig int) (rspJSON []byte, err error) {
return context.transactionJSON(reqJSON, true, portConfig)
}
// transactionJSON performs a card transaction using raw JSON []bytes, to the current or specified port
func (context *Context) transactionJSON(reqJSON []byte, multiport bool, portConfig int) (rspJSON []byte, err error) {
// Remember in the context if we've ever seen multiport I/O, for timeout computation
if multiport {
context.i2cMultiport = true
}
// Unmarshal the request to peek inside it. Also, accept a zero-length request as a valid case
// because we use this in the test fixture where we just accept pure responses w/o requests.
var req Request
var noResponseRequested bool
if len(reqJSON) > 0 {
// Make sure that it is valid JSON, because the transports won't validate this
// and they may misbehave if they do not get a valid JSON response back.
err = note.JSONUnmarshal(reqJSON, &req)
if err != nil {
return
}
// If this is a hub.set, generate a user agent object if one hasn't already been supplied
if !context.DisableUA && (req.Req == ReqHubSet || req.Cmd == ReqHubSet) && req.Body == nil {
ua := context.UserAgent()
if ua != nil {
req.Body = &ua
reqJSON, _ = note.JSONMarshal(req)
}
}
// Determine whether or not a response will be expected from the notecard by
// examining the req and cmd fields
noResponseRequested = req.Req == "" && req.Cmd != ""
if !DoNotReterminateJSON {
// Make sure that the JSON has a single \n terminator
for {
if strings.HasSuffix(string(reqJSON), "\n") {
reqJSON = []byte(strings.TrimSuffix(string(reqJSON), "\n"))
continue
}
if strings.HasSuffix(string(reqJSON), "\r") {
reqJSON = []byte(strings.TrimSuffix(string(reqJSON), "\r"))
continue
}
break
}
reqJSON = []byte(string(reqJSON) + "\n")
}
}
// Debug
if context.Debug {
var j []byte
if context.Pretty {
j, _ = note.JSONMarshalIndent(req, "", " ")
} else {
j, _ = note.JSONMarshal(req)
}
fmt.Printf("%s\n", string(j))
}
// If it is a request (as opposed to a command), include a CRC so that the
// request might be retried if it is received in a corrupted state. (We can
// only do this on requests because for cmd's there is no 'response channel'
// where we can find out that the cmd failed. Note that a Seqno is included
// as part of the CRC data so that two identical requests occurring within the
// modulus of seqno never are mistaken as being the same request being retried.
lastRequestRetries := 0
lastRequestCrcAdded := false
if !noResponseRequested {
reqJSON = crcAdd(reqJSON, context.lastRequestSeqno)
lastRequestCrcAdded = true
}
// Only one caller at a time accessing the I/O port
lockTrans(multiport, portConfig)
// Transaction retry loop. Note that "err" must be set before breaking out of loop
err = nil
for {
if lastRequestRetries > requestRetriesAllowed {
break
}
// Only do reopen/reset in the single-port case, because we may not be talking to the port in error
if !multiport {
// Reopen if error
err = context.ReopenIfRequired(portConfig)
if err != nil {
unlockTrans(multiport, portConfig)
if context.Debug {
fmt.Printf("%s\n", err)
}
return
}
// Do a reset if one was pending
if context.resetRequired {
context.Reset(portConfig)
}
}
// Perform the transaction
rspJSON, err = context.TransactionFn(context, portConfig, noResponseRequested, reqJSON)
if err != nil {
// We can defer the error if a single port, but we need to reset it NOW if multiport
if multiport {
if context.ResetFn != nil {
context.ResetFn(context, portConfig)
}
} else {
context.resetRequired = true
}
}
// If no response expected, we won't be retrying
if noResponseRequested {
break
}
// Decode the response to create an error if the response JSON was badly formatted.
// do this because it's SUPER inconvenient to always be checking for a response error
// vs an error on the transaction itself
if err == nil {
var rsp Request
err = note.JSONUnmarshal(rspJSON, &rsp)
if err != nil {
err = fmt.Errorf("error unmarshaling reply from module: %s %s: %s", err, note.ErrCardIo, rspJSON)
} else {
if rsp.Err != "" {
if req.Req == "" {
err = fmt.Errorf("%s", rsp.Err)
} else {
err = fmt.Errorf("%s: %s", req.Req, rsp.Err)
}
}
}
}
// Don't retry these transactions for obvious reasons
if req.Req == ReqCardRestore || req.Req == ReqCardRestart {
break
}
// If an I/O error, retry
if note.ErrorContains(err, note.ErrCardIo) && !note.ErrorContains(err, note.ErrReqNotSupported) {
// We can defer the error if a single port, but we need to reset it NOW if multiport
if multiport {
if context.ResetFn != nil {
context.ResetFn(context, portConfig)
}
} else {
context.resetRequired = true
}
lastRequestRetries++
if context.Debug {
fmt.Printf("retrying I/O error detected by host: %s\n", err)
}
time.Sleep(500 * time.Millisecond)
continue
}
// If an error, stop transaction processing here
if err != nil {
break
}
// If we sent a CRC in the request, examine the response JSON to see if
// it has a CRC error. Note that the CRC is stripped from the
// rspJSON as a side-effect of this method.
if lastRequestCrcAdded {
rspJSON, err = crcError(rspJSON, context.lastRequestSeqno)
if err != nil {
lastRequestRetries++
if context.Debug {
fmt.Printf("retrying: %s\n", err)
}
time.Sleep(500 * time.Millisecond)
continue
}
}
// Transaction completed
break
}
// Bump the request sequence number now that we've processed this request, success or error
context.lastRequestSeqno++
// If this was a card restore, we want to hold everyone back if we reset the card if it
// isn't a multiport case. But in multiport, we only want to hold this caller back.
if (req.Req == ReqCardRestore) && req.Reset {
// Special case card.restore, reset:true does not cause a reboot.
unlockTrans(multiport, portConfig)
} else if context.isLocal && (req.Req == ReqCardRestore || req.Req == ReqCardRestart) {
if multiport {
unlockTrans(multiport, portConfig)
time.Sleep(12 * time.Second)
} else {
context.reopenRequired = true