This repository was archived by the owner on Dec 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path$autorun$.VSP.UART.bridge.outgoing.sb
More file actions
1015 lines (930 loc) · 36.4 KB
/
$autorun$.VSP.UART.bridge.outgoing.sb
File metadata and controls
1015 lines (930 loc) · 36.4 KB
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 (c) 2015, Laird
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// SPDX-License-Identifier:ISC
//
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++ ++
// +++++ When UwTerminal downloads the app it will store it as a filenname ++
// +++++ which consists of all characters up to the first . and excluding it ++
// +++++ ++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// BL620 custom VSP service: This application will connect to a VSP service and
// allow communication to that server from the UART.
//
//******************************************************************************
// This app provides for a command interface over the uart for testing VSP and
// the protocol is as follows:-
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Convention : (1) Case sensitive, and commands are presented in alphabetic order
// (2) If line ends with \ then it continues on next line. That does
// not mean that it should be sent as multiple lines
// (3) Replace anything between ##
// (4) #INTaaaa# means a number in decimal, hex, octal or binary
// format -> 23 == 0x17 == h'17 == o'23 == b'10111
// aaaa is just a description
// (5) #HEXaaaa# means a string without delimitors consisting of hex
// characters only aaaa is just a description
// (6) #STRaaaa# means a string without delimitors
// aaaa is just a description
// (7) "STRaaaa" means a string which must have the " delimitor
// aaaa is just a description
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// -----------------------------------------------------------------------------
// at+bls OR scan
// - Start a scan using the timeout #SCAN_TMT#
//
// -----------------------------------------------------------------------------
// atd #HEXbdAddr7bytes# OR
// connect #HEXbdAddr7bytes# OR
// - Connect to device with given BT address
//
// -> if an invalid or null BT address is given, the default mac address
// (see #define BTAddr) will be used.
//
// -> Upon successful connection the application enters bridge mode. Any data
// arriving at the UART is sent over the VSP connection.
//
// -> Note: The device you are connecting to must be running a VSP server.
//
// ::Note::
// - Upon connection, the module will automatically switch to bridge mode.
// Any data arriving at the VSP port will be sent to the UART and vice versa.
//
// -> To switch back to command mode so the module can accept commands again, assert the
// nAutorun pin. This can be done by unticking DTR in UwTerminal. Switch back to bridge mode
// by deasserting the nAutorun pin - ticking DTR in UwTerminal.
//
// -> Make sure DIP Switch 2 on CON12 is in the ON position if using a DVK kit.
// -----------------------------------------------------------------------------
// at+btd #HEXbdaddr7bytes#
// - Deletes corresponding link key from the database
//
// -----------------------------------------------------------------------------
// ath OR disconnect
// - Disconnect from peer device.
//
// -----------------------------------------------------------------------------
// bdaddr
// - Prints the module's 7 byte BT address
//
// -----------------------------------------------------------------------------
// stop
// - Stop scanning
//
// -----------------------------------------------------------------------------
// ato OR bridge
// - enter bridge mode. Any data arriving at the UART is sent over the BLE
// connection.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// misc i clearall
// - Make all elements of the entire i[] array equal to 0
//
// -----------------------------------------------------------------------------
// misc i set #INTidx# #INTval#
// - i[#INTidx#] = #INTval#
// - #INTidx# will be checked for valid index
//
// -----------------------------------------------------------------------------
// misc s$ clearall
// - make all elements of the entire s$[] array empty
//
// -----------------------------------------------------------------------------
// misc s$ set #INTidx# #STRescapedvalue#
// - s$[#INTidx#] = #STRescapedvalue#
// - #INTidx# will be checked for valid index
//
// -----------------------------------------------------------------------------
// misc s$ sethex #INTidx# #HEXdigitsvalue#
// - s$[#INTidx#] = #HEXdigitsvalue#
// - #INTidx# will be checked for valid index
//
// -----------------------------------------------------------------------------
// quit OR exit
// - Exit to command mode
//
//******************************************************************************
//
// *Instructions*
// 1. Set BTAddr to the BT Address of the peer device you want to connect to by default
// 2. Set CONNECT_ON_STARTUP to 1 to automatically connect
// 3. Start a VSP server on a BT900 with the other VSP application (on github) or by bridging SIO_19 to GND to enable command VSP mode (bridge SIO_7 to VCC on a BL600 development kit)
// 4. Download and run this application to a BL620 and it will automatically connect to the VSP server
//
//
// ::Note::
// - Upon connection, the module will automatically switch to bridge mode. Any data arriving
// at the VSP port will be sent to the UART and vice versa.
//
// -> To switch back to command mode so the module can accept commands again, assert the
// nAutorun pin. This can be done by unticking DTR in UwTerminal. Switch back to bridge mode
// by deasserting the nAutorun pin - ticking DTR in UwTerminal. This can also be done by
// pressing the caret "^" key 3 times with LineMode disabled.
//
// -> Make sure DIP Switch 2 on CON12 is in the ON position if using a DVK kit.
//
//******************************************************************************
//This is the target Bluetooth device to connect to, 7 bytes in hex
#define BTAddr "01D9E61101BF82"
//******************************************************************************
// Definitions
//******************************************************************************
//If set to 1, on startup the module will connect to device BTAddr for VSP
#define CONNECT_ON_STARTUP 0
//BLE Scan config parameters
#define SCAN_TMT 20000 //Scan timeout in mS
//Set this to 0 to disable all debugging messages
#define ENABLE_DEBUG_PRINTS 1
#define APP_VERSION "1.0"
//Size of i[]
#define NUM_OF_I_PARAMS (5)
//Size of s$[]
#define NUM_OF_S_PARAMS (5)
#define DISCON_TIMER 0 //If this is changed, make sure to change the EvTmrX statement
#define DISCON_TIMER_DUR_MS 500
#define CARET_TIMER 1
#define CARET_TIMER_DUR_MS 100
//APP RUN MODES
#define CMD_MODE 0
#define BRIDGE_VSP_MODE 1
//UUIDs
#define BASEUUID "\56\9a\11\01\b8\7f\49\0c\92\cb\11\ba\5e\a5\16\7c" //VSP base UUID
#define MIUUID "\56\9a\20\03\b8\7f\49\0c\92\cb\11\ba\5e\a5\16\7c" //Modem in UUID
#define MOUUID "\56\9a\20\02\b8\7f\49\0c\92\cb\11\ba\5e\a5\16\7c" //Modem out UUID
#define RXUUID "\56\9a\20\01\b8\7f\49\0c\92\cb\11\ba\5e\a5\16\7c" //Receive VSP UUID
#define TXUUID "\56\9a\20\00\b8\7f\49\0c\92\cb\11\ba\5e\a5\16\7c" //Transmit VSP UUID
#define BT900_DEV_ID 0x42370900
#define BL620_DEV_ID 0x424C0620
//******************************************************************************
// Global Variable Declarations
//******************************************************************************
dim rc //Result code
dim BleHandle //Ble Connection Handle
dim Mode : Mode = 0 //Current program mode: 0 = connecting, 1 = connected, find modem in characteristic, 2 = find modem out characteristic, 3 = find RX characteristic, 4 = find TX characteristic, 5 = find modem out descriptor, 6 = find TX descriptor, 7 = enable modem out notIFications, 8 = enable TX, 9 = enable modem in status
dim MIHandle //Modem In handle (if one exists)
dim MOHandle //Modem Out handle (if one exists)
dim RXHandle //RX handle
dim TXHandle //TX handle
dim MOCCCDHandle //Modem Out CCCD handle (if one exists)
dim TXCCCDHandle //TX CCCD handle (if one exists)
dim UUID1$, UUID2$ //UUID and temporary string variables
dim BufferState : BufferState = 0 //Buffer state
dim BufferFull : BufferFull = 0 //Buffer full
dim u$ : u$ = "" //UART read buffer
dim RecBuf$ : RecBuf$ = "" //VSP read buffer
dim ModemStat : ModemStat = 1 //Modem in status
dim ModemInOutExists : ModemInOutExists = 1 //If modem in/out exists on the server
dim BTAddr$ //Bluetooth address to connect to
dim ok$ : ok$ = "\nOK" //OK command response
dim er$ : er$ = "\nERROR " //Error command response
dim pr$ : pr$ = "\r\n>" //
dim nc$ : nc$ = "\nNO CARRIER" //No carrier response
dim uc$ : uc$ = "\nUNKNOWN COMMAND" //Unknown command response
dim carCnt : carCnt = 0 //Count variable for number of times '^' entered
//******************************************************************************
// Register Error Handler as early as possible
//******************************************************************************
sub HandlerOnErr()
if (ENABLE_DEBUG_PRINTS!=0) then
print "\n OnErr - ";GetLastError();"\n"
endif
endsub
onerror next HandlerOnErr
dim stRsp$ as string //Uart rx data is stored here
dim i[NUM_OF_I_PARAMS] //Index 0 used for return values
dim s$[NUM_OF_S_PARAMS] //Must be at least 5 elements
dim urtcmd$ //CMD line from uart
dim tkn$,tlen //Used by command parser
dim InConnection : InConnection = 0 //Set to 1 when in a connection
//******************************************************************************
// Register Error Handler as early as possible
//******************************************************************************
SUB AssertRC(rc, line)
IF (rc != 0) THEN
PRINT "Error at line ";line;": ";INTEGER.H'rc;"\n"
ENDIF
ENDSUB
//******************************************************************************
// Function and Subroutine definitions
//******************************************************************************
//-------------------------------------------------------------------------
//#CMD#// ath OR disconnect
//-------------------------------------------------------------------------
function _disconnect()
rc = BLEDISCONNECT(BleHandle)
if rc!=0 then
exitfunc rc
endif
endfunc -3 //Don't give response to user
//-------------------------------------------------------------------------
// Process a caret character ^ do decide whether or not to switch to command mode
// - When the carCnt value is 3, end func with 1 to switch to command mode
// - Think of it like a boolean value
//-------------------------------------------------------------------------
function SwitchToCmd()
//If ^ was sent after the delay time (valid) increment the counter
if TimerRunning(CARET_TIMER)==0 then
carCnt = carCnt + 1
if carCnt<3 then
TimerStart(CARET_TIMER,CARET_TIMER_DUR_MS,0)
else
TimerCancel(CARET_TIMER)
exitfunc 1
endif
else
//Invalid press
print "\n"
TimerCancel(CARET_TIMER)
carCnt = 0
endif
endfunc 0 //Don't give response to user
//==============================================================================
//UART data received
//==============================================================================
FUNCTION HndlrUartRxVSP()
dim uLen, bytesWaiting, newData$
IF BufferState == 0 && ModemStat == 1 then
//Get number of bytes waiting in actual Uart RX Buffer before reading
bytesWaiting = UartInfo(3)
//Read data that has arrived through via the UART
uLen = UartReadN(u$, 20)
//Get the most recently received data
newData$ = Right$(u$, bytesWaiting)
IF uLen > 0 then
if StrCmp(newData$,"^")==0 then
//Parse the ^ entry
if SwitchToCmd() == 1 then
print "\n"
//Switch to command mode
rc = SendMsgApp(0,CMD_MODE)
endif
else
rc = BLEGATTCWRITE(BleHandle, RXHandle, u$)
BufferState = 1
u$ = ""
endif
ENDIF
ENDIF
ENDFUNC 1
//==============================================================================
//BLE connection timed out
//==============================================================================
FUNCTION HndlrConnTO()
PRINT "Connection attempt timed out.\n"
ENDFUNC 1
//==============================================================================
//Characteristic found
//==============================================================================
FUNCTION HndlrFindChar(cHndl,cProp,hVal,isUuid)
IF (Mode == 1) THEN
//Modem in
IF (cProp == 0 && hVal == 0 && isUuid == 0) THEN
//No modem in/out characteristics
ModemInOutExists = 0
Mode = 3
UUID1$ = BASEUUID
UUID2$ = RXUUID
rc = BLEGATTCFINDCHAR(BleHandle, BleHandleUuid128(UUID1$), 0, BleHandleUuid128(UUID2$), 0)
AssertRC(rc, 3)
ELSE
MIHandle = hVal
Mode = 2
UUID1$ = BASEUUID
UUID2$ = MOUUID
rc = BLEGATTCFINDCHAR(BleHandle, BleHandleUuid128(UUID1$), 0, BleHandleUuid128(UUID2$), 0)
AssertRC(rc, 4)
ENDIF
ELSEIF (Mode == 2) THEN
//Modem out
MOHandle = hVal
Mode = 3
UUID1$ = BASEUUID
UUID2$ = RXUUID
rc = BLEGATTCFINDCHAR(BleHandle, BleHandleUuid128(UUID1$), 0, BleHandleUuid128(UUID2$), 0)
AssertRC(rc, 5)
ELSEIF (Mode == 3) THEN
//RX
IF (cProp == 0 && hVal == 0 && isUuid == 0) THEN
//Characteristic not found
rc = _disconnect()
PRINT "VSP RX characteristic was not found, disconnected.\n"
ELSE
//Characteristic found
RXHandle = hVal
Mode = 4
UUID1$ = BASEUUID
UUID2$ = TXUUID
rc = BLEGATTCFINDCHAR(BleHandle, BleHandleUuid128(UUID1$), 0, BleHandleUuid128(UUID2$), 0)
AssertRC(rc, 6)
ENDIF
ELSEIF (Mode == 4) THEN
//TX
IF (cProp == 0 && hVal == 0 && isUuid == 0) THEN
//Characteristic not found
rc = _disconnect()
PRINT "VSP TX characteristic was not found, disconnected.\n"
ELSE
//Characteristic found
TXHandle = hVal
Mode = 5
UUID1$ = BASEUUID
UUID2$ = MOUUID
rc = BLEGATTCFINDDESC(BleHandle, BleHandleUuid128(UUID1$), 0, BleHandleUuid128(UUID2$), 0, 0xFE012902, 0)
AssertRC(rc, 7)
ENDIF
ENDIF
ENDFUNC 1
//==============================================================================
//Characteristic written
//==============================================================================
FUNCTION HndlrAttrWrite(cHndl,aHndl,nSts)
if (nSts !=0) then
rc = BlePair(cHndl,1)
AssertRC(rc, 349)
exitfunc 1
endif
IF (Mode == 7) THEN
//Enable TX notIFications
Mode = 8
UUID1$ = "\01\00"
rc = BLEGATTCWRITE(BleHandle, TXCCCDHandle, UUID1$)
AssertRC(rc, 8)
ELSEIF (Mode == 8) THEN
//Write to Modem In
IF (ModemInOutExists == 1) THEN
Mode = 9
UUID1$ = "\01"
BufferFull = 0
rc = BLEGATTCWRITE(BleHandle, MIHandle, UUID1$)
AssertRC(rc, 9)
ELSE
BufferFull = 0
BufferState = 0
Mode = 10
ModemStat = 1
u$ = ""
RecBuf$ = ""
print "Ready to transmit/receive!\n"
rc = SendMsgApp(0,BRIDGE_VSP_MODE)
ENDIF
ELSEIF (Mode == 9) THEN
//Now ready to send data
BufferFull = 0
BufferState = 0
Mode = 10
u$ = ""
RecBuf$ = ""
print "Ready to transmit/receive!\n"
rc = SendMsgApp(0,BRIDGE_VSP_MODE)
ELSEIF (Mode == 10) THEN
//UART data was written
BufferState = 0
rc = HndlrUartRxVSP()
ENDIF
ENDFUNC 1
//==============================================================================
//Received BLE notification
//==============================================================================
FUNCTION HndlrAttrNotify()
dim nCtx, Hndl, Data$, discard, UartSent, arc
arc = BLEGATTCNOTIFYREAD(nCtx, Hndl, Data$, discard)
while (arc == 0)
IF (Hndl == MOHandle) then
//Modem Out changed
UUID1$ = "\01"
IF (strcmp(UUID1$, Data$) == 0) then
ModemStat = 1
rc = HndlrUartRxVSP()
ELSE
ModemStat = 0
ENDIF
ELSEIF (Hndl == TXHandle) then
//Data
IF BufferFull == 0 then
UartSent = UARTWRITE(Data$)
IF UartSent != strlen(Data$) then
STRSHIFTLEFT(Data$, UartSent)
RecBuf$ = Data$
//NotIFy that we cannot accept more data
UUID1$ = "\00"
BufferFull = 1
rc = BLEGATTCWRITE(BleHandle, MIHandle, UUID1$)
ENDIF
ELSE
//Buffer is full
RecBuf$ = RecBuf$ + Data$
ENDIF
ENDIF
Data$ = ""
arc = BLEGATTCNOTIFYREAD(nCtx, Hndl, Data$, discard)
endwhile
ENDFUNC 1
//==============================================================================
//UART transmit buffer empty
//==============================================================================
FUNCTION HndlrUartTxEmpty()
dim UartSent
IF (strlen(RecBuf$) > 0) then
UartSent = UARTWRITE(RecBuf$)
IF (UartSent == strlen(RecBuf$)) then
//Cleared - notify
RecBuf$ = ""
UUID1$ = "\01"
BufferFull = 0
rc = BLEGATTCWRITE(BleHandle, MIHandle, UUID1$)
ELSE
//Not cleared so shIFt
STRSHIFTLEFT(RecBuf$, UartSent)
ENDIF
ELSE
BufferFull = 0
ENDIF
ENDFUNC 1
//==============================================================================
//CCCD Descriptor found
//==============================================================================
FUNCTION HndlrFindDesc(nCtx, Hndl)
IF (Mode == 5) THEN
//Modem out CCCD
MOCCCDHandle = Hndl
Mode = 6
UUID1$ = BASEUUID
UUID2$ = TXUUID
rc = BLEGATTCFINDDESC(BleHandle, BleHandleUuid128(UUID1$), 0, BleHandleUuid128(UUID2$), 0, 0xFE012902, 0)
ELSEIF (Mode == 6) THEN
//TX CCCD
TXCCCDHandle = Hndl
Mode = 7
IF (ModemInOutExists == 1) THEN
//Enable modem out notIFications
UUID1$ = "\01\00"
rc = BLEGATTCWRITE(BleHandle, MOCCCDHandle, UUID1$)
AssertRC(rc, 10)
ELSE
//Modem in doesn't exist - enable TX notifications
Mode = 8
UUID1$ = "\01\00"
rc = BLEGATTCWRITE(BleHandle, TXCCCDHandle, UUID1$)
AssertRC(rc, 8)
ENDIF
ENDIF
ENDFUNC 1
//==============================================================================
//BLE characteristics data changed
//==============================================================================
FUNCTION HndlrAttrRead(nCtx, Hndl, Stat)
dim Data$, discard, UartSent, nAhndl, nOfst
rc = BleGattcReadData(Hndl,nAhndl,nOfst,Data$)
IF (Hndl == MOHandle) then
//Modem Out changed
UUID1$ = "\01"
IF (strcmp(UUID1$, Data$) == 0) then
ModemStat = 1
rc = HndlrUartRxVSP()
ELSE
ModemStat = 0
ENDIF
ELSEIF (Hndl == TXHandle) then
//Data
IF BufferFull == 0 then
UartSent = UARTWRITE(Data$)
IF UartSent != strlen(Data$) then
STRSHIFTLEFT(Data$, UartSent)
RecBuf$ = Data$
//Notify that we cannot accept more data
UUID1$ = "\00"
BufferFull = 1
rc = BLEGATTCWRITE(BleHandle, MIHandle, UUID1$)
ENDIF
ELSE
//Buffer is full
RecBuf$ = RecBuf$ + Data$
ENDIF
ENDIF
Data$ = ""
ENDFUNC 1
//==============================================================================
//BLE message
//==============================================================================
FUNCTION HndlrBleMsg(nMsgId, nCtx)
//Clear the caret count
carCnt = 0
IF (nMsgId == 0) then
//Connected!
//Opening the GATT client only whe connected to save memory
rc = BleGattcOpen(256, 0)
AssertRC(rc, 0)
BleHandle = nCtx
Mode = 1
dim UUID1$, UUID2$
UUID1$ = BASEUUID
UUID2$ = MIUUID
rc = BLEGATTCFINDCHAR(nCtx, BleHandleUuid128(UUID1$), 0, BleHandleUuid128(UUID2$), 0)
AssertRC(rc, 2)
PRINT "Connected!\n"
InConnection = 1
//encrypt the connection if previously bonded with this device
dim addr$, fAsCentral, info, rollingAge, rollingCount
rc = BleGetAddrFromConnHandle(nCtx, addr$)
if (rc==0) then
if (BleBondingIsTrusted(addr$,fAsCentral,info,rollingAge,rollingCount)>0) then
rc = BleEncryptConnection(nCtx, 7, 1) //Might not need this
endif
endif
ELSEIF (nMsgId == 1) then
//Disconnected!
PRINT "\nDisconnected!\n"
InConnection = 0
BleGattcClose()
rc = SendMsgApp(0,CMD_MODE)
elseif (nMsgId == 10) then
//Start process of writing characteristics and descriptors from the beginning
Mode = 6
exitfunc HndlrFindDesc(0, TXCCCDHandle)
ENDIF
ENDFUNC 1
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function ClearS()
dim j
for j = 0 to (NUM_OF_S_PARAMS-1)
s$[j]=""
next
endfunc 0
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function ClearI()
dim j
for j = 0 to (NUM_OF_I_PARAMS-1)
i[j]=0
next
endfunc 0
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
sub UartRsp(rsp as integer)
if rsp == 0 then
print ok$;pr$
elseif rsp == -2 then
print pr$
elseif rsp == -3 then
print ok$
elseif rsp == -4 then
print uc$;pr$
elseif rsp > 0 then
print er$;integer.h' rsp;pr$
endif
endsub
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function ExtractIntTokens(u$,stIdx,num)
while num>0
tlen = ExtractIntToken(u$,i[stIdx])
if tlen == 0 then
exitfunc 4
endif
num=num-1
stIdx = stIdx+1
endwhile
endfunc 0
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function ExtractStrTokens(u$,stIdx,num)
while num>0
tlen = ExtractStrToken(u$,s$[stIdx])
if tlen == 0 then
exitfunc 3
endif
num=num-1
stIdx = stIdx+1
endwhile
endfunc 0
//-------------------------------------------------------------------------
//#CMD#// ato OR bridge
//-------------------------------------------------------------------------
sub _bridge()
TimerCancel(CARET_TIMER)
carCnt = 0
rc = SendMsgApp(0,BRIDGE_VSP_MODE)
endsub
//-------------------------------------------------------------------------
//#CMD#// at+bls OR scan
//-------------------------------------------------------------------------
function _scan()
//Only allow scanning if not in a connection
if InConnection == 1 then
print "\nALREADY CONNECTED\n"
exitfunc -2
endif
rc = BLESCANSTART(SCAN_TMT, 0)
if rc!=0 then
exitfunc rc
endif
endfunc -1 //Don't give response to user
//-------------------------------------------------------------------------
//#CMD#// atd #HEXbdAddr7bytes# OR connect #HEXbdAddr7bytes#
//-------------------------------------------------------------------------
function _connect()
if InConnection == 1 then
print "\nALREADY CONNECTED"
exitfunc -2
endif
rc = ExtractStrTokens(urtcmd$,1,1)
//Use #defined/stored mac address if none given
if rc!=0 then
s$[1] = BTAddr
endif
s$[1] = StrDehexize$(s$[1])
//Stop scanning in case
rc = BleScanStop()
//Connect to target device
rc = BLECONNECT(s$[1], 5000, 7500, 30000, 500000)
if rc!=0 then
exitfunc rc
endif
endfunc -1
//-------------------------------------------------------------------------
//#CMD#// at+btd #HEXbdAddr7bytes#
//-------------------------------------------------------------------------
function _delete()
rc = ExtractStrTokens(urtcmd$,1,1)
if rc!=0 then
exitfunc -2
endif
s$[1] = StrDehexize$(s$[1])
rc = BleBondingEraseKey(s$[1])
if rc!=0 then
exitfunc rc
endif
endfunc 0
//------------------------------------------------------------------------------
// #CMD#// at+bti
// #CMD#// at+btd #HEXbdAddr7bytes#
//------------------------------------------------------------------------------
Function _at()
StrShiftLeft(urtcmd$,1) //Remove the '+'
tlen = ExtractStrToken(urtcmd$,tkn$)
if tlen > 0 then
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if strcmp(tkn$,"btd")==0 then
exitfunc _delete()
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
elseif strcmp(tkn$,"bls")==0 then
exitfunc _scan()
endif
endif
endfunc -4 //Print 'UNKNOWN COMMAND' if incorrect command
//------------------------------------------------------------------------------
//#CMD#// misc i clearall
//#CMD#// misc i set #INTidx# #INTval#
//#CMD#// misc s$ clearall
//#CMD#// misc s$ set #INTidx# #STRescapedvalue#
//#CMD#// misc s$ sethex #INTidx# #HEXdigitsvalue#
//------------------------------------------------------------------------------
function _Misc()
tlen = ExtractStrToken(urtcmd$,tkn$)
if tlen == 0 then
exitfunc 5
endif
//=================================================
if strcmp(tkn$,"s$")==0 then
tlen = ExtractStrToken(urtcmd$,tkn$)
if tlen == 0 then
exitfunc 5
endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if strcmp(tkn$,"clearall")==0 then
exitfunc ClearS()
endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if strcmp(tkn$,"set")==0 then
//Extract 1 (#INTidx#) and store starting at i[1]
rc = ExtractIntTokens(urtcmd$,1,1)
if rc != 0 then
exitfunc rc
endif
if (i[1] < 0) || (i[1] >= NUM_OF_S_PARAMS) then
exitfunc 6
endif
//Extract 1 (#STRescapedvalue#) and store starting at s$[1]
rc = ExtractStrTokens(urtcmd$,i[1],1)
if rc != 0 then
exitfunc rc
endif
StrDeEscape(s$[i[1]])
exitfunc 0
endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if strcmp(tkn$,"sethex")==0 then
//Extract 1 (#INTidx#) and store starting at i[1]
rc = ExtractIntTokens(urtcmd$,1,1)
if rc != 0 then
exitfunc rc
endif
if (i[1] < 0) || (i[1] >= NUM_OF_S_PARAMS) then
exitfunc 6
endif
//Extract 1 (#STRescapedvalue#) and store starting at s$[1]
rc = ExtractStrTokens(urtcmd$,i[1],1)
if rc != 0 then
exitfunc rc
endif
StrDeEscape(s$[i[1]])
exitfunc 0
endif
endif
//=================================================
if strcmp(tkn$,"i")==0 then
tlen = ExtractStrToken(urtcmd$,tkn$)
if tlen == 0 then
exitfunc 5
endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if strcmp(tkn$,"clearall")==0 then
exitfunc ClearI()
endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if strcmp(tkn$,"set")==0 then
dim idx
tlen = ExtractIntToken(urtcmd$,idx)
if tlen == 0 then
exitfunc 5
endif
if (idx < 0) || (idx >= NUM_OF_I_PARAMS) then
exitfunc 6
endif
tlen = ExtractIntToken(urtcmd$,i[idx])
if tlen == 0 then
exitfunc 5
endif
exitfunc 0
endif
endif
endfunc 5
//------------------------------------------------------------------------------
// This handler is called when there is an scan timeout
//------------------------------------------------------------------------------
function HndlrScanTO() as integer
UartRsp(0)
endfunc 1
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function OnUartCmd() as integer
rc = -2 //Assume there is no error
tlen = ExtractStrToken(urtcmd$,tkn$) //Get first token
if tlen > 0 then
if strcmp(tkn$,"at")==0 then
rc = _at()
elseif strcmp(tkn$,"atd")==0 || strcmp(tkn$,"connect")==0 then
rc = _connect()
elseif StrCmp(tkn$,"ato")==0 || StrCmp(tkn$,"bridge")==0 then
_bridge()
rc = -1 //Don't give response to user
elseif strcmp(tkn$,"scan")==0 then
rc = _scan()
elseif StrCmp(tkn$,"ato")==0 || StrCmp(tkn$,"bridge")==0 then
rc = SendMsgApp(0,BRIDGE_VSP_MODE)
rc = -1 //Don't give response to user
elseif StrCmp(tkn$,"ath")==0 || StrCmp(tkn$,"disconnect")==0 then
rc = _disconnect()
elseif strcmp(tkn$,"misc")==0 then
rc = _misc()
elseif strcmp(tkn$,"stop")==0 then
rc = BleScanStop()
elseif strcmp(tkn$,"quit")==0 || strcmp(tkn$,"exit")==0 then
if (InConnection == 1) then
//Disconnect
rc = _disconnect()
endif
print "\nVersion ";APP_VERSION
exitfunc 0
elseif strcmp(tkn$,"bdaddr")==0 then
s$[1] = SysInfo$(4)
print "\n";StrHexize$(s$[1])
endif
endif
//Send a response back to the user
UartRsp(rc)
endfunc 1
//------------------------------------------------------------------------------
// This handler is called when data has arrived at the serial port
//------------------------------------------------------------------------------
function HndlrUartRxCmd()
dim nMatch : nMatch = 0
//Check if CR has been received
nMatch=UartReadMatch(stRsp$,13)
if nMatch!=0 then
//CR exists in the input buffer
urtcmd$ = strsplitleft$(stRsp$,nMatch)
exitfunc OnUartCmd()
endif
endfunc 1
//------------------------------------------------------------------------------
// Called after SendMsgApp is called. Used to switch between command and bridge mode
// cmd: 0 = switch to command mode
// 1 = switch to bridge mode
//
// msgID: Not Used
//------------------------------------------------------------------------------
function SetMode(msgID, cmd) as integer
if cmd==BRIDGE_VSP_MODE then
if InConnection == 0 then
print "\n";nc$;pr$
exitfunc 1
endif
ONEVENT EVUARTRX CALL HndlrUartRxVSP
print ok$;"\n"
elseif cmd==CMD_MODE then
ONEVENT EVUARTRX CALL HndlrUartRxCmd
UartRsp(0)
endif
endfunc 1
//------------------------------------------------------------------------------
// This handler is called when there at least one scan response waiting to be read
//------------------------------------------------------------------------------
function HndlrScanResp()
DIM periphAddr$, advData$, nDiscarded, nRssi, nme$
//Read all cached advert reports
rc=BleScanGetAdvReport(periphAddr$, advData$, nDiscarded, nRssi)
WHILE (rc == 0)
rc = BLEGETADBYTAG(advData$, 0x09, nme$)
print "\nSCAN: "; StrHexize$(periphAddr$), nRssi, nme$
rc=BleScanGetAdvReport(periphAddr$, advData$, nDiscarded, nRssi)
ENDWHILE
endfunc 1
//------------------------------------------------------------------------------
// Called on a transition on the nAutorun pin (DTR in UwTerminal)
//------------------------------------------------------------------------------
function HndlrGpioChan0()
dim i : i = GpioRead(28)
//If DTR unticked
if i == 1 then
TimerStart(DISCON_TIMER, DISCON_TIMER_DUR_MS, 0)
//DTR ticked -> switch to command mode
elseif TimerRunning(DISCON_TIMER)!=0 then
TimerCancel(DISCON_TIMER)
exitfunc SetMode(0, CMD_MODE)
endif
endfunc 1
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
sub Initialise()
//Just works pairing will work without confirmation
rc = BleSecMngrJustWorksConf(0)
//Use 'Just Works' pairing
rc = BleSecMngrIoCap(0)
//Bond when pairing
rc = BleSecMngrBondReq(1)
endsub
//******************************************************************************
// Equivalent to main() in C
//******************************************************************************
//Setup pairing
Initialise()
//Setup nAutorun pin to control switching between command and bridge mode
rc=GpioBindEvent(0,28,2)
//Connect to device at startup if needed
IF (CONNECT_ON_STARTUP == 1) THEN
//Connect
rc = _connect()
print "\nConnecting: ";StrHexize$(s$[1]);"\n"
ELSE
//Send user prompt
UartRsp(0)
ENDIF
//------------------------------------------------------------------------------
// Enable synchronous event handlers
//------------------------------------------------------------------------------
ONEVENT EVBLEMSG CALL HndlrBleMsg
ONEVENT EVBLE_CONN_TIMEOUT CALL HndlrConnTO
ONEVENT EVFINDCHAR CALL HndlrFindChar
ONEVENT EVATTRWRITE CALL HndlrAttrWrite
ONEVENT EVATTRNOTIFY CALL HndlrAttrNotify