-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathMicroBitSerial.cpp
1128 lines (943 loc) · 33.4 KB
/
MicroBitSerial.cpp
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
/*
The MIT License (MIT)
Copyright (c) 2016 British Broadcasting Corporation.
This software is provided by Lancaster University by arrangement with the BBC.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "mbed.h"
#include "MicroBitSerial.h"
#include "ErrorNo.h"
#include "MicroBitComponent.h"
#include "MicroBitFiber.h"
#include "NotifyEvents.h"
uint8_t MicroBitSerial::status = 0;
int MicroBitSerial::baudrate = 0;
/**
* Constructor.
* Create an instance of MicroBitSerial
*
* @param tx the Pin to be used for transmission
*
* @param rx the Pin to be used for receiving data
*
* @param rxBufferSize the size of the buffer to be used for receiving bytes
*
* @param txBufferSize the size of the buffer to be used for transmitting bytes
*
* @code
* MicroBitSerial serial(USBTX, USBRX);
* @endcode
* @note the default baud rate is 115200. More API details can be found:
* -https://github.com/mbedmicro/mbed/blob/master/libraries/mbed/api/SerialBase.h
* -https://github.com/mbedmicro/mbed/blob/master/libraries/mbed/api/RawSerial.h
*
* Buffers aren't allocated until the first send or receive respectively.
*/
MicroBitSerial::MicroBitSerial(PinName tx, PinName rx, uint8_t rxBufferSize, uint8_t txBufferSize) : RawSerial(tx,rx), delimeters()
{
// + 1 so there is a usable buffer size, of the size the user requested.
this->rxBuffSize = rxBufferSize + 1;
this->txBuffSize = txBufferSize + 1;
this->rxBuff = NULL;
this->txBuff = NULL;
this->rxBuffHead = 0;
this->rxBuffTail = 0;
this->txBuffHead = 0;
this->txBuffTail = 0;
this->rxBuffHeadMatch = -1;
this->baud(MICROBIT_SERIAL_DEFAULT_BAUD_RATE);
#if CONFIG_ENABLED(MICROBIT_DBG)
SERIAL_DEBUG = this;
#endif
}
/**
* An internal interrupt callback for MicroBitSerial configured for when a
* character is received.
*
* Each time a character is received fill our circular buffer!
*/
void MicroBitSerial::dataReceived()
{
//get the received character
//Note: always read from the serial to clear the RX interrupt
char c = getc();
if(!(status & MICROBIT_SERIAL_RX_BUFF_INIT))
return;
int delimeterOffset = 0;
int delimLength = this->delimeters.length();
//iterate through our delimeters (if any) to see if there is a match
while(delimeterOffset < delimLength)
{
//fire an event if there is to block any waiting fibers
if(this->delimeters.charAt(delimeterOffset) == c)
MicroBitEvent(MICROBIT_ID_SERIAL, MICROBIT_SERIAL_EVT_DELIM_MATCH);
delimeterOffset++;
}
uint16_t newHead = (rxBuffHead + 1) % rxBuffSize;
//look ahead to our newHead value to see if we are about to collide with the tail
if(newHead != rxBuffTail)
{
//if we are not, store the character, and update our actual head.
this->rxBuff[rxBuffHead] = c;
rxBuffHead = newHead;
//if we have any fibers waiting for a specific number of characters, unblock them
if(rxBuffHeadMatch >= 0)
if(rxBuffHead == rxBuffHeadMatch)
{
rxBuffHeadMatch = -1;
MicroBitEvent(MICROBIT_ID_SERIAL, MICROBIT_SERIAL_EVT_HEAD_MATCH);
}
}
else
//otherwise, our buffer is full, send an event to the user...
MicroBitEvent(MICROBIT_ID_SERIAL, MICROBIT_SERIAL_EVT_RX_FULL);
}
/**
* An internal interrupt callback for MicroBitSerial.
*
* Each time the Serial module's buffer is empty, write a character if we have
* characters to write.
*/
void MicroBitSerial::dataWritten()
{
if(txBuffTail == txBuffHead || !(status & MICROBIT_SERIAL_TX_BUFF_INIT))
return;
//send our current char
putc(txBuff[txBuffTail]);
uint16_t nextTail = (txBuffTail + 1) % txBuffSize;
//unblock any waiting fibers that are waiting for transmission to finish.
if(nextTail == txBuffHead)
{
MicroBitEvent(MICROBIT_ID_NOTIFY, MICROBIT_SERIAL_EVT_TX_EMPTY);
detach(Serial::TxIrq);
}
//update our tail!
txBuffTail = nextTail;
}
/**
* An internal method to configure an interrupt on tx buffer and also
* a best effort copy operation to move bytes from a user buffer to our txBuff
*
* @param string a pointer to the first character of the users' buffer.
*
* @param len the length of the string, and ultimately the maximum number of bytes
* that will be copied dependent on the state of txBuff
*
* @param mode determines whether to configure the current fiber context or not. If
* The mode is SYNC_SPINWAIT, the context will not be configured, otherwise
* no context will be configured.
*
* @return the number of bytes copied into the buffer.
*/
int MicroBitSerial::setTxInterrupt(uint8_t *string, int len, MicroBitSerialMode mode)
{
int copiedBytes = 0;
for(copiedBytes = 0; copiedBytes < len; copiedBytes++)
{
uint16_t nextHead = (txBuffHead + 1) % txBuffSize;
if(nextHead != txBuffTail)
{
this->txBuff[txBuffHead] = string[copiedBytes];
txBuffHead = nextHead;
}
else
break;
}
if(mode != SYNC_SPINWAIT)
fiber_wake_on_event(MICROBIT_ID_NOTIFY, MICROBIT_SERIAL_EVT_TX_EMPTY);
//set the TX interrupt
attach(this, &MicroBitSerial::dataWritten, Serial::TxIrq);
return copiedBytes;
}
/**
* Locks the mutex so that others can't use this serial instance for reception
*/
void MicroBitSerial::lockRx()
{
status |= MICROBIT_SERIAL_RX_IN_USE;
}
/**
* Locks the mutex so that others can't use this serial instance for transmission
*/
void MicroBitSerial::lockTx()
{
status |= MICROBIT_SERIAL_TX_IN_USE;
}
/**
* Unlocks the mutex so that others can use this serial instance for reception
*/
void MicroBitSerial::unlockRx()
{
status &= ~MICROBIT_SERIAL_RX_IN_USE;
}
/**
* Unlocks the mutex so that others can use this serial instance for transmission
*/
void MicroBitSerial::unlockTx()
{
status &= ~MICROBIT_SERIAL_TX_IN_USE;
}
/**
* We do not want to always have our buffers initialised, especially if users to not
* use them. We only bring them up on demand.
*/
int MicroBitSerial::initialiseRx()
{
if((status & MICROBIT_SERIAL_RX_BUFF_INIT))
{
//ensure that we receive no interrupts after freeing our buffer
detach(Serial::RxIrq);
free(this->rxBuff);
}
status &= ~MICROBIT_SERIAL_RX_BUFF_INIT;
if((this->rxBuff = (uint8_t *)malloc(rxBuffSize)) == NULL)
return MICROBIT_NO_RESOURCES;
this->rxBuffHead = 0;
this->rxBuffTail = 0;
//set the receive interrupt
status |= MICROBIT_SERIAL_RX_BUFF_INIT;
attach(this, &MicroBitSerial::dataReceived, Serial::RxIrq);
return MICROBIT_OK;
}
/**
* We do not want to always have our buffers initialised, especially if users to not
* use them. We only bring them up on demand.
*/
int MicroBitSerial::initialiseTx()
{
if((status & MICROBIT_SERIAL_TX_BUFF_INIT))
{
//ensure that we receive no interrupts after freeing our buffer
detach(Serial::TxIrq);
free(this->txBuff);
}
status &= ~MICROBIT_SERIAL_TX_BUFF_INIT;
if((this->txBuff = (uint8_t *)malloc(txBuffSize)) == NULL)
return MICROBIT_NO_RESOURCES;
this->txBuffHead = 0;
this->txBuffTail = 0;
status |= MICROBIT_SERIAL_TX_BUFF_INIT;
return MICROBIT_OK;
}
/**
* An internal method that either spin waits if mode is set to SYNC_SPINWAIT
* or puts the fiber to sleep if the mode is set to SYNC_SLEEP
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP
*/
void MicroBitSerial::send(MicroBitSerialMode mode)
{
if(mode == SYNC_SPINWAIT)
while(txBufferedSize() > 0);
if(mode == SYNC_SLEEP)
fiber_sleep(0);
}
/**
* Reads a single character from the rxBuff
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - A character is read from the rxBuff if available, if there
* are no characters to be read, a value of zero is returned immediately.
*
* SYNC_SPINWAIT - A character is read from the rxBuff if available, if there
* are no characters to be read, this method will spin
* (lock up the processor) until a character is available.
*
* SYNC_SLEEP - A character is read from the rxBuff if available, if there
* are no characters to be read, the calling fiber sleeps
* until there is a character available.
*
* Defaults to SYNC_SLEEP.
*
* @return a character from the circular buffer, or MICROBIT_NO_DATA is there
* are no characters in the buffer.
*/
int MicroBitSerial::getChar(MicroBitSerialMode mode)
{
if(mode == ASYNC)
{
if(!isReadable())
return MICROBIT_NO_DATA;
}
if(mode == SYNC_SPINWAIT)
while(!isReadable());
if(mode == SYNC_SLEEP)
{
if(!isReadable())
eventAfter(1, mode);
}
char c = rxBuff[rxBuffTail];
rxBuffTail = (rxBuffTail + 1) % rxBuffSize;
return c;
}
/**
* An internal method that copies values from a circular buffer to a linear buffer.
*
* @param circularBuff a pointer to the source circular buffer
*
* @param circularBuffSize the size of the circular buffer
*
* @param linearBuff a pointer to the destination linear buffer
*
* @param tailPosition the tail position in the circular buffer you want to copy from
*
* @param headPosition the head position in the circular buffer you want to copy to
*
* @note this method assumes that the linear buffer has the appropriate amount of
* memory to contain the copy operation
*/
void MicroBitSerial::circularCopy(uint8_t *circularBuff, uint8_t circularBuffSize, uint8_t *linearBuff, uint16_t tailPosition, uint16_t headPosition)
{
int toBuffIndex = 0;
while(tailPosition != headPosition)
{
linearBuff[toBuffIndex++] = circularBuff[tailPosition];
tailPosition = (tailPosition + 1) % circularBuffSize;
}
}
/**
* Sends a single character over the serial line.
*
* @param c the character to send
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - the character is copied into the txBuff and returns immediately.
*
* SYNC_SPINWAIT - the character is copied into the txBuff and this method
* will spin (lock up the processor) until the character has
* been sent.
*
* SYNC_SLEEP - the character is copied into the txBuff and the fiber sleeps
* until the character has been sent. This allows other fibers
* to continue execution.
*
* Defaults to SYNC_SLEEP.
*
* @return the number of bytes written, or MICROBIT_SERIAL_IN_USE if another fiber
* is using the serial instance for transmission.
*/
int MicroBitSerial::sendChar(char c, MicroBitSerialMode mode)
{
if(txInUse())
return MICROBIT_SERIAL_IN_USE;
lockTx();
//lazy initialisation of our tx buffer
if(!(status & MICROBIT_SERIAL_TX_BUFF_INIT))
{
int result = initialiseTx();
if(result != MICROBIT_OK)
return result;
}
uint8_t toTransmit[2] = { c, '\0'};
int bytesWritten = setTxInterrupt(toTransmit, 1, mode);
send(mode);
unlockTx();
return bytesWritten;
}
/**
* Sends a ManagedString over the serial line.
*
* @param s the string to send
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - bytes are copied into the txBuff and returns immediately.
*
* SYNC_SPINWAIT - bytes are copied into the txBuff and this method
* will spin (lock up the processor) until all bytes
* have been sent.
*
* SYNC_SLEEP - bytes are copied into the txBuff and the fiber sleeps
* until all bytes have been sent. This allows other fibers
* to continue execution.
*
* Defaults to SYNC_SLEEP.
*
* @return the number of bytes written, MICROBIT_SERIAL_IN_USE if another fiber
* is using the serial instance for transmission, MICROBIT_INVALID_PARAMETER
* if buffer is invalid, or the given bufferLen is <= 0.
*/
int MicroBitSerial::send(ManagedString s, MicroBitSerialMode mode)
{
return send((uint8_t *)s.toCharArray(), s.length(), mode);
}
/**
* Sends a buffer of known length over the serial line.
*
* @param buffer a pointer to the first character of the buffer
*
* @param len the number of bytes that are safely available to read.
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - bytes are copied into the txBuff and returns immediately.
*
* SYNC_SPINWAIT - bytes are copied into the txBuff and this method
* will spin (lock up the processor) until all bytes
* have been sent.
*
* SYNC_SLEEP - bytes are copied into the txBuff and the fiber sleeps
* until all bytes have been sent. This allows other fibers
* to continue execution.
*
* Defaults to SYNC_SLEEP.
*
* @return the number of bytes written, MICROBIT_SERIAL_IN_USE if another fiber
* is using the serial instance for transmission, MICROBIT_INVALID_PARAMETER
* if buffer is invalid, or the given bufferLen is <= 0.
*/
int MicroBitSerial::send(uint8_t *buffer, int bufferLen, MicroBitSerialMode mode)
{
if(txInUse())
return MICROBIT_SERIAL_IN_USE;
if(bufferLen <= 0 || buffer == NULL)
return MICROBIT_INVALID_PARAMETER;
lockTx();
//lazy initialisation of our tx buffer
if(!(status & MICROBIT_SERIAL_TX_BUFF_INIT))
{
int result = initialiseTx();
if(result != MICROBIT_OK)
return result;
}
bool complete = false;
int bytesWritten = 0;
while(!complete)
{
bytesWritten += setTxInterrupt(buffer + bytesWritten, bufferLen - bytesWritten, mode);
send(mode);
if(mode == ASYNC || bytesWritten >= bufferLen)
complete = true;
}
unlockTx();
return bytesWritten;
}
/**
* Reads a single character from the rxBuff
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - A character is read from the rxBuff if available, if there
* are no characters to be read, a value of MICROBIT_NO_DATA is returned immediately.
*
* SYNC_SPINWAIT - A character is read from the rxBuff if available, if there
* are no characters to be read, this method will spin
* (lock up the processor) until a character is available.
*
* SYNC_SLEEP - A character is read from the rxBuff if available, if there
* are no characters to be read, the calling fiber sleeps
* until there is a character available.
*
* Defaults to SYNC_SLEEP.
*
* @return a character, MICROBIT_SERIAL_IN_USE if another fiber is using the serial instance for reception,
* MICROBIT_NO_RESOURCES if buffer allocation did not complete successfully, or MICROBIT_NO_DATA if
* the rx buffer is empty and the mode given is ASYNC.
*/
int MicroBitSerial::read(MicroBitSerialMode mode)
{
if(rxInUse())
return MICROBIT_SERIAL_IN_USE;
lockRx();
//lazy initialisation of our buffers
if(!(status & MICROBIT_SERIAL_RX_BUFF_INIT))
{
int result = initialiseRx();
if(result != MICROBIT_OK)
return result;
}
int c = getChar(mode);
unlockRx();
return c;
}
/**
* Reads multiple characters from the rxBuff and returns them as a ManagedString
*
* @param size the number of characters to read.
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - If the desired number of characters are available, this will return
* a ManagedString with the expected size. Otherwise, it will read however
* many characters there are available.
*
* SYNC_SPINWAIT - If the desired number of characters are available, this will return
* a ManagedString with the expected size. Otherwise, this method will spin
* (lock up the processor) until the desired number of characters have been read.
*
* SYNC_SLEEP - If the desired number of characters are available, this will return
* a ManagedString with the expected size. Otherwise, the calling fiber sleeps
* until the desired number of characters have been read.
*
* Defaults to SYNC_SLEEP.
*
* @return A ManagedString, or an empty ManagedString if an error was encountered during the read.
*/
ManagedString MicroBitSerial::read(int size, MicroBitSerialMode mode)
{
uint8_t buff[size + 1];
memclr(&buff, size + 1);
int returnedSize = read((uint8_t *)buff, size, mode);
if(returnedSize <= 0)
return ManagedString();
return ManagedString((char *)buff, returnedSize);
}
/**
* Reads multiple characters from the rxBuff and fills a user buffer.
*
* @param buffer a pointer to a user allocated buffer.
*
* @param bufferLen the amount of data that can be safely stored
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - If the desired number of characters are available, this will fill
* the given buffer. Otherwise, it will fill the buffer with however
* many characters there are available.
*
* SYNC_SPINWAIT - If the desired number of characters are available, this will fill
* the given buffer. Otherwise, this method will spin (lock up the processor)
* and fill the buffer until the desired number of characters have been read.
*
* SYNC_SLEEP - If the desired number of characters are available, this will fill
* the given buffer. Otherwise, the calling fiber sleeps
* until the desired number of characters have been read.
*
* Defaults to SYNC_SLEEP.
*
* @return the number of characters read, or MICROBIT_SERIAL_IN_USE if another fiber
* is using the instance for receiving.
*/
int MicroBitSerial::read(uint8_t *buffer, int bufferLen, MicroBitSerialMode mode)
{
if(rxInUse())
return MICROBIT_SERIAL_IN_USE;
lockRx();
//lazy initialisation of our rx buffer
if(!(status & MICROBIT_SERIAL_RX_BUFF_INIT))
{
int result = initialiseRx();
if(result != MICROBIT_OK)
return result;
}
int bufferIndex = 0;
int temp = 0;
if(mode == ASYNC)
{
while((temp = getChar(mode)) != MICROBIT_NO_DATA && bufferIndex < bufferLen)
{
buffer[bufferIndex] = (char)temp;
bufferIndex++;
}
}
if(mode == SYNC_SPINWAIT)
{
while(bufferIndex < bufferLen)
{
buffer[bufferIndex] = (char)getChar(mode);
bufferIndex++;
}
}
if(mode == SYNC_SLEEP)
{
if(bufferLen > rxBufferedSize())
eventAfter(bufferLen - rxBufferedSize(), mode);
while(bufferIndex < bufferLen)
{
buffer[bufferIndex] = (char)getChar(mode);
bufferIndex++;
}
}
unlockRx();
return bufferIndex;
}
/**
* Reads until one of the delimeters matches a character in the rxBuff
*
* @param delimeters a ManagedString containing a sequence of delimeter characters e.g. ManagedString("\r\n")
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - If one of the delimeters matches a character already in the rxBuff
* this method will return a ManagedString up to the delimeter.
* Otherwise, it will return an Empty ManagedString.
*
* SYNC_SPINWAIT - If one of the delimeters matches a character already in the rxBuff
* this method will return a ManagedString up to the delimeter.
* Otherwise, this method will spin (lock up the processor) until a
* received character matches one of the delimeters.
*
* SYNC_SLEEP - If one of the delimeters matches a character already in the rxBuff
* this method will return a ManagedString up to the delimeter.
* Otherwise, the calling fiber sleeps until a character matching one
* of the delimeters is seen.
*
* Defaults to SYNC_SLEEP.
*
* @return A ManagedString containing the characters up to a delimeter, or an Empty ManagedString,
* if another fiber is currently using this instance for reception.
*
* @note delimeters are matched on a per byte basis.
*/
ManagedString MicroBitSerial::readUntil(ManagedString delimeters, MicroBitSerialMode mode)
{
if(rxInUse())
return ManagedString();
//lazy initialisation of our rx buffer
if(!(status & MICROBIT_SERIAL_RX_BUFF_INIT))
{
int result = initialiseRx();
if(result != MICROBIT_OK)
return result;
}
lockRx();
int localTail = rxBuffTail;
int preservedTail = rxBuffTail;
int foundIndex = -1;
//ASYNC mode just iterates through our stored characters checking for any matches.
while(localTail != rxBuffHead && foundIndex == -1)
{
//we use localTail to prevent modification of the actual tail.
char c = rxBuff[localTail];
for(int delimeterIterator = 0; delimeterIterator < delimeters.length(); delimeterIterator++)
if(delimeters.charAt(delimeterIterator) == c)
foundIndex = localTail;
localTail = (localTail + 1) % rxBuffSize;
}
//if our mode is SYNC_SPINWAIT and we didn't see any matching characters in our buffer
//spin until we find a match!
if(mode == SYNC_SPINWAIT)
{
while(foundIndex == -1)
{
while(localTail == rxBuffHead);
char c = rxBuff[localTail];
for(int delimeterIterator = 0; delimeterIterator < delimeters.length(); delimeterIterator++)
if(delimeters.charAt(delimeterIterator) == c)
foundIndex = localTail;
localTail = (localTail + 1) % rxBuffSize;
}
}
//if our mode is SYNC_SLEEP, we set up an event to be fired when we see a
//matching character.
if(mode == SYNC_SLEEP && foundIndex == -1)
{
eventOn(delimeters, mode);
foundIndex = rxBuffHead - 1;
this->delimeters = ManagedString();
}
if(foundIndex >= 0)
{
//calculate our local buffer size
int localBuffSize = (preservedTail > foundIndex) ? (rxBuffSize - preservedTail) + foundIndex : foundIndex - preservedTail;
uint8_t localBuff[localBuffSize + 1];
memclr(&localBuff, localBuffSize + 1);
circularCopy(rxBuff, rxBuffSize, localBuff, preservedTail, foundIndex);
//plus one for the character we listened for...
rxBuffTail = (rxBuffTail + localBuffSize + 1) % rxBuffSize;
unlockRx();
return ManagedString((char *)localBuff, localBuffSize);
}
unlockRx();
return ManagedString();
}
/**
* A wrapper around the inherited method "baud" so we can trap the baud rate
* as it changes and restore it if redirect() is called.
*
* @param baudrate the new baudrate. See:
* - https://github.com/mbedmicro/mbed/blob/master/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_MCU_NRF51822/serial_api.c
* for permitted baud rates.
*
* @return MICROBIT_INVALID_PARAMETER if baud rate is less than 0, otherwise MICROBIT_OK.
*
* @note the underlying implementation chooses the first allowable rate at or above that requested.
*/
void MicroBitSerial::baud(int baudrate)
{
if(baudrate < 0)
return;
this->baudrate = baudrate;
RawSerial::baud(baudrate);
}
/**
* A way of dynamically configuring the serial instance to use pins other than USBTX and USBRX.
*
* @param tx the new transmission pin.
*
* @param rx the new reception pin.
*
* @return MICROBIT_SERIAL_IN_USE if another fiber is currently transmitting or receiving, otherwise MICROBIT_OK.
*/
int MicroBitSerial::redirect(PinName tx, PinName rx)
{
if(txInUse() || rxInUse())
return MICROBIT_SERIAL_IN_USE;
lockTx();
lockRx();
if(txBufferedSize() > 0)
detach(Serial::TxIrq);
detach(Serial::RxIrq);
serial_init(&_serial, tx, rx);
attach(this, &MicroBitSerial::dataReceived, Serial::RxIrq);
if(txBufferedSize() > 0)
attach(this, &MicroBitSerial::dataWritten, Serial::TxIrq);
this->baud(this->baudrate);
unlockRx();
unlockTx();
return MICROBIT_OK;
}
/**
* Configures an event to be fired after "len" characters.
*
* Will generate an event with the ID: MICROBIT_ID_SERIAL and the value MICROBIT_SERIAL_EVT_HEAD_MATCH.
*
* @param len the number of characters to wait before triggering the event.
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - Will configure the event and return immediately.
*
* SYNC_SPINWAIT - will return MICROBIT_INVALID_PARAMETER
*
* SYNC_SLEEP - Will configure the event and block the current fiber until the
* event is received.
*
* @return MICROBIT_INVALID_PARAMETER if the mode given is SYNC_SPINWAIT, otherwise MICROBIT_OK.
*/
int MicroBitSerial::eventAfter(int len, MicroBitSerialMode mode)
{
if(mode == SYNC_SPINWAIT)
return MICROBIT_INVALID_PARAMETER;
//configure our head match...
this->rxBuffHeadMatch = (rxBuffHead + len) % rxBuffSize;
//block!
if(mode == SYNC_SLEEP)
fiber_wait_for_event(MICROBIT_ID_SERIAL, MICROBIT_SERIAL_EVT_HEAD_MATCH);
return MICROBIT_OK;
}
/**
* Configures an event to be fired on a match with one of the delimeters.
*
* Will generate an event with the ID: MICROBIT_ID_SERIAL and the value MICROBIT_SERIAL_EVT_DELIM_MATCH.
*
* @param delimeters the characters to match received characters against e.g. ManagedString("\n")
*
* @param mode the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode
* gives a different behaviour:
*
* ASYNC - Will configure the event and return immediately.
*
* SYNC_SPINWAIT - will return MICROBIT_INVALID_PARAMETER
*
* SYNC_SLEEP - Will configure the event and block the current fiber until the
* event is received.
*
* @return MICROBIT_INVALID_PARAMETER if the mode given is SYNC_SPINWAIT, otherwise MICROBIT_OK.
*
* @note delimeters are matched on a per byte basis.
*/
int MicroBitSerial::eventOn(ManagedString delimeters, MicroBitSerialMode mode)
{
if(mode == SYNC_SPINWAIT)
return MICROBIT_INVALID_PARAMETER;
//configure our head match...
this->delimeters = delimeters;
//block!
if(mode == SYNC_SLEEP)
fiber_wait_for_event(MICROBIT_ID_SERIAL, MICROBIT_SERIAL_EVT_DELIM_MATCH);
return MICROBIT_OK;
}
/**
* Determines whether there is any data waiting in our Rx buffer.
*
* @return 1 if we have space, 0 if we do not.
*
* @note We do not wrap the super's readable() method as we don't want to
* interfere with communities that use manual calls to serial.readable().
*/
int MicroBitSerial::isReadable()
{
return (rxBuffTail != rxBuffHead) ? 1 : 0;
}
/**
* Determines if we have space in our txBuff.
*
* @return 1 if we have space, 0 if we do not.
*
* @note We do not wrap the super's writeable() method as we don't want to
* interfere with communities that use manual calls to serial.writeable().
*/
int MicroBitSerial::isWriteable()
{
return (txBuffHead != (txBuffTail - 1)) ? 1 : 0;
}
/**
* Reconfigures the size of our rxBuff
*
* @param size the new size for our rxBuff
*
* @return MICROBIT_SERIAL_IN_USE if another fiber is currently using this instance
* for reception, otherwise MICROBIT_OK.
*/
int MicroBitSerial::setRxBufferSize(uint8_t size)
{
if(rxInUse())
return MICROBIT_SERIAL_IN_USE;
lockRx();
// + 1 so there is a usable buffer size, of the size the user requested.
this->rxBuffSize = size + 1;
int result = initialiseRx();
unlockRx();
return result;
}
/**
* Reconfigures the size of our txBuff
*
* @param size the new size for our txBuff
*
* @return MICROBIT_SERIAL_IN_USE if another fiber is currently using this instance
* for transmission, otherwise MICROBIT_OK.
*/
int MicroBitSerial::setTxBufferSize(uint8_t size)
{
if(txInUse())
return MICROBIT_SERIAL_IN_USE;
lockTx();
// + 1 so there is a usable buffer size, of the size the user requested.
this->txBuffSize = size + 1;
int result = initialiseTx();
unlockTx();