Home
User Guide - smartBASIC BL600 Extensions
Contents
1. Laird smartBASIC BL600 Extensions User Manual Release 1 5 70 0 r5 global local Embedded Wireless Solutions Support Center http ews support lairdtech com Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Asia 852 2923 0610 www lairdtech com bluetooth smart BASIC User Manual 2014 Laird Technologies All Rights Reserved No part of this document may be photocopied reproduced stored in a retrieval system or transmitted in any form or by any means whether electronic mechanical or otherwise without the prior written permission of Laird Technologies No warranty of accuracy Is given concerning the contents of the information contained in this publication To the extent permitted by law no liability including liability to any person by reason of negligence will be accepted by Laird Technologies its subsidiaries or employees for any direct or indirect loss or damage caused by omissions from or inaccuracies in this document Laird Technologies reserves the right to change details in this publication without notice Windows is a trademark and Microsoft MS DOS and Windows NT are registered trademarks of Microsoft Corporation BLUETOOTH is a trademark owned by Bluetooth SIG Inc U S A and licensed to Laird Technologies and its subsidiaries Other product and company names herein may be the trademarks of their respective owners Laird Technologies Saturn House Mercury Park Wooburn Green Bu
2. INTEGER a result code neim Typical value 0x0000 indicates a successful operation Arguments byVal charHandle AS INTEGER charHandle This is the handle to the characteristic whose value must be updated which was returned when BleCharCommit was called byRef attrS AS STRING attr I l St String variable contains new value to write to the characteristic Interactive No Command Example BleCharValueWrite sb See in BL600CodeSnippets zip DIMM C Nar re SS SSS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS j Initialise and instantiate service characteristic I E FUNCTION OnStTartup DIM REF ASYG aTtTreS 2 abero ar commit service re BleServiceNew 1 BleHandleUuidl6 0x18EE hSvc Americas 1 800 492 2320 Option 2 102 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual initialise char write read enabled accept signed writes rc BleCharNew 0x4A BleHandleUuidl16 1 BleAttrMetaData 1 1 20 0 rc 0 0 commit Char initialised above With Initial value hi to service hovo rc BleCharCommit hSvc attrs hMyChar commit changes to service rc BleServiceCommit hsve ENDEAUNOCH AEG EUNCT ION Bnidlevarekx Timers tart 0 105 0 ND ONE VAL FUNCTION HndlrTmroO DIM t rc UartRead t re BleCharValueWrite hMyChar ts IF rc 0 THEN PRINT nNew characteristi
3. I O UART I2C SPI Drivers BLE Radio Bluetooth Low Energy Stack Figure 1 BLE smartBASIC module block diagram 2 INTERACTIVE MODE COMMANDS Interactive mode commands allow a host processor or terminal emulator to interrogate and control the operation of a smarfBASIC based module Many of these emulate the functionality of AT commands Others add extra functionality for controlling the filing system and compilation Process Syntax Unlike commands for AT modems a soace character must be inserted between AT the command and subsequent parameters This allows the smart BASIC tokeniser to efficiently distinguish between AT commands and other tokens or variables starting with the letters at Example PRY lees The response to every Interactive mode command has the following form lt linefeed character gt response text lt carriage return gt This format simplifies the parsing within the host processor The resoonse may be one or multiple lines Where more than one line is returned the last line has one of the following formats lt lf gt 00 lt cr gt for a successful outcome or lt lf gt 01 lt tab gt hex number lt tab gt optional verbose explanation lt cr gt for failure Americas 1 800 492 2320 Option 2 6 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note In the case of the 01 response the l
4. IF rc 0 THEN WALITEVENT ENDL PRINT AnS write aga n tO azerioute handle 3 atHndl 3 aees 0a 06 W077 Oe rc BleGattcWriteCmd conHndl atHndl ats IF rc 0 THEN WALITEVENT BNIDIL E PRINT n write again to attribute handle 3 atHndl 3 atS 09 0A 0B 0C rc BleGattcWriteCmd conHndl atHndl at IF rc 0 THEN WALITEVENT ENDIF PRINT nwrite to attribute handle 300 which does not exist atHndl 300 rc BleGattcWriteCmd conHndl atHndl atS IF rc 0 THEN PRINT nEven when the attribute does not exist an event will occur WALTEVENT ENIDILE CloseConnections ENDIF ENDFUNC 1 function HandlerNotifyBuf as integer print nEVNOTIPYBUP Event endfunc 0 need to progress the WAITEVENT J BEEE Main equivalent J EES ONE VENT EVBLEMSG CALL HndlrBleMsg Onbvent EYVNOTIFPYBUF Call HandlerNotityBuUT IF OnStartup 0 THEN Americas 1 800 492 2320 Option 2 151 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nAdvertising and Gatt Client is open n ELSE PRINT inmate Oneterrue ENDIF WALTEVENT PRINT ANNELI CING A Expected Output Advertising and Gatt Client is open Connected so write to attribute handle 3 EVNOTIFYBUF Event write again to attribute handle 3 EVNOTIFYBUF Event write again to attribute handle 3 EVNOTIFYBUF Event write to attribute handle 300 which
5. Peripheral Preferred Connection Parameters characteristic of the GAP service This value must be smaller than nSupervisionTimeout nMaxConninterval 1 i e nSlaveLatency lt nSupervisionTimeout nMaxConninterval 1 Interactive No Command Example BleGapSvcInit sb See in BL600CodeSnippets zip DIM iaePdivchines nmenNr tole apomnce MaimConmlniw MaxConnml rit Ommolo lO 1s lyst dvcNmes Laird TS nmeWrtble 0 Device name will not be writable by peer apprnce 768 The device will appear as a Generic Thermometer Main cami 500000 Minimum acceptable connection interval is 0 5 seconds MaxGonmine 1000000 Maximum acceptable connection interval is 1 second ConnsuplO 4000000 Connection supervisory timeout is 4 seconds sL 0 Slave latency number of conn events that can be missed re pleGapovelinik dvelmes nmevirrole apeornece Man onmnink MaxConmint Conmsuel sik LE re THEN PRINT nsuecess ELSE PRINT eatled 0x1 INTEGER NTC Print result code as 4 hex digits ENDIF Expected Output BLEGAPSVCINIT is an extension function Americas 1 800 492 2320 Option 2 80 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleGetDeviceNameS FUNCTION This function reads the device name characteristic value from the local gatt table This value is the same as that sup
6. 0 THEN PRINT nAdvertising and Gatt Client is open n ELSE PRINT Thea Ire On wer tu ENDIF WALTEVENT US SE NEIEN aa Expected Output Americas 1 800 492 2320 Option 2 131 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Advertising and Gatt Client is open Connected so scan remote Gatt Table for first service and a characeristic scan will be initiated in the event EVDISCPRIMSVC cHndl 3790 svcUuid FEOLFEO2 sHndl 1 eHndl 11 Got first primary service so scan for ALL characteristics EVDISCCHAR cHnd1l 3790 chUuid FEO1FC21 Props 2 valHndl 3 ISvcUuid 0 Got first characteristic service at handle 3 Scan tor ALL Descs EVDISCDESC BVDLSCDESG EVDISCDESC BVDISCDESC EVDISCDESC EVDISCDESC EVDISCDESC EVDISCDESC EVDISCDESC cHnd1l 3790 cHnd1l 3790 cHnd1l 3790 cHnd1l 3790 cHnd1l 3790 cHnd1l 3790 cHnd1l 3790 cHnd1l 3790 cHnd1 3790 dscUuild FEO1FD21 dscUuid FC033344 dscUuid FE01 DEAD dscUuid FBO04BEEF dscUuid FC033344 dscUuid FEO1LFD23 dscUuid FE01DEAD dscUuid FE0O1DEAD dscUuid 00000000 dscHndl 4 dscHndl 5 dscHnd1l 6 dscHndl 7 dscHnd1l 8 dscHnd1l 9 dscHnd1l 10 dscHndl 11 dscHnd1l 0 Descriptor Scan complete Scan for descritors with uuid OxDEAD EVDISCDESC cHnd1 3790 dscUuid FEO1DEAD dscHnd1l 6 EVDISCDESC cHnd1l 3790 dscUuid FEOIDEAD dscHndl 10 EVDISCDESC cHnd1l 3790 dscUuid FEO1LDEA
7. Americas 1 800 492 2320 Option 2 92 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual byVal mdVal AS INTEGER This is the mandatory metadata that is used to define the properties of the Value attribute that will be created in the Characteristic and will have been pre created using the help of the function BleAttrMetadata byVal mdCccd AS INTEGER This is an optional metadata that is used to define the properties of the CCCD Descriptor attribute that will be created in the Characteristic and will have been mdCccd pre created using the help of the function BleAttrMetadata or set to 0 if CCCD is not to be created If nNCharProps specifies that the Characteristic is notifiable or indicatable and this value contains O this function will abort with an appropriate result code byVal mdSccd AS INTEGER This is an optional metadata that is used to define the properties of the SCCD Descriptor attribute that will be created in the Characteristic and will have been mdSccd pre created using the help of the function BleAttrMetadata or set to 0 if SCCD is not to be created If nCharProps specifies that the Characteristic is broadcastable and this value contains O this function will abort with an appropriate resulfcode mdVal Interactive No Command Example BleCharNew sb See in BL6OO00CodeSnippets zip Dik tree D
8. BleGattcClose sb See in BL600CodeSnippets zip BUR are open the gatt client with default notify indicate ring buffer size rc BleGattcOpen 0 0 IF rc 0 THEN PRINT nGatt Client is now open ENDIF BleGattcClose PRINT nGatt Client is now closed BleGattcClose PRINT nGatt Client is closed was safe to call when already closed Expected Output Gatt Client is now open Gatt Client is now closed Gatt Client is closed was safe to call when already closed BLEGATTCCLOSE is an extension subroutine BleDiscServiceFirst BleDiscServiceNext FUNCTIONS This pair of functions is used to scan the remote Gatt Server for all primary services with the help of the EVDISCPRIMSVC message event and when called a handler for the event message must be registered as the discovered primary service information is passed back in that message A generic or uuid based scan can be initiated The former will scan for all primary services and the latter will scan for a primary service with a particular uuid the handle of which must be supplied and is generated by using either BleHandleUvid16 or BleHandleUvid128 While the scan is in progress and waiting for the next piece of data from a Gatt server the module will enter low power state as the WAITEVENT statement is used as normal to wait for events and messages Depending on the size of the remote GATT server table and the connection interval the scan of all primary may take many
9. Example BleAdvGetADbyIndex sb See in BL600CodeSnippets zip DIM ro adl ad2 ftulilAbs NADTag Abyals Americas 1 800 492 2320 Option 2 61 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual AD with length 6 bytes tag 0xDD adis O6 BDD 1i1 22 32 4455 AD with length 7 bytes tag OxDA ad2s 07 EE AA BB CC DD BE EE IP DUM NDIS excl 45 eiciZ s PRINT ae Gn Semi enc mem a Ae Waa nADTag OxDD rc BleGetADbyTag fullADS nADTag ADvalS ip yec O 7 HEN PRINT nAD element with tag 0x INTEGER H nADTag is StrHexizeS ADval ELSE PRINT nbwror reading AD i INTEGER Hire TEIN BIE E nADTag OXEE rc BleGetADbyTag fullADS nADTag ADvalS ie re O THEN PRINT nAD element with tag 0x INTEGER H nADTag is StrHexizeS ADval ELSE PRINT nkeror reading AD INTEGER Hro TEIN E nADTAG 0xFF Will fail because no AD exists in fullADS with the tag FF rc BleGetADbyTag fullADS nADTag ADvalS IF rc 0 THEN PRINT nAD element with tag 0x INTEGER H nADTag is StrHexizeS ADval ELSE PRINT A OError redding AD T INTEGER Hre ENDIF Expected Output 06DD11223344550 7EEAABBCCDDEEFF AD element with tag 0x000000DD is 1122334455 AD element with tag 0x000000EE is AABBCCDDEEFF Error reading AD 00006060 BLEGETADBYTAG Is an extension func
10. No Command Example BleGattcFindDesc sb See in BL600CodeSnippets zip ce Remote server has 5 prim services with 16 bit uuid and 3 with 128 bit uuids je of the 16 bit uuid are the same value OxDEAD and J 2 Or the 128 birt uuids are also the same 1122334455667798 99AABBCCDDEEFEE a Americas 1 800 492 2320 Option 2 138 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual jj Seeyese Greece Usiiag BleGecicllolescbese silo aimyokecl ii Coeidilicis sieic using Nordt e Uch Dongle ee LOUGe Dil Mee ae se OmMaine leu ner aa a hee hehe a DUNG ROM Ons pace le DIM ro adhere adc o aOR re BlleAdvRpEIni amp adRpto 2 0 10 TE cc 0 THEN rc EleScanRptInit CRPE ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt scRpt ENDIF if Tre 0 THEN re B leAGvyertStare O0raddro 50 0 0 ENDIF fopen the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF El DEUNG vase SUB Closetonneerilens rc BleDisconnect conHnd1 rc BleAdvertStop PLD SUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx Dim Une Ss UNo UR Wigharcly conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected CMa UiNe 0 ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for ALL services uHndS BleHandleUuidl6 OxDEAD uuo LI AS SE
11. This section describes all the connection manager related routines The Bluetooth specification stipulates that a peripheral cannot initiate a connection but can perform disconnections Only Central Role devices are allowed to connect when an appropriate advertising packet Is received from a peripheral Events and Messages See also Events and Messages for BLE related messages that are thrown to the application when there is a connection or disconnection The relevant message IDs are 0 1 14 15 16 17 18 and 20 0 There is a connection and the context parameter contains the connection handle There is a disconnection and the context parameter contains the connection handle 14 New connection parameters for connection associated with connection handle 15 Request for new connection parameters failed for connection handle supplied 16 The connection is to a bonded master Americas 1 800 492 2320 Option 2 63 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 17 The bonding has been updated with a new long term key 18 The connection is encrypted 20 The connection is no longer encrypted BleDisconnect FUNCTION This function causes an existing connection identified by a handle to be disconnected from the peer When the disconnection is complete a EVBLEMSG message with msgld 1 and context containin
12. latency to be negotiated with the master Note An adjusted value is used if this value times the value in 106 is greater than the supervision timeout in 107 When in interactive mode and connected for virtual serial port services this is the Tx power used for adverts and connections Note A low value is set to ensure that in production if smart BASIC applications are downloaded over the air the limited range allows many stations to be used to program devices If Virtual Serial Port Service is enabled in interactive mode see 100 then this specifies the size of the transmit ring buffer in the managed layer sitting above the service characteristic fifo register Value range 32 to 256 If Virtual Serial Port Service is enabled in interactive mode see 100 then this specifies the size of the receive ring buffer in the managed layer sitting above the service characteristic fifo register Value range 32 to 256 If set to 1 then the service UUID for the virtual serial port is as per Nordic s implementation and any other value is per Laird s modified service See more details of the service definition here This is the advert interval in milliseconds when advertising for connections in interactive mode and UART bridge mode Valid values 20 to 10240 milliseconds This is the advert timeout in milliseconds when advertising for connections in interactive mode and UART bridge mode Americas 1 800 492 2320 Option 2 9 Laird Tech
13. nChar created and User Description usrDescS added ELSE PRINT nFailed ENDIF Expected Output Char created and User Description A description added BLECHARDESCUSERDESC Is an extension function BleCharDescPrstnFrmt FUNCTION Americas 1 800 492 2320 Option 2 94 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This function adds an optional Presentation Format Descriptor to a Characteristic and can only be called after BleCharNew has started the process of describing a new Characteristic It adds the descriptor to the gatt table with open read permission and no write access which means a metadata parameter is not required The BT 4 0 specification states that one or more presentation format descriptors can occur in a Characteristic and that if more than one then an Aggregate Format description is also included The book Bluetooth Low Energy The Developer s Handbook by Robin Heydon says the following on the subject of the Presentation Format Descriptor One of the goals for the Generic Attribute Profile was to enable generic clients A generic client is defined as a device that can read the values of a characteristic and display them to the user without understanding what they mean The most important aspect that denotes if a characteristic can be used by a generic client is the Characteristi
14. nFilterPolicy Interactive Command Example DIM addr byRef peerAddrS AS STRING It can be an empty string that is omitted if the advertisement type is not ADV_DIRECT_IND This is only required when nAdvType 1 When not empty a valid address string is exactly seven octets long such as OO 1 1 22 33 44 55 66 where the first octet is the address type and the rest of the 6 octets is the Usual MAC address in big endian format so that most significant octet of the address Is at offset 1 whether public or random O Public 1 Random Static 2 Random Private Resolvable 3 Random Private Non resolvable All other values are illegal byVal nAdvinterval AS INTEGER The interval between two advertisement events in milliseconds An advertisement event consists of a total of three packets being transmitted in the three advertising channels Interval range Between 20 and 10240 milliseconds byVal nAdvTimeout AS INTEGER The time after which the module stops advertising in milliseconds Value range Between 0 and 16383000 milliseconds rounded up to the nearest one seconds or 1000 ms A value of 0 means disable the timeout but note that if limited advert modes was specified in BleAdvRoptinit then the timeout is capped to 180000 ms as per the Bluetooth Specification When the advert type specified is ADV_DIRECT_IND the timeout is automatically set to 1280 ms as per the Bluetooth Specification Warning To save power d
15. N None O Odd Not Available E Even Not Available 2 Databits 8 3 Stopbits Flow Control 4 N None H CTS RTS hardware X Xon Xoft Not Available UartCloseEx Note On the BL600 firmware versions older than 1 3 57 3 the following bug exists If the RX and TX buffers are not empty an internal pointer is still set to NULL This results in unpredictable behavior Workaround Use Uartlnfo 6 to check if the buffers are empty and then call UartClosekRx 1 as per the example below Workaround for FW 1 3 57 0 and earlier BL600 Example UartCloseExWA sb See in Firmware Zip file DIM red Dil mae UartClose roel UseLOpen 9600 0 0 CNeln open as DTE at 300 baudrate odd parity IS Gaart 1 Wesceleiies jes ees ve le aoon ro Americas 1 800 492 2320 Option 2 15 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT CLAIS Workaround fom bug for fiemware versions older than 173 57 3 IE Varini 6 1 0 THEN PRINT nDatae im at least one buller Uart Port not closed BLSE rc2 0UartCloseEx 1 rel Uartopen 9600 0 0 TCN81FT open as DTE at 300 baudrate odd parity PRINT nThe Uart Port was closed ENDIF For FW 1 3 57 3 and newer BL600 Example UartCloseEx sb See in Firmware Zip file DME DINEAR UartClose rol UartOpen 9600 0 0
16. New Connection 134 Conn Interval 30000 Conn Supervision Timeout 720000 Conn Slave Latency 0 Request new parameters New conn Interval T5000 New conn Supervision Timeout 4000000 conn Slave Latency 19 Disconnected 134 Note First set of parameters will differ depending on your central device BLESETCURCONNPARMS is an extension function Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 67 Laird Technologies smart BASIC User Manual BleGetCurConnParms FUNCTION This function gets the current connection parameters for the connection identified by the connection handle Given there are three connection parameters the function takes three variables by reference so that the function can return the values in those variables BLEGETCURCONNPARMS nConnHandle nintervalUs nSuprToutUs nSlaveLatency Returns INTEGER a result code Typical value 0x0000 indicates a successful operation Arguments byVal nConnHandle AS INTEGER nConnHandle Specifies the handle of the connection that needs to have the connection parameters changed byRef nintervalUs AS INTEGER The current connection interval in microseconds byRef nSuprToutUs_ AS INTEGER The current link supervision timeout in microseconds for the connection byRef nSlaveLatency AS INTEGER This is the current number of connection interval polls that the p
17. OT INTEGER H vl PRINT UC avelenech in Decimal sale yil an read unsigned byte from index 6 rc BleDecodeU8 attrS vl1 6 PRINT Andata in Hex Ox INTEGER H vl PRINTE V ndata in Decimal ways ia Expected Output Americas 1 800 492 2320 Option 2 169 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth in Hex 0x00000002 in Decimal 2 in Hex 0x00000086 in Decimal 134 BLEDECODEU8 Is an extension function BleDecodeS16 FUNCTION This function reads two bytes in a string at a specified offset into a 32bit integer variable with sign extension If the offset points beyond the end of the string then this function falls BLEDECODES16 attrS nData nindex INTEGER the number of bytes extracted from the attribute string Can be less than Returns the size expected if the nilndex parameter is positioned towards the end of the string Arguments attrs byRef attrS AS STRING This references the attribute string from which the function reads byRef nData AS INTEGER nData This references an integer to be updated with the 2 byte data from attr after sign extension byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the NAEK string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive No Command
18. PRINT nlhe actual frequency Of the PWM output is ener regia TAn A now configure SIO2 pin as a PWM output PRINT CprocetPunc 272 2 3rd parameter is subfunc PWM output Set PWM output to 0 GpioWrite 2 0 Set PWM output to 50 GpioWrite 2 nMaxRes Z2 7 See Meee tie ee IOS GpioWrite 2 nMaxRes any value gt nMaxRes will give a 100 duty cycle Set PWM output to 33 3332 GpioWrite 2 nMaxRes 3 Expected Output O The actual frequency of the PWM output is 1000 O GPIOCONFIGPWM is a Module function GpioRead FUNCTION This routine reads the value from a SIO special purpose I O pin The module datasheet will contain a pinout table which will mention SIO Special I O pins and the number designated for that special I O pin corresponds to the nSigNum argument GPIOREAD nSigNum INTEGER the value from the signal If the signal number is invalid it returns the value 0 For digital pins the value is O or 1 For ADC pins it is a value in the range penne of O to M where M is the maximum based on the bit resolution of the analogue to digital converter Arguments nSigNum byVal nSigNum INTEGER The signal number as stated in the pinout table of the module Americas 1 800 492 2320 Option 2 23 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive No Command Example
19. String variable containing new value to write to the characteristic and attr os l then send as a notification to the client If there is no connection this function fails with an appropriate result code Interactive No Command Example BleCharValueNotify sb See in BL600CodeSnippets zip DIM iMy Chats paws combine it BUNGTI Ol wens taceno DIM Mae ye howe cil arte adot sald Glico mS eR Dir ate co hi DIM m Cee meee BWettrriletacdatan yl Or ce CE Dm e adaa hore a Conni eye with handle nsveUliad rc BleServiceNew 1 BleHandleUuidl6 0x18EE hSvc initialise char write read enabled accept signed writes notifiable rc BleCharNew 0x12 BleHandleUuidl16 1 BleAttrMetaData 1 0 20 0 rc mdCccd 0 commit char initialised above with initial value hi to service hMyChar rc BleCharCommit hSvc attrs hMyChar commit changes to service rc BleServiceCommit hSvc rc BleScanRptInit scRpt Add 1 service handle to scan report e 5 La Neve oe NCU Waele Selon a e a commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addrs 50 0 0 ENDEUNCG ce SUB Closeconnect ions rc BleDisconnect conHnd1 rc BleAdvertStop Americas 1 800 492 2320 Option 2 104 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ENDSUB FUNCTION HndlrBleMsg BYVAL nMs
20. WALILTEVENT PRENT noe at or chaser e rote Vien Wut OxDEADY uHndl BleHandleUuidl6 OxDEAD re BlebrseCharhirst Comhmd ly uhm sAtrr eArtter IF rc 0 THEN HandlerCharDisc will exit with 0 when operation is complete WALTEVENT uuS 112233445566778899AABBCCDDEEFFOO PRIN Y nnanscan tor seryice wira Custom uue uus Americas 1 800 492 2320 Option 2 124 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual uuS StrDehexizeS uu uHndl BleHandlevuidl28 uus re BlebiseCharkiret connmdl uhmdil sAbir eAtir IF rc 0 THEN HandlerCharDisc will exit with 0 when operation is complete WALTEVENT ENDIF BND IE ENDIF CleseConmecervons ENDIF ENDFUNC 1 5595555555555 555555555555555 BVDISCPRIMSVC event handler asenessssss552 555555558555 595 5555555955555 5 5955555555555 5 5555555 555555555555 PUNCTION Hand lerrrimsve chndl svcUuuid sind ehndil CER PRIN pEyDISeCPRIMSVC PRINT ene CHMEL PRINT svecuusd inceqer sh svevuid PRINT Srnec remicit PRINT eHndl eHndl IF sHnoll O THEN PRINT nPrimary Service Scan complete EXITFUNG 0 BLSE PRINT mnGot first primary service so scan for ALL characteristics SATCTE sHndl eAttr eHndl re BleDiscCharFirst confndl 0 sSsAttr eaAttr IF rc 0 THEN PRIN mSean Ccharacterl tico talled EXITFUNC
21. WALTEVENT JE SUE ie Ms DE Ena Expected Output Advertising and Gatt Client is open Connected so scan remote Gatt Table for first service and a characeristic scan will be initiated in the event EVDISCPRIMSVC cHnd1 3549 svcUuid FE01FE02 sHndl 1 eHndl 17 Got first service so scan for ALL characteristics BVDISCCHAR EVDISCCHAR EVDISCCHAR EVDISCCHAR BVDISCCHAR EVDISCCHAR EVDISCCHAR EVDISCCHAR EVDISCCHAR cHnd1 3549 cHnd1 3549 cHnd1 3549 cHnd1 3549 cHnd1 3549 cHnd1 3549 cHnd1 3549 cHnd1 3549 cHnd1 3549 chUuid FE01FC21 chUuid FC033344 chUuid FE01DEAD chUuid FB04BEEF chUuid FC033344 chUuid FE01FC23 chUuid FE01DEAD chUuid FE01DEAD chUuid 00000000 E T Scan complete Scan for characteristic EVDISCCHAR EVDISCCHAR EVDISCCHAR EVDISCCHAR cHnd1 3549 cHnd1 3549 cHnd1 3549 cHnd1 3549 with uuid chUuid FEO1DEAD chUuild FEO1DEAD chUuuid FEO1DEAD chUuid 00000000 Characteristic Scan complete Props 2 Props 2 Props 2 Props 2 Props 2 Props 2 Props 2 Props 2 Props 0 OxDEAD Props 2 Props 2 Props 2 Props 0 valHndl 3 valHndl 5 TSvcUuid 0 TSvcUuid 0 valHndl 7 ISvcUuid 0 valHndl 9 ISvcUuid 0 valHndl 11 ISvcUuid 0 valHndl 13 ISvcUuid 0 valHndl 15 ISvcUuid 0 valHndl 17 ISvcUuid 0 valHndl 0 ISvcUuid 0 valHndl 7 ISvcUuid 0 valHnd1l 15 ISvcUuid 0 valHndl 17 ISvcUuid 0 valHndl 0 ISvcUuid 0 Scan for service with custom uuid 1122334455667788 99AABBCCDDEEFFOO cHnd1l 3549 chUuid FC0
22. dp 45 rc BleTxPowerSet dp PRINT nTx power desmred dp eaectudl Sysinto 20038 de 1000 rc BleTxPowerSet dp PRINT nTx power desired dp actual SysInfo 2008 Expected Output desired 1000 desired 8 desired 2 10 5 A 5 1000 desired desired desired desired actual actual actual actual actual actual actual BLETXPOWERSET is an extension function BleTxPwrWhilePairing FUNCTION This function sets the transmit power of all packets that are transmitted while a pairing is in progress This mode of pairing is referred to as Whsiper Mode Pairing The actual value is clipped to the transmit power for normal operation which is set using BleTxPowerSet function The actual value is determined by scanning through the value list 4 0 4 8 12 16 20 30 55 so that the highest value that is less than the desired value is selected If the desired value is higher than 55 55 is set For example setting 1000 results in 4 3 results in 4 100 results in 55 At any time SYSINFO 2018 returns the actual transmit power setting Or when in command mode use the command AT 2018 BLETXPWRWHILEPAIRING nTxPower INTEGER a result code Reins Typical value Ox0000 indicates a successful operation Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 48 La
23. ee Blescankoc Ine ScReEs ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpts scRpt ENDIF Americas 1 800 492 2320 Option 2 143 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual te ve 0 THEN re BleAdvertStart 0 addrs 50 0 0 ENDIF fopen the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDEUNG re SUB Closet onnecrions rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx DIM uHndA conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNGC Q ELSEIF nMsgID 0 THEN PRINT n Connected so read attibute handle 3 atHndl 3 norr 0 rc BleGattcRead conHndl atHndl nOff IF rc 0 THEN WALITEVENT BNDIF PRINT nread attibute handle 300 which does not exist atHndl 300 noff 0 rc BleGattcRead conHndl atHndl nOff IF rc 0 THEN WALTEVENT BENDI IE CloseConnections ENDIF ENDEUNCG 1 LuMmeruOnm HancdherAterReao chndlyaknicdib mots as inbeger dim norse rAd cite gt print nEVATTRREAD Drie seh mel Hna Print attrkndi gt anndil print T Stetus j integer h nots if nSts 0 then Print nAttribute read OK rc BleGattcReadData cHndl nAhndl1 nOfst atS Prine Anata o trrHexize ats Print T OFCSertS mortar print Len strlen a
24. nPassKey INTEGER a result code ELUN Typical value 0x0000 indicates a successful operation Arguments byVal connHandle AS INTEGER connHandle This is the connection handle as received via the EVBLEMSG event with msgld set to 0 byVal nPassKey AS INTEGER nPassKey This is the passkey to submit to the stack Submit a value outside the range 0 to 999999 to reject the pairing Interactive No Command Example BleSecMngrPasskey sb See in BL600CodeSnippets zip DM Miser rc Onmrtanc ke DIM addrs addrs FUNCTION HandlerBleMsg BYVAL nMsgid AS INTEGER BYVAL nCtx AS INTEGER AS INTEGER SELCE MMSE CANE O COnmaancd ker C PRINT n Ble Connection nCtx CASE 1 PRINT n Disconnected s nCtx n EXITFUNG Q CASH 101 PRINT n Auth Key Request type nCtx rc BleSecMngrPassKey connHandle 123456 IF rc 0 THEN key is 123456 PRINT nPasskey 123456 was used BLSE PRINT nResult Code Ox integer h rc ENDIF CASH ELSE ENDS EME Cr ENDEUNG ONEVENT EVBLEMSG CALL HandlerBleMsg rc BleSecMngriloCap 4 Set i o capability Keyboard Only authenticated pairing IF BleAdvertStart 0 addrS 25 0 0 0 THEN PRINT nAdverts Started n PRINT nMake a connection to the BL600 ELSE PRINE V n naAdyvercLsemenrt nor sSuccessrul ENDINE Americas 1 800 492 2320 Option 2 69 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com
25. this variable is updated with a handle to the service UUID which can then be subsequently used to advertise the service in an advert report Given svcUuid that there is no BT SIG adopted Serial Port Service the UUID for the service Is 128 bit so an appropriate Advert Data element can be added to the advert or scan report using the function BleAdvRptAddUuid128 which takes a handle of nFlags Bit O that type Related BLEVSPINFO BLEVSPCLOSE BLEVSPWRITE BLEVSPREAD BLEVSPFLUSH Commands Example BleVspOpen sb See in BL600CodeSnippets zip DIM schoo adkpilo aden 7epove hime Close VSP if already open Te BlevsSpinto 0 0 THEN BleVSpClose ENDIF Americas 1 800 492 2320 Option 2 190 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Open VSP IF BleVSpOpen 128 128 0 vspSvcHndl 0 THEN PRINT nVSP service opened ELSE PRINT nFailed ENDEE Expected Output VSP service opened BLEVSPOPEN is an extension function BleVSpClose SUBROUTINE This subroutine closes the managed virtual serial port which had been opened with BLEVSPOPEN This routine is safe to call if it is already closed When this subroutine is invoked both receive and transmit buffers are flushed If there is data in either buffer when the port is closed it will be lost BLEVSPCLOSE Ecenin Local Stack Frame Underf
26. 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals Americas 1 800 492 2320 Option 2 116 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual EVDISCPRIMSVC event message This event message WILL be thrown if either BleDiscServiceFirst or BleDiscServiceNext returns a success The message contains 4 INTEGER paramefters Connection Handle Service Uvid Handle Start Handle of the service in the Gatt Table End Handle for the service If no more services were discovered because the end of the table was reached then all parameters will contain O apart from the Connection Handle BLEDISCSERVICEFIRST connHandle startAttrHandle uvidHandle A typical pseudo code for discovering primary services involves first calling BleDiscServiceFirst then waiting for the EVDISCPRIMSVC event message and depending on the information returned in that message calling BleDiscServiceNext which in turn will result in another EVDISCPRIMSVC event message and typically is as follows Register a handler for the EVDISCPRIMSVC event message On EVDISCPRIMSVC event message If Start End Handle 0 then scan is complete Else Process information then call BleDiscServiceNext if BleDiscServiceNext not OK then scan co
27. 16 bit offset We recommend to save RAM that you create a 128 bit UUID of your own and manage the 16 bit soace accordingly akin to what the Bluetooth SIG does with their 16 bit UUIDs If command AT CFG 112 1 is used to change the value of the config key 112 to 1 then Nordic s serial port service is exposed with UUID s as follows The UUID of the service is 6e 400001 b5a3 393 e0a9 e50e24dcca9e The UUID of the rx fifo Characteristic Is 6e 400002 b5a3 393 e0a9 e50e24dcca9e The UUID of the tx fifo Characteristic Is 6e 400003 b5a3 393 e0a9 e50e24dcca9e Note The first byte in the UUID s above is the most significant byte of the UUID The rx fifo characteristic is for data that comes to the module and the tx fifo characteristic is for data that goes out from the module This means a GATT Client using this service will send data by writing into the rx fifo characteristic and will get data from the module via a value notification The rx fifo characteristic is defined with no authentication or encryption requirements a maximum of 20 bytes value attribute The following properties are enabled WRITE WRITE_NO_RESPONSE The tx fifo characteristic value attribute is with no authentication or encryption requirements a maximum of 20 bytes value attribute The following properties are enabled NOTIFY The CCCD descriptor also requires no authentication encryption The Modemin char
28. 2 Dec 2014 Added UartOpen specifics for this module Americas 1 800 492 2320 Option 2 3 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual CONTENTS ROVISION PUI SCO IY gcceecestsec acest octea nee ecietncacis cd caeeciee tances 4 cairns A 3 ROUSING AE ease A E canes E EE A E EA E A E oeacar A E A E A E E eae aon E AT 4 Tee OCUN eE E ee aeer see men gnen sere naneesres 5 D c mentation OV CLV OW aisutucndaauencounsieiananedendoansnmtancpecmutoecanssundnoesnaqiamataanpenastomtanetansacieacumoustnecisunuientemohsansanmeaonnectinny 5 What DOES a BLE Module Contain vaseccssasseactpciasinoceangsewatacasinaacancsessie aa ea aaia i 5 2 Interactive Mode COMMANGAS cccccccecececececueueueueuaueecusuatatatatatataeaeaeaeaeaegeeegeneueaegeaeaeeeenenenenens 6 3 Core Language Built in ROUTINGS ccccceccececececseeeeecesececseaeaeseceseseeseatausesesesetaeaeanaeseseneeas 12 iHormation ROUNE S essri a aE E NE aE SSS a 12 UART Universal Asynchronous Receive TranSMit cccccccccsseecceccessecccceeeeecccceeeeceeseueeecesseueeecesseugeeeessaeeeeeeseaees 15 I2C Tw Wire Interface WVU seca cceacantecereciactistcncaeiecs cauehtenseceucadtssnbiodsencassantdesued antaneesctaeatbtcesatacetdessataucsasaantdeaseiaececces 17 BE Ve CO E E anda enwatan A E E E 17 4 Core Extensions Built in ROUtINGS sassassnssnnnenunnnnnnnnnnrnurnurnnrnn
29. 20 0 rc DIM hHtsMeas composite handle for htsMeas characteristic Americas 1 800 492 2320 Option 2 99 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Create the Measurement Characteristic object add user description descriptor rc BleCharNew 0x2A BleHandleUuidl16 0x2A1C mdCharVal mdCccd 0 rc BleCharDescUserDesc usrDescS mdUsrDsc attrS hello 00worl 64 IF BleCharCommit hHtsSvc attr hHtsMeas 0 THEN PRINT nCharacteristic Committed BLSE PRINT nFailed ENDIF rc BleServiceCommit hHtsSvc the characteristic will now be visible in the GATT table and is refrenced by hHtsMeas for subsequent calls Expected Output l l Characteristic Commited BLECHARCOMMIT is an extension function BleCharValueRead FUNCTION This function reads the current content of a characteristic identified by a composite handle that was previously returned by the function BleCharCommit In most cases a read will be performed when a GATT client writes to a characteristic value attribute The write event is presented asynchronously to the smart BASIC application in the form of EVCHARVAL event and so this function will most offen be accessed from the handler that services that event BLECHARVALUEREAD charHandle attrS INTEGER a result code Kerot Typical value 0x0000 indicates a successful operati
30. Appearance characteristic of the GAP service Possible values org bluetooth characteristic gap appearance byVal nMinConninterval AS INTEGER The preferred minimum connection interval updates the Peripheral Preferred Connection Parameters characteristic of the GAP service Range is between 7500 and 4000000 microseconds rounded to the nearest 1250 microseconds This must be smaller than nMaxConninterval byVal nMaxConnlinterval AS INTEGER The preferred maximum connection interval updates the Peripheral nAppearance nMinConnlInterval nMaxConnlinterval Americas 1 800 492 2320 Option 2 79 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Preferred Connection Parameters characteristic of the GAP service Range is between 7500 and 4000000 microseconds rounded to the nearest 1250 microseconds This must be larger than nMinConninterval byVal nSupervisionTimeout AS INTEGER The preferred link supervision timeout and updates the Peripheral nSupervisionTimeout Preferred Connection Parameters characteristic of the GAP service Range is between 100000 to 32000000 microseconds rounded to the nearest 10000 microseconds byVal nSlaveLatency AS INTEGER The preferred slave latency is the number of communication intervals that a slave may ignore without losing the connection and updates the nSlaveLatency
31. BLU s4 EVCHARSCCD This event is thrown when the client writes to the SCCD descriptor of a characteristic It comes with two parameters The characteristic handle that was returned when the characteristic was registered using the function BleCharCommit 2 The new 16 bit value in the updated SCCD attribute The SCCD is used to manage broadcasts of characteristic values Example EvCharSccd sb See in BL600CodeSnippets zip DIM hiMy Chiat re eh Vals comlamcrl FUNCTION OnSstartup DENE Eo aE aE a add e a oe a EEE N DIM charMet charMet BleAttrMetaData 1 1 20 1 rc Create service rc BleServiceNew 1 BleHandleUuidl6 Ox18EKE hSvc initialise broadcast capable readable writeable rc BleCharNew 0x0B BleHandleUuidl6 1 charMet 0 BleAttrMetadata 1 1 1 0 rc2 Commit Char anttialised above with initial value na vo service hMyChax Americas 1 800 492 2320 Option 2 39 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleCharCommit hSvc attrs hMyChar commit service to GATT table rc BleServiceCommit howe rC BleAdvertStart 0 adde 20 300000 0 EM DEUNCG ce SUB loseConnections rc BleDisconnect conHndl rc BleAdvertStop rc GpioUnbindEvent 1 ENDSUB FUNCTION PrepAdvReport dim adRpto ashes Sveta initialise new advert report Yc BleAdvRptinit a
32. BleAdvertStop FUNCTION This function causes the BLE module to stop advertising BLEADVERTSTOP INTEGER a result code naiur Typical value 0x0000 indicates a successful operation Arguments None Interactive No Command Example BleAdvertStop sb See in BL600CodeSnippets zip DIMERS cicleiao Div see FUNCTION HndlrBlrAdvTimOut PRINT nAdvert stopped via timeout PROMS nei ng o ENDFUNC 0 FUNCTION BenOPress IF BleAdvertStop 0 THEN Americas 1 800 492 2320 Option 2 53 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nAdvertising Stopped ELSE PRINT ni nAdvertising Lalled to stop ENDIF PRINTE ib scsi seta Caemere ENDEUNC 10 IF BleAdvertStart 0 addrS 25 O00000 00 THEN PRINT nAdverts Started Press button 0 to stop n ELSE BRINE a naidvectrutsecmcnb nort Successtral ENDTE TE GpLeser rune 16071 2 rE GpioBindEvent 0 16 1 CNEVENT SiYBLE ADV TIMEOUl SeALli tnd lr E A lamouwt ONEVENT EVGPIOCHANO CALL BtnOPress WALTEVENT Expected Output Adverts Started Press button 0 to stop Advertising Stopped Belen sa BLEADVERTSTOP is an extension function BleAdvRptinit FUNCTION This function is used to create and Initialise an advert report with a minimal set of ADs advertising records and store it the string specified It is not adver
33. DIM conHndl SUB OnStarTtua DIM ee laiacll iS a a a a aao re BleVopopen 128 128 0 nnd rc BleScanRptInit scRpt rc BleAdvRptAddUuidl128 scRpts hnd1 rc BleAdvRptsCommit adRpt scRpts re pbleAdvertStare 0 addro 20 200000 0 rc GpioBindEvent 1 16 1 Channels i band wo low erancabtonvon GelOnoin Ie PRINT nDevice name is BleGetDeviceNames n bcS nGemcd me some text nPress bucton 0 CO exicy n re BleVSpWrite tx ENDSUB SUB CloseConnections DIM FE rc BleDisconnect conHndl rc BleAdvertStop Americas 1 800 492 2320 Option 2 197 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleVspClose ENDSUB PUNCTION HndlrBleMsg BYVAL NMsgld BYVAL MCEX conHndl nCtx IF nMsgID 1 THEN PRINT nDisconnected from client CALS OIE 10 ENDIF ENDFUNC 1 PUNCTION HndieBendP AS INTEGER just exit and stop waiting for events BADE UNC 30 FUNCTION HandlerBradge AS INTEGER transfer data between VSP and UART ring buffers BleVspUartBridge ENDFUNC 1 ONEVENT EVVSPRX CALL HandlerBridge ONEVENT EVUARTRX CALL HandlerBridge ONE VERN S BV VS PE MP iy CALL HandlerBridge ONEVENT EVUARTTXEMPTY CALL HandlerBridge ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT EVGPIOCHANL CALL HadiliwBr nvr OnStartup WAITEVENT Coce onne e on mer ale e d aero e rade Cleared abone PP T
34. GATT server table and the connection interval the search of the characteristic may take many 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals Note Itis not currently possible to scan for characteristics in included services This will be a future enhancement EVFINDCHAR event message This event message WILL be thrown if BleGattcFindChar returns a success The message contains 4 INTEGER parameters Connection Handle Characteristic Properties Handle for the Value Attribute of the Characteristic Included Service Uvid Handle If the specified instance of the service characteristic is not present in the remote Gatt Server Table then all parameters will contain O apart from the Connection Handle Characteristic Properties contains the properties of the characteristic and is a bit mask as follows BitO Set if BROADCAST is enabled Bit 1 Set if READ is enabled Bit2 Set if WRITE_WITHOUT_RESPONSE is enabled Bit3 Set if WRITE is enabled Bit4 Set if NOTIFY is enabled Bit5 Set if INDICATE is enabled Bit Set if AUTHENTICATED_SIGNED_WRITE is enabled Bit 7 Set if RELIABLE_WRITE is enabled Bit 15 Set if the characteristic has extended properties Americas 1 800 492 2320 Option 2 133 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com
35. HandlerrPrimsve cChndl sevcvuuid shnmdl ehndl AS INTEGER PRI nly piSCPR IMS VC ee OINME lt e elutavcliiae Se layarelde PRINT M svcUurd amt egernr i sae U mad PRES Shino SHME PRINT eHndl eHndl IF sHndl 0 THEN PRINT nScan complete COIN 0 BLSE re BleDiscServiceNext cHndl IP ge l 0 THEN PRINT mSecan abort BAIT FUNC TO BNDIF Americas 1 800 492 2320 Option 2 119 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ay BE et endfunc 1 esas esse ase asses ss SS Main equivalent fr peeesa ses SS ONEVENT EVBLEMSG CALL HndlrBleMsg OnE Vvene EVDLSCPRIMS VE call HandlerPrimSvc Register base uuids with the underlying stack otherwise the services with the 128bit uuid s will be delivered with a uuid handle FF000000 UNKNOWN urd 112233445566778899AABBCCDDEEFFOO uuidS StrDehexizes uuids uHndl BleHandleUuidl28 uuids uuidS 1122DFAD5566778899AABBCCDDBEEFOO uuid StreDehexLzes ona S uHndl BleHandleUuidl28 uuids IF OnStartup 0 THEN PRINT nAdvertising and Gatt Client is open n ELSE PRINT nbet hire Onstartup ENDIF WALTEVENT Ua ES DER EIN aa Expected Output Americas 1 800 492 2320 Option 2 120 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart B
36. Is an extension subroutine BleVSpUartBridge SUBROUTINE Americas 1 800 492 2320 Option 2 196 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This function creates a bridge between the managed Virtual Serial Port Service and the UART when both are open Any data arriving from the VSP is automatically transferred to the UART for forward transmission Any data arriving at the UART Is sent over the air It should be called either when data arrives at either end or when either end indicates their transmit buffer is empty The following events are examples EVVSPRX EVUARTRX EVVSPTXEMPTY and EVUARTTXEMPTY Given that data can arrive over the UART a byte ata time a latency timer specified by AT CFG 116 command may be used to optimise the data transfer over the air This tries to ensure that full packets are transmitted over the air Therefore if a single character arrives over UART a latency timer is started If it expires that single character or any more that arrive but less than 20 will be forced onwards when that timer expires BLEVSPUARTBRIDGE Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments None Interactive No Command Related BLEVSPOPEN BLEVSPCLOSE BLEVSPINFO BLEVSPWRITE BLEVSPFLUSH Commands Related Commands Example BleVSpUartBridge sb See in BL600CodeSnippets zip
37. NUI o mdAcir made ced mdsecad aeteo 00 00 ce SleCharGonmth iSGe aebro Me har l re BleServiceCommit hSvc Register Service 2 can now reuse the service handle hUuidS2 BleHandleUuidl6 0x1856 1G Je We ery Ceen eg SII VICI I TA y IU OrS 7 Inte ReGister Characteristic 1 im Service 2 Americas 1 800 492 2320 Option 2 7 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual mdAttr PI Arter tadar PREGA The AC ESS NONE B TETA tree E ONE 1070 ae mA Cea E er ME a ea ETE A E E E ELERA EEA Cero OREN OTa mdSccd BLE CHAR METADATA ATTR NOT PRESENT chProp BEET O HARPPROPRERCIE I NICMU ILE 3g hUuidC21 BleHandleUuidl6 0x2A54 Ce BleCharNew chProp NUuldC 1 mdArter maCced mdseca attrs 00 00 00 00 ge keChar onmm nmSve aebro me har re BleServiceCommit hSvc The 2 services are now visible in the gatt table Writes into a characteristic from a remote client is defected and processed as follow l To deal with writes from a gati client Into characteristic or Service l which has the handle hChar11 This handler is called when there is a EVCHARVAL message FUNCTION HandlerCharVal BYVAL hChar AS INTEGER AS INTEGER DIM attrs IF hChar hCharll THEN rc BleCharValueRead hCharll attr print Svcl Charl has been writen with attr ENDIF ENDFUNC 1
38. PRINT nDevice name is BleGetDeviceNameS txS nSend me some text I won t get it nTo exit the app press Button 0O n re BleVSpWrite tx S ENDSUB SUB CloseConnecri ons DIM ice rc BleDisconnect conHnd1 rc BleAdvertStop BleVspClose BleVspFlush 2 J Ps Dorn OUr ers ENDSUVUB SSS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SSS SS VSP Rx buffer event handler 7 gt 5 S222 22222 22252 SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS PUNCTION HandlerVSpRx As INTEGER BleV spr lish 0 PRINT nRx buffer flushed ENDFUNC 1 nandler to service button 0 pressed Americas 1 800 492 2320 Option 2 199 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION Hmdilr Benen t AS INTEGER stop waiting for events and exit app ENDEUNEG Jo aa 2 aS SS See SS ee a ee ee eS eS Se ee ee Se ee ee Se ee Se ee J BLE evens Hane ler e FUNCTION HndlrBleMsg BrVAL mMsoqid BYVAL m rx conhndl nCex IF nMsgIiD 1 THEN PRINT nDasconnected from client EXLEE UNG 0 ENDILE ENDFUNC 1 ONE VENTS EVVSERX CALL HandlerVSpRx ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT EVGPITOCHANT CALL HndilrBENOPT Onotarcup Calls first subroutine declared above WALTEVENT Cose onne ction O se 7 Calls second subrouletme d
39. Selon r aM Caa i i 1 commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addrs 200 0 0 PNDSUB SUB CloseConnections rc BleDisconnect conHnd1 Americas 1 800 492 2320 Option 2 109 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleAdvertStop ENDSUB PUNCTION Hndlabilevise BYVAL NMsgld BYVAL nGrx conHndl nCtx ENDEUNG T FUNCELON HandlerCharDese BYVAL NChar AS INTEGER BYVAL hDese AS INTEGER DIM Anstne nuuid a Ofise uid IF hChar hMyChar THEN rc BleCharDescRead hChar hDesc 0 20 duid aS IF rc 0 THEN PRINT nRead 20 bytes from index offset in new char value PRINT Vn a New Descriptor Data StrHexizes ac PRINT n Length StrLen aS PRIME Thn ss Descriptor VUD Wome ei ck Celunee EXT 2EUNCG VO BLSE PRINT nCould not access the uuid BENDI F E DOE PRINY nlhis is for Some other characteristic JEND IL IE ENDEUNC i install a nancler tor wreices to Characteristic values ONEVENT EVCHARDES CALL HandlerCharbesc ONEVENT EVBLEMSG CALL HndlrBleMsg OnStartup PRINT nWrite to the User Descriptor with UUID 0x2999 wait for events and messages WALTEVENT CloseConnections PRINT de Guile calgon eicle pecs Expected Output Write to the User Descriptor with UUID 0x2999 Read 20 bytes f
40. Server Characteristic Configuration Descriptor or SCCD for short ASCCD always has 2 bytes of data and currently only 1 bit is used as on off settings for broadcasts Finally if the Characteristic has other Descriptors to qualify its behaviour a separate API function is also supplied to add that to the GATT table and when setting up a metadata object will also need to be supplied In a nutshell think of a metadata object as a note to define how an attribute will behave and the GATT table manager will need that before it is added Some attributes have those notes specified by the BI specification and so the GATT table manager will not need to be provided with any but the rest require it This function helps write that metadata BLEATTRMETADATA nReadRights nWriteRights nMaxDataLen flsVariableLen resCode INTEGER a 32 bit opaque data object to be used in subsequent calls when AeA adding Characteristics to a GATT table Arguments byVal nReadRights AS INTEGER nReadRights This soecifies the read rights and shall have one of the following values No Access 1 Open Americas 1 800 492 2320 Option 2 90 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual nWrite Rights nMaxDataLen flsVariableLen resCode Interactive Command Example DIM mdVal DiIMomedceed DiMirmedsecd DIM ee ey laos Encrypted wit
41. TCN31H lopen as DIE at 300 baudrate odd parity Oo awa oes WPeSboOobiks Cis7 rls flow TOMAN PRIONEN IF Uarcelosebx CDEE OEREN PRIN Y nDarca in ar least one burccer Uart Pore nor Closed EROE rel UartOpen 9600 0 0 CNela open as DTE at 300 baudrate odd parity PRINT nUart Port was closed ENDIF Expected Output Lairg Data in at least one buffer Uart Port not closed UARTCLOSEEX is a core function UartSetRTS The BL600 module does not offer the capability to control the RTS pin because the underlying hardware does not allow it UartBREAK The BL600 module does not offer the capability to send a BREAK signal If this feature is required then the best way to expedite it is to put UART_TX and an I O pin configured as an output through an AND goate For normal operation the general purpose output pin is set to logic high which means the output of the AND gate follows the state of the UART_TX pin When a BREAK is to be sent the general purpose pin is set to logic high which means the output of the AND gate are low and remain low regardless of the state of the UART_TX pin Americas 1 800 492 2320 Option 2 16 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual I2C Two Wire Interface TWI The BL600 can only be configured as an I2C master with the additional constraint that it
42. These rows are grouped into collections called services and characteristics The grouping is achieved by creating a row with Type 0x2800 or 0x2801 for services primary and secondary respectively and 0x2803 for characteristics Basically a table should be scanned from top to bottom and the specification stipulates that the 16 bit handle field SHALL contain values in the range 1 to 65535 and SHALL be in ascending order and gaps are allowed When scanning if a row is encountered with the value 0x2800 or 0x2801 in the Type column then it SHALL be Understood as the start of a primary or secondary service which in turn SHALL contain at least one charactestic or one included service which have Type 0x2803 and 0x2802 respectively When a row with Type 0x2803 a characteristic is encountered then the next row shall contain the value for that characteristic and then after that there may be 0 or more descriptors This means each characteristic shall consist of at least 2 rows in the table and if descriptors exist for that characteristic then a single row per descriptor 0x0001 Ox2800 UUID of the Service Primary Service 1 Start 0x0002 Ox2803 Properties Value Handle Value Characteristic 1 Start UUID 0x0003 Value Value 1 to 512 bytes Actual data UUID1 0x0004 0x2803 Properties Value Handle Value Characteristic 2 Start UUID2 0x0005 Value Value 1 to 512 bytes Actual data UUID2 0x0006 0x2902 Value Descriptor 1 CCCD 0x0007 O
43. Value 10 to the power of nExponent byVal nUnit AS INTEGER Valid range Oto 65535 nUnit This value is a 16 bit UUID Used as an enumeration to specify the units which are listed in the Assigned Numbers document published by the Bluetooth SIG found at http developer bluetooth org gatt units Pages default asox byValnNameSpace AS INTEGER Valid range Oto 255 nNameSpace The value identifies the organization defined in the Assigned Numbers document published by the Bluetooth SIG found at hitps developer bluetooth org gatt Pages GattNamespaceDescriptors asox byVal nNSdesc AS INTEGER nNSdesc Valid range 0O to 65535 This value is a description of the organisation specified by nNameSpace Interactive No Command Example BleCharDescPrstnFrmt sb See in BL600CodeSnippets zip DIM ro Mevacuccess UsrDescs UsrDesco A description DIM charUurd CharUuid BleHandleUuidlo 1 DIM charMet charMet BleAttrMetaData 1 1 20 0 metaSuccess DIM mdUsrDsc mdUsrDsc BleAttrMetaData 1 1 20 0 metaSuccess DIM mece ss mesced E be leAterilecadaran Ip 7 Ort OCOC D metadata stor char initialise char write read enabled accept signed writes indicatable rc BleCharNew 0x4B charUuid charMet 0 mdSccd rc BleCharDescUserDesc usrDesc mdUsrDsc IF rc 0 THEN PRINT nChar created and User Description usrbescS added ELSE PRINT nFailed ENDIF i II other Optional descriptors La 16 bit signed intege
44. another service This will Usually but not necessarily be a SECONDARY service which is virtually identical to a PRIMARY service from the GATT Server perspective and the only difference is that when a GATT client queries a device for all services it does not get any mention of SECONDARY services When a GATT client encounters an INCLUDED SERVICE object when querying a particular service it shall perform a sub procedure to get handles to all the characteristics that are part of that INCLUDED service This mechanism is provided to allow for a single set of Characteristics to be shared by multiple primary services This is most relevant if a Characteristic is defined so that it can have only one instance in a GATT table but needs to be offered in multiple PRIMARY services Hence a typical implementation where a characteristic is part of many PRIMARY services installs that Characteristic in a SECONDARY service see BleSvcCommit and then uses the function defined in this section to add it to all the PRIMARY services that want to have that characteristic as part of their group It is possible to include a service which is also a PRIMARY or SECONDARY service which in turn can include further PRIMARY or SECONDARY services The only restriction to nested includes is that there cannot be recursion Americas 1 800 492 2320 Option 2 88 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www laird
45. be terminated by a carriage return for it to be processed Note The module self reboots so that the bonding manager context is also reset Examples AT BTD AT BTD is an extension Command Americas 1 800 492 2320 Option 2 10 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual AT MAC 12 hex digit mac address COMMAND This is a Command that is successful one time as it writes an IEEE MAC address to non volatile memory This address is then used instead of the random static MAC address that comes preprogrammed in the module Notes Ifthe module has an invalid licence then this address Is not visible If the address 000000000000 Is written then it is treated as invalid and prevents a new address trom being entered AT MAC 12 hex digits Returns nOO r or n01 192A r Where the error code 192A is NVO_NVWORM_EXISTS This means that an IEEE MAC address already exists this can be read using the command AT 24 A string delimited by which shall be a valid 12 hex digit MAC address that Is Arguments written to non volatile memory Interactive Command This is an interactive mode command and MUST be terminated by a carriage return for it fo be processed Note The module self reboots if the write is successful Subsequent invocations of this command generate an error E
46. be the only master on the bus and only 7 bit slave addressing is supported Note On the BL600 firmware releases older than 1 2 54 4 there is an issue where some I2C slaves are not able to drive the ACK down to a low enough voltage level for the module to recognise it as an ACK This is a result of a bug In the BL600 s 2C driver which results in the SDA line not being released by the module This has been corrected in release 1 2 54 4 and the firmware is available as a UART download on request You should upgrade the firmware if you have an 2C slave not responding to the correct slave address SPI Interface Note The BL600 module can only be configured as a SPI master Americas 1 800 492 2320 Option 2 17 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 4 CORE EXTENSIONS BUILT IN ROUTINES Miscellaneous Routines This section describes all miscellaneous functions and subroutines RESET SUBROUTINE This routine is used to force a reset of the module RESET nType Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nType byVal nType AS INTEGER This is for future use Set to 0 Interactive Command ne Example RESET si See in Brel0Codesnippers Zip RESET 0 force a reset of the module Expected Output Like when you reset the module using the interactive
47. bluetooth smart BASIC User Manual WALTEVENT Adverts Started Make a connection to the BL600 Ble Connection 1655 Auth Key Request type 1 Passkey 123456 was used Disconnected 1055 BLESECMNGRPASSKEY is an extension function BleSecMngrKeySizes FUNCTION This function sets minimum and maximum long term encryption key size requirements for subsequent pairings If this function is not called default values are 7 and 16 respectively To ship your end product to a country with an export restriction reduce nMaxKeySize to an appropriate value and ensure it is not modifiable BLESECMNGRKEYSIZES nMinKeysize nMaxKeysize INTEGER a result code Ret ee Typical value 0x0000 indicates a successful operation Arguments nMinKevsi byVal nMinKeysiz AS INTEGER INKeYSIZ The minimum key size The range of this value is from 7 to 16 nMaxKevsi byVal nMaxKeysize AS INTEGER axKeyYSIZe The maximum key size The range of this value Is from nMinKeysize to 16 Interactive No Command Example BleSecMngrKeySizes sb See in BL600CodeSnippets zip PRINT BleSecMngrkKeySizes 8 15 Expected Output BLESECMNGRKEYSIZES is an extension function BleSecMngrloCap FUNCTION Americas 1 800 492 2320 Option 2 70 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This function sets the user I O capabilit
48. charUuid charUuid BleHandleUuidlo 1 DIM charMet charMet BleAttrMetaData 0 0 20 1 metaSuccess DIM BSveUuiad hSveUuid Blebandlevurdls svycuUuid Dim ee emcee cecdm Blet tt reiletadat ceil 2 Orme 7 7 CCCDPMeCraGara hor e Create service rc BleServiceNew 1 hSvcUuid hSvc initialise char write read enabled accept signed writes indicatable rc BleCharNew 0x20 charUuid charMet mdCccd 0 commit char initialised above with Initial value hit to service hMyChar rc BleCharCommit hSvc attrs hMyChar Commit Service co CATT table rc BleServiceCommit hSvc eCc BleAdvertStart 07 addrs 20 300000 0 ENDANG SUB CloseConnections rc BleDisconnect conHnd1l rc BleAdvertStop rc GpioUnbindEvent 1 Americas 1 800 492 2320 Option 2 37 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ENDSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conhnd ncGux IF nMsgID 1 THEN PRINT n n Disconnected from client EXITFUNGC O ELSEIF nMsgID 0 THEN PRINT n Connected to client ENDINE EIEN cl FUNCLEION HndlrCharhve BYVAL echarHandle AS INTEGER As INTEGER IF charHandle hMyChar THEN PRINT T nGot eCOnElLEMartom of rocco ne Indicacion ETSE PRINC nGor Confirmation of come other Indication r oharhandle ENDIE ENDEUNG 1 FUNCTION HndirUartkRx AS INTEGER ENDFUNC 0 PUNC
49. digital inputs that can auto generafte is hardware dependent For the EVDETECTCHANN 81400 module N can only be 0 Use GpioAssignEvent to generate these events See example for GpioAssignEvent GpioSetFunc FUNCTION This routine sets the function of the GPIO pin identified by the nSigNum argument The module datasheet contains a pinout table which denotes SIO Special I O pins The number designated for that special I O pin corresponds to the nSigNum argument GPIOSETFUNC nSigNum nFunction nSubFunc INTEGER a result code The most typical value is 0x0000 indicating a KeLUrnS successful operation Arguments nSigNum yu nSigNum AS INTEGER The signal number as stated in the pinout table of the module byVal nFunction AS INTEGER Specifies the configuration of the GPIO pin as follows 1 DIGITAL_IN nFunction 2 DIGITAL_OUT 3 ANALOG_IN 4 ANALOG_REF not currently available on the BL600 module 5 ANALOG_OUT not currently available on the BL600 module byVal nSubFunc INTEGER Configures the pin as follows If nFunction DIGITAL IN Bits 0 3 OxO1 Pull down resistor weak 0x02 Pull up resistor weak nSubFunc Ox03 Pull down resistor strong Ox04 Pull up resistor strong Else No pull resistors Bits 4 5 0x10 When in deep sleep mode awake when this pin is LOW 0x20 When in deep sleep mode awake when this pin is HIGH Else No effect in deep sleep mode Americas 1 800 492 2320 Option 2 20 Lai
50. does not exist Even when the attribute does not exist an event will occur EVNOTIFYBUF Event Disconnected Fo LG esa BLEGATTCWRITECMD is an extension function BleGattcNotifyRead FUNCTION A Gatt Server has the ability to notify or indicate the value attribute of a characteristic when enabled via the Client Characeristic Configuration Descriptor CCCD This means data will arrive from a Gatt Server at any time and so has to be managed so that it can synchronised with the smartBASIC runtime engine Data arriving via a notification does not require Gatt acknowledgements however indications require them This Gatt Client manager saves data arriving via a notification in the same ring buffer for later extraction using the command BleGafttcNotifyRead and for indications an automatic gatt acknowledgement Is sent when the data Is saved in the ring buffer This acknowledgment happens even if the data was discarded because the ring buffer was full If however it is required that the data NOT be acknowledged when it is discarded on a full buffer then set the flags parameter in the BleGattcOpen function where the Gatt Client manager is opened In the case when an ack is NOT sent on data discard the Gatt Server will be throttled and so no further data will be notified or indicated by it until BleGattNotifyRead is called to extract data from the ring buffer to create space and it will tigger a delayed acknowledgement When the Gatt Clie
51. falls The seven byte string consists of a byte each for century year month day hour minute and second If year month Is zero it is taken as not noted year and all the other fields are set zero not noted For example 5 May 2013 10 31 24 will be represented in the source as DD O7 05 05 OA 1F 18 and the year will be translated into a century and year so that the destination string will be 14 0D 05 05 0A 1F 18 BLEDECODETIMESTAMP atirS timestampS nlndex INTEGER the number of bytes extracted from the attribute string Can be less Returns than the size expected if the nlndex parameter is positioned towards the end of the string Arguments attrs byRef attrS AS STRING This references the attribute string from which the function reads byRef timestampS AS STRING timestampS On exit this is an exact 7 byte string as described above For example 5 May 2013 10 31 24 is stored as 14 O0D 05 05 0A 1F 18 byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the string attr is not long enough to accommodate the index plus the number of bytes to read this function fails nindex Interactive No Command Example BleDecodeTimestamp sb See in BL600CodeSnippets zip DIM chrlandile yl svcHandle re Ess DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc roch May 2 Oe a Toe A Americas 1 800 492 2320 Option 2 178 Laird Technologies Europe 44 1628
52. hHtsSvc Have to add includes before any characteristics are committed PRINT INTEGER bh Blesvchddineludesve Bat Sye BleSvcAddlIncludeSvc is an extension function BleAttrMetadata FUNCTION A GATT Table is an array of attributes which are grouped into Characteristics which in turn are further grouped into Services Each attribute consists of a data value which can be anything from 1 to 512 bytes long according to the specification and properties such as read and write permissions authentication and security properties When Services and Characteristics are Americas 1 800 492 2320 Option 2 89 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual added to a GATT server table multiple attributes with appropriate data and properties get added This function allows a 32 bit integer to be created which is an opaque object which defines those properties and is then submitted along with other information to add the attribute to the GATT table When adding a Service attribute not the whole service in this present context the properties are defined in the BI specification so that it is open for reads without any security requirements but cannot be written and always has the same data content structure This implies that a metadata object does NOT need to be created However when adding Characteristics which consists of a min
53. in Hex 0x INTEGER Kyi PRINTE Y ndata in Decimal g yiz n Expected Output data in Hex 0x00000302 data in Decimal 770 data in Hex 0x00008786 data in Decimal 34694 BLEDECODEU16 Is an extension function BleDecodeS24 FUNCTION This function reads three bytes in a string at a specified offset into a 32bit integer variable with sign extension If the offset points beyond the end of the string this function fails BLEDECODES24 attrS nData nindex INTEGER the number of bytes extracted from the attribute string Can be less Returns than the size expected if the nlndex parameter is positioned towards the end of the string Arguments attrs byRef attrS AS STRING This references the attribute string from which the function reads byRef nData AS INTEGER nData This references an integer to be updated with the 3 byte data from attr with sign extension byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the nine string atir is not long enough to accommodate the index plus the number of bytes to read this function falls Interactive No Command Example BleDecodeS24 sb See in BL600CodeSnippets zip DIM Chridanci Lle yil svehand Le re DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM aters aeee AOT Oa oTa aa 0A aaa Aao DIM uuid uuid 0x1853 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl1
54. index into the string attr treated as a bit array where the new fragment of data bits is written If the string attr is not long enough to atirS Americas 1 800 492 2320 Option 2 166 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual accommodate the index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails byVal srcBitArr AS INTEGER srcBitArr This contains the source data bits which is qualified by the nSrcldx and nBitLen arguments that follow byVal nSrcldx AS INTEGER This is the zero based bit index into the bit array contained in srcBitArr from where Boreas the data bits will be copied No data is copied if this index is negative or greater than 32 byVal nBitLlen AS INTEGER nBitLen This soecies the number of bits from offset nSrcldx to be copied into the destination bit array represented by the string attr It will be clipped to the number of bits left to copy after the index nSrcldx Interactive Nis Command Example BleEncodeBits sb See in BL600CodeSnippets zip DIM isis ee Toke loko LOLOL iad rc BleEncodeBits attr 20 bA 7 5 Mess a ieee eee ee eet toile a Ome teea Exoected Output 00 00 A0 01 BLEENCODEBBITS is an extension function Attribute Decoding Functions Data in a Characteri
55. is read If the nindex string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive No Command Example BleDecodeSFloat sb See in BL600CodeSnippets zip DIM chrhandle yl svchandle re mantissa Coup DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DEM aceea ae EE eA O00 Ol 02 02 04 85 60 387 33 60 DIM uuid uuid 0x1853 rc BleServiceNew 1 BleHandleUuid1l6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read 2 bytes FLOAT from index 2 in the string rc BleDecodeSFloat attr mantissa exp 2 PRINT nThe number read is mantissa x 10 exp Americas 1 800 492 2320 Option 2 177 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual j j wead 2 bytes FLOAT from index 6 in the string rc BleDecodeSFloat attr mantissa exp 6 PRINT nThe number read is mantissa x 10 exp Expected Output The number read is 77 0 x 10 0 The number read is 1926x 10 8 BLEDECODESFLOAT is an extension function BleDecodeTIMESTAMP FUNCTION This function reads seven bytes from string an offset into an attribute string If the offset plus seven bytes points beyond the end of the string then this function
56. length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive No Command Example BleEncode8 amp sb See in BL600CodeSnippets zip IDI sere DIM atEers attrs Laird PRINT a eveeieiers 1s Oycleicias Remember 4 bytes are used to store an integer on the BL600 furie EC Go andex 2 1il will be agnored rc BleEncode8 attr 0x11143 2 write A to index 0 rc BleEncodes attrS 0x41 0 J weite 1B to index 1 rc BleEncodes attrS 0x42 1 L write Dron index 3 rc BleEncodes attrsS 0x44 3 write y to index 7 attr will be extended rc BleEncodes attrS 0x6 7 PRINT Mates now sak bars Americas 1 800 492 2320 Option 2 157 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output attrS Laird attrsS now ABCDd 00 00g BLEENCODES8 Is an extension function BleEncode16 FUNCTION This function overwrites two bytes in a string at a specified offset If the string is not long enough then it is extended with the new extended block uninitialized and then the bytes specified are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a
57. length of the string variable This means the caller Returns does not need to call strlen function to determine how many bytes in the string must be processed Local Stack Frame Underflow EEC CPUN Local Stack Frame Overflow Arguments strMs byRef st rMsg AS STRING J The content of the receive buffer is copied to this string MaxRead byVal nMaxRead AS INTEGER NMAaXREaAA The maximum number of bytes to read Interactive No Command Related BLEVSPOPEN BLEVSPCLOSE BLEVSPINFO BLEVSPWRITE BLEVSPFLUSH Commands Note strMsg cannot be a string constant e g the cat but must be a string variable and If you must Use a const string first save it fo a temp string variable and then pass it to the function Use the iOS BL600 Serial app and connect to your BL600 to test this sample app Example BleVSpRead sb See in BL600CodeSnippets zip Dil eomtmenl Only 1 global variable because its value is used in more than 1 routine All other variables declared locally inside routine that they are used in More efficient because these local variables only exist in memory when they are being used inside their respective routines L EE Open Vsp and start advertising J SUB OmStareue DIN tee lacks E a e CRPE a eiclches aR 2 eiclijoies 1 a 4 re BileVSpOpen 1287128 0 hid re Blescankor init ScRors rc BleAdvRptAddUuidl128 scRpts hnd1 rc BleAdvRptsCommit adRpt scRpts C B leAdv
58. nAdvAppearance 0 Interactive Command NO Example BleAdvRptInit sb See in BL600CodeSnippets zip DIM advRptsS advRpts DIM discovMode discovMode 0 DIM advAppearance advAppearance 1 DIM maxDevName maxDevName 10 IF BleAdvRptInit advRpt discovMode advAppearance maxDevName 0 THEN PRINT nAdvert report initialised ENDIF Expected Output Advert report initialised BLEADVRPTINIT is an extension function BleScanRptinit FUNCTION This function is used to create and initialise a scan report which is sent in a SCAN_RSP message It is not used until BIEADVRPTSCOMMIT is called This report is for use with SCAN_RESPONSE packets BLESCANRPTINIT scanRpt INTEGER a result code Ret oe aiid Typical value 0x0000 indicates a successful operation Arguments byRef scanRpt ASSTRING scanRpt This contains a scan report Interactive No Command Example BleScanRptInit sb See in BLo00CodeSnippets zip DIM SCnRPUo men SCRE T Americas 1 800 492 2320 Option 2 55 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual IF BleScanRptInit scnRpt 0 THEN PRINT nScan report initialised EAIN Expected Output Scan report initialised BLESCANRPTINIT is an extension function BleAdvRptGetSpace FUNCTION This function returns the free space in the advert advRot BLEADVRPTGETSPACE advRp
59. number of bits to read from attr Due to nMaxBits teak l l the destination being an integer variable it cannot be greater than 32 Negative values are treated as zero Interactive No Command Example BleDecodeBits sb See in BL600CodeSnippets zip DIM schrHandle vi svechandle re tas decSErs DIM ba ba 0 DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc ABCDEFGHIJ DIM arbre 2 aurro 4 47 43 44 4546 4 48 49 42 DIM uuid 2 ce 0x1853 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl 0x2A1C mdVal 0 0 ee BleCharCommit svchHandle abrtrs chriuandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read max 14 bits from index 20 in the etring Eo andex 10 rc BleDecodeBITS attr 20 ba 10 14 PRINT ioe array INTECGER B ba read max 14 bits from index 20 in the string to index 10 ba 0x12345678 PRINT On Mie array INTEGER B Tba rc BleDecodeBITS attr 14000 ba 0 14 PRINT M Abit array now TECER P ba bani wll not have been modLiied because index 14000 Ldoesn t exist 1n ab bio Expected Output Bue array OOQDODQ0Q00000L0N0001L1LOLOONON0000000 bit array OOOLOOLOOOLLOLOOCTOLOLIOOLLILOO0 bit array now 00010010001101000101011001111000 Americas 1 800 492 2320 Option 2 181 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetoo
60. only notifyable Iae DIM re result code DIM hSve service handle DIM mdAttr DIM sakelereKerl DiM medseed DiMrchibae DIM attrs DIM NCharil nancies tor charcacceristic 1 of SeryLicece 1 DIM nChar2L hanciles ftor charcaccerLstL 2 of SeryLce 1 DIM nChari2 hancles tor characteriscLe 1 orf Serye 2 DIM NUU l j handles for uuid of Service 1 Pr wines I handles for uuid of Service DIM uidi 7 7 handles for uuid of characteristic Ian Service 1 DIM nUuide ionn handles tor uuid of choracieristic 2 an service l DEM nUuUrdC2 I 77 handles for uuid of characteristic l in Service 2 Register Service 1 hUuidSl1 BleHandleUuidl6 0x180D ie Nese ew e en Vein ETNICE RIMA Ea ky Insc J ReEGiIster Characteristic 1 an Service 1 mdAttr BPlelevurievadawa PERE ht AC E OPEN Eine thee E T OFEN 070 ae mdCccd BLE CHAR METADATA ATTR NOT PRESENT mdSccd BLE CHAR METADATA ATTR NOT PRESENT chProp Dib eth eR Orr Rie ek eek HAR Ee hO r Ri EITE vik TE hUuidC1l1l BleHandleUuidl6 0x2A37 re EleCharNew Che roo hUund ine mda ma eced mdsece rc BleCharCommit shHrs hrs hCharl11 Il Register Characteristic 2 an Service 1 mdAttr Pleteericeadara ETER tik E gt OPEN Bub TERA E OEN Ore madt edy EE er ME a ea BLERA EE E CE OPE EEE RATE RA E a OREN Ore mdSccd BLE CHAR METADATA ATTR NOT PRESENT chProp Bit CHAR ER Orr Riis ep Eelam hUuidCl12 BleHandleUuidl6 0x2A39 te Plo harken C Erop
61. possible to register a custom service and bind that with the virtual service manager to allow that service to function in the managed environment This allows the application developer to interact with any GATT client implementing a serial port service whether one currently deployed or one that the Bluetooth SIG adopts VSP Configuration Given that VSP operation can happen in command mode the ability to configure it and save the new configuration in non volatile memory is available For example in bridge mode the baudrate of the uart can be specified to something other than the default 9600 Configuration is done using the AI CFG command and refer to the section describing that command for further details The configuration id pertinent to VSP are 100 to 116 inclusive Command and Bridge Mode Operation Just as the physical UART Is used to interact with the module when It is not running a smart BASIC application it is also possible to have limited interaction with the module in interactive mode The limitation applies to NOT being able to launch smart BASIC applications using the AT RUN command If bridge mode is enabled then any incoming VSP data Is retransmitted out via the UART Conversely any data arriving via the UART is transmitted out the VSP service This latter functionality provides a cable replacement function Americas 1 800 492 2320 Option 2 186 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wirel
62. s length to accommodate If the client tries to write more bytes than the initial maximum length then the client will get an error response byRef resCode AS INTEGER This variable will be updated with result code which will be 0 if a metadata object was successfully returned by this call Any other value implies a metadata object did not get created No BleAttrMetadata sb See in BL600CodeSnippets zip J MetaGdrea tor value attribute of Characteristic metadata for CCCD attribute On Characteristic mecadata tor SCCD actccribute oft Characteristic Crearte che mecadarca ror the value acrteibouce ima che charcacrterLstLG and Heart e ESESe Rate attribute has variable length There is always a Value attribute in a characteristic mdVal BleAttrMetadata 17 0 20 0 rc There is a CCCD anci SCCD 10 CALS CNACACTETLSELE Americas 1 800 492 2320 Option 2 91 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual mdCccd BleAttrMetadata 1 mdSccd BleAttrMetadata 0 r 2 A OTE o TOT Tre Create the Characteristic object IF BleCharNew 3 BleHandleUuidl16 Ox2A1C mdVal mdCccd mdSccd 0 THEN PRINT success Blok PRINT nFailed END LE Expected Output BLEATTRMETADATA Is an extension function BleCharNew FUNCTION When a Characteristic is to be added to a GATT table multipl
63. security and bonding Attribute encoding and decoding Laird custom VSP service Power management Wireless status Events related to the above What Does a BLE Module Contain Our smart BASIC based BLE modules are designed to provide a complete wireless processing solution Each module contains A highly integrated radio with an integrated antenna external antenna options are also available BLE Physical and Link layer Higher level stack Multiple GPIO and ADC Wired communication interfaces like UART I2C and SPI A smart BASIC run time engine Program accessible flash memory which contains a robust flash file system exposing a conventional file system and a database for storing user configuration data Voltage regulators and brown out detectors For simple end devices these modules can completely replace an embedded processing system The following block diagram Figure 1 illustrates the structure of the BLE smart BASIC module from a hardware perspective on the left and a firmware software perspective on the right Americas 1 800 492 2320 Option 2 5 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 44 connection pads User smartBASIC Application Example App ARM Cortex MO smartBASIC smartBASIC run time engine provides safe access to Nono BLE stack drivers and Data non vol stores Store 16K RAM
64. the module to send any data waiting to be sent in the transmit ring buffer While the CCCD value is not set for notifications writes by the smart BASIC application result in data being buffered If the buffer is full The appropriate write routine indicates how many bytes actually got absorbed by the driver In the background the transmit ring buffer is emptied with one or more indicate or notify messages to the client When the last bytes from the ring buffer are sent EVVSPTXEMPTY is thrown to the smart BASIC application so that it can write more data if it chooses When GATT Client sends data to the module by writing into the rx fifo characteristic the managing driver will immediately save the data in the receive ring buffer if there is any space If there is no space in the ring buffer data is discarded After the ring buffer is updated event EVVSPRX Is thrown to the smart BASIC runtime engine so that an application can read and process the data Similarly given that ModemOuTt is notified to the client the ModemOut characteristic has a Client Configuration Characteristic CCCD which must be set to 0x0001 By default in a connection the RIS bit in ModemOuTt is set to 1 so that the VSP driver assumes there is buffer space in the peer to send data The RIS flag is affected by the thresholds of 80 and 120 which means the when opening the VSP port the rxbuffer cannot be less than 128 bytes It is intended that in a future release it will be
65. the smart BASIC runtime engine if it was successful If the request to change the connection parameters fails an EVBLEMSG message with msgid 15 is thrown to the smart BASIC runtime engine BLESETCURCONNPARMS nConnHandle nMinIntUs nMaxintUs nSuprToutUs nSlaveLatency INTEGER a result code Bein Typical value 0x0000 indicates a successful operation Arguments byVal nConnHandle AS INTEGER nConnHandle Specifies the handle of the connection that must have the connection parameters changed byVal nMinIntUs AS INTEGER The minimum acceptable connection interval in microseconds byVal nMaxintUs AS INTEGER The maximum acceptable connection interval in microseconds byVal nSuprToutUs AS INTEGER nSuprToutUs The link supervision timeout for the connection in microseconds It should be greater than the slave latency times the actual granted connection interval byVal nSlaveLatency AS INTEGER The number of connection interval polls that the peripheral may ignore This times the connection interval shall not be greater than the link supervision timeout nMinIntUs nMaxintUs nSlaveLatency Note Slave latency is a mechanism that reduces power usage in a peripheral device and maintains short latency Generally a slave reduces power usage by setting the largest connection interval possible This means the latency is equivalent to that connection interval To mitigate this the peripheral can greatly reduce the connection i
66. to that record Field 2 One octet and is a tag value which identifies the type of payload that starts at the next octet Hence the payload data is length 1 A special NULL AD record consists of only one field that is the length field when it contains just the OO value The specification also allows custom AD records to be created using the Manufacturer Specific Data AD record Note Refer to the Supplement to the Bluetooth Core Specification Version 1 Part A which has the latest list of all AD records You will need to register as at least an Adopter which is free to gain access to this information Americas 1 800 492 2320 Option 2 50 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleAdvertStart FUNCTION This function causes a BLE advertisement event as per the Bluetooth Specification An advertisement event consists of an advertising packet in each of the three advertising channels The type of advertisement packet is determined by the nAdvlype argument and the data in the packet is initialised created and submitted by the BLEADVRPTINIT BEADVRPTADDxxx and BLEADVRPTCOMMIT functions respectively If the Advert packet type nAdvType is soecified as 1 ADV_DIRECT_IND then the peerAddr string must not be empty and should be a valid address When advertising with this packet type the time
67. which contains 3 descriptors thar are IS uuid are 6 bit and 8 are 122 o 3 of the 16 bit uuid are the same value OxDEAD and 2 of the 128 bit uuids are also the same 112233445566778899AABBCCDDEEFF he Sever cueelec Usilng EleGanive Voli e De ea a wimwOlecl alm Ooemlicia sci A ocang Norde Usb Dong l Selo DIM oo COMM Uline na d oir mice Aree Vc lA med DUNC S Om S wake iio DIM tee eiclkjoins eiclcies Sscloirs rc BleAdyRotInit adRots 27 0 10 IF rc 0 THEN rc BleScanRptInit scRpt ENDIF if re 0 THEN re Plead RersCommit adReis seRpes ENDIF LE re O THEN re BleAdvertStart 0 addrs 50 0 0 ENDIF Lopen the gatt client with default notify indicate ring butter size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF BENDFUNC rc SUB CloseConnections rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx DIM u s Contind lnc x IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNC Q ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for first service PRINT n and a characeristic scan will be initiated in the event re BlebDiscServicerirse condnd 0 0 IF rc 0 THEN wait for start and end handles for first primary service WALILTEVENT PRINT a nGGaa tor deS ritor wich uuid ODED uHndl BleHandleUuidl6 OxDEAD te BlebrseDesecrirsr conhndl uhHndl cvalArer IF rc 0 THEN HandlerDescDisc will exit with 0 when op
68. write to the CCCD characteristic The BL600 will then notify your device of a new characteristic value Connected to client CCCD Val 0 Notifications have been disabled by client CCCD Val 1 Notifications have been enabled by client Successful notification of new value Belen 4 BLECHARVALUENOTIFY is an extension function BleCharValuelndicate FUNCTION If There is BLE Connection this function is used to write new data into the VALUE attribute of a Characteristic so that it can be sent as an indication to the GATT client The characteristic is identified by a composite handle returned by the function BleCharCommit An indication results in an acknowledgement from the client and that will be presented to the smart BASIC application as the EVCHARHVC event BLECHARVALUEINDICATE charHandle attrS INTEGER a result code KeU Typical value 0x0000 indicates a successful operation Arguments byVal charHandle AS INTEGER charHandle This is the handle to the characteristic whose value must be updated which was returned when BleCharCommit was called byRef attrS AS STRING String variable containing new value to write to the characteristic and attr oe then to send as a notification to the client If there is no connection this function fails with an appropriate result code Interactive No Command Example BleCharValueIndicate sb See in BL600CodeSnippets zip DIM PM Char ie creo Conn FUNCTION Ons
69. 0 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual function HandlerAttryrite cHndl annd noes as Integer dim noret NANmd ar Dre sme Ae WE ey S PLLC Vehndil eNd Print vat chmed i armel print status integer h nSts if nSts 0 then Print Wwetribuite waite Oh else print nrailed to write attribute endif endfunc Q function HandlerAttrNotify as integer dim ciad annd ae cdce PLINE SN NEVATIRNOTIE Event rc BleGattcNotifyRead cHndl aHndl att dscd print n BleGattcNotifyRead if rc 0 then print endesan print Traer Andle anA Print Y data St uenexizes atts print discarded dscd else Printe failed with Arnee Jer Te endif endfunc 1 a Main equivalent eeeesosesescsesessa ase s sees see ees ses es ees ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVATTRWRITE call HandlerAttrWrite Chad erie BYATTRNOTIEY call HandlerAttrNotify IF Onstereup 0 THEN PRINT nAdvertising and Gatt Client is open n ELSE PRIME MP etimresOnstarrue ENDIF WALTEVENT PRITS AAE ICINE Expected Output Americas 1 800 492 2320 Option 2 155 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies Advertising and Gatt Client is open Connected so enable notification for char with cccd at 16 EVATTRWRITE cHndl 877 attrHndl 16 status 00000000 Attribute
70. 0 x 00 as FLOAT to index 2 and we will fal pecause the mantissa is too large it has to be lt 8388600 iF BlekncoderLOAT attics 10000000 0 2 1 0 THEN PRINT nFailed to encode to FLOAT BNP LE Expected Output 0 Failed to encode to FLOAT Failed to encode to FLOAT BLEENCODEFLOAT is an extension function BleEncodeSFLOATEX FUNCTION This function overwrites two bytes in a string at a specified offset as short 16 bit float value If the string is not long enough it is extended with the extended block uninitialized Then the bytes are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODESFLOATEX atirS nData nindex INTEGER a result code il Typical value Ox0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This argument is the string that will be written to an attribute byVal nData AS INTEGER The 32 bit value is converted into a 2 byte IEEE 11073 16 bit SFLOAT consisting of a nData 12 bit signed mantissa and a 4 bit signed exponent This means a signed 32 bit value always fits in such a FLOAT enitity but there will be a loss in significance to 12 from 32 byVal nindex AS INTEGER This is the zero based index into the string attr where the new
71. 00 results in 4 3 results in 4 100 results in 55 At any time SYSINFO 2008 returns the actual transmit power setting When in command mode use the command AT 2008 BLETXPOWERSET nTxPower INTEGER a result code ecm Typical value 0x0000 indicates a successful operation Arguments byVal nTxPower AS INTEGER Specifies the new transmit power in dBm units to be used for all subsequent Tx nTxPower packer The actual value is determined by scanning through the value list 4 0 4 8 12 16 20 30 55 so that the highest value that is less than the desired value is selected If the desired value is higher than 55 55 Is set Interactive No Command Americas 1 800 492 2320 Option 2 47 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example BleTxPowerSet sb See in BL600CodeSnippets zip DIM re elo dp 1000 rc BleTxPowerSet dp Pee Vie AC PRINT nTx power desired dp actual T Sysinto 2008 dp 8 rc BleTxPowerSet dp PRINT nTx power desiared dp actual Sysinto 2008 dp 2 rc BleTxPowerSet dp PRINT nTx power destred dp T actual Sysinto 2003 dp 10 rc BleTxPowerSet dp PRINT nTx power desired do actuale T Sysinto 2003 Co 2 5 rc BleTxPowerSet dp PRINT nTx power desired dp T m actual T Sysitinto 2003
72. 00066924a1287d56f2747622b2a note 0 s in byte position 2 3 and an offset 0Oxd913 hUuid2 BleHandleUuidSibling hUuidl 0x1234 IF hUuid2 0 THEN PRINT nFailed to create a handle ELSE ERINE Anhand e tor cue oN elno Uu d eaa naea aa a A a n ENDIF hUuid2 now references an object which also points to the base uuid ced9000066924a1287d56 2700004762 note O s in byte position 2 3 and has the offset 0x1234 Expected Output Handle for custom Uuid is FC03D913 66856685 Handle for custom sibling Uuid is FC031234 66907596 BLEHANDLEUUIDSIBLING is an extension function BleSvcCommit This function is now deprecated use BleServiceNew amp BleServiceCommft instead BleServiceNew FUNCTION As explained in an earlier section a Service in the context of a GATT table is a collection of related Characteristics This function is used to inform the underlying GATT table manager that one or more related characteristics are going to be created and installed in the GATT table and that until the next call of this function they shall be associated with the service handle that it provides upon return of this call Under the hood this call results in a single attribute being installed in the GATT table with a type signifying a PRIMARY or a SECONDARY service The value for this attribute shall be the UUID that will identify this service and In turn have been precreated using one of the functions BleHandleUuid16 BleHa
73. 01 2803 are considered belonging to that characteristic For example see characteristic at row with handle 0x0004 which has the mandatory value row and then 2 descriptors The Bluetooth specification allows for multiple instances of the same service or characteristics or descriptors and they are differentiated by the unique handle Hence when a handle is known there is no ambiguity Each GATT Server table allocates the handle numbers the only stipulation being that they be in ascending order gaps are allowed This is important to understand because two devices containing the same services and characteristic and in EXACTLY the same order may NOT allocate the same handle values especially if one device increments handles by 1 and another with some other arbitrary random value The specification DOES however stipulate that once the handle values are allocated they be fixed for all subsequent connections unless the device exposes a GATT Service which allows for indications to the client that the handle order has changed and thus force it fo flush it s cache and rescan the GATT table When a connection is first established there is no prior Knowledge as to which services exist and of their handles so the GATT protocol which is used to interact with GATT servers provides procedures that allow for the GATT table to be scanned so that the client can ascertain which services are offered This section describes smartBASIC functions which encapsulate a
74. 3 114 In the virtual serial port service manager data transfer is managed When sending data using NOTIFIES the underlying stack uses transmission buffers of which there are a finite number This soecifies the number of transmissons to leave unused when sending a lot of data This also allows other services to send notifies without having to wait for them The total number of transmission buffers can be determined by calling SYSINFO 2014 or in interactive mode submitting the command ATi 2014 When in interactive mode and connected for virtual serial port services this is the minimum connection interval in milliseconds to be negotiated with the master Valid values Oto 4000 ms Note Ifa value of less than 8 Is specified then the minimum value of 7 5 is selected When in interactive mode and connected for virtual serial port services this is the maximum connection interval in milliseconds to be negotiated with the master Valid values O to 4000 ms Note Ifa value of less than the minimum specified in 105 then it is forced to the value in 105 plus 2 ms When in interactive mode and connected for virtual serial port services this is the connection supervision timeout in milliseconds to be negotiated with the master Valid range 0 to 32000 Note Ifthe value is less than the value in 106 then a value double the one specified in 106 is used When in interactive mode and connected for virtual serial port services this is the slave
75. 33344 Props 2 valHndl 5 ISvcUuid 0 BRVDISCCHAR EVDISCCHAR cHnd1 3549 chUuid FC033344 Props 2 valHndl 11 ISvcUuid 0 EVDISCCHAR cHnd1l 3549 chUuid 00000000 Props 0 valHndl 0 ISvcUuid 0 Characteristic Scan complete Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 126 Laird Technologies smart BASIC User Manual BLEDISCCHAREFIRST and BLEDISCCHARNEXT are both extension functions BleDiscDescFirst BleDiscDescNext FUNCTIONS These pair of functions are used to scan the remote Gatt Server for descriptors in a characteristic with the help of the EVDISCDESC message event and when called a handler for the event message must be registered as the discovered descriptor information is passed back in that A generic or uuid based scan can be initiated The former will scan for all descriptors and the latter will scan for a descriptor with a particular uuid the handle of which must be supplied and is generated by using either BleHandleUuvid16 or BleHandleUuvid128 If instead it is Known that a gatt table has a specific service characteristic and a specific descriptor then a more efficient method for locating details of that characteristic is to use the function BleGattcFindDesc which is described later While the scan is in progress and waiting for the next piece of data from a Gatt server the module will enter low power state as the WA
76. 45 4 PRINT Abr eo 2 attrS Americas 1 800 492 2320 Option 2 159 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output BLEENCODE 24 is an extension function BleEncode32 FUNCTION This function overwrites four bytes in a string at a specified offset If the string is not long enough then it is extended with the new extended block uninitialized and then the bytes specified are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODE32 atirS nData nindex INTEGER a result code Keins Typical value 0x0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This argument is the string that will be written to an attribute nDat byVal nData AS INTEGER atad The four bytes of this integer is saved The rest is ignored byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of index data is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function
77. 6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle Americas 1 800 492 2320 Option 2 172 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read 3 signed bytes from index 2 rc BleDecodeS 24 attrsS vl1 2 PRINT ndata in Hex Ox INTEGER H vl PRINTE Y ndata in Decimal g iil cay read 3 signed bytes from index 6 rc BleDecodeS24 attr S vli 6 PRINT Andata im Hex 0x INTEGER H l PRINT Y ndarta in Decimal ele in Expected Output Hex 0x00040302 Decimal 262914 Hex OxFF888786 Decimal 7829626 BLEDECODES24 is an extension function BleDecodeU24 FUNCTION This function reads three bytes from a string at a specified offset into a 32 bit integer variable without sign extension If the offset points beyond the end of the string then this function fails BLEDECODEU24 atirS nData nindex INTEGER the number of bytes extracted from the attribute string Can be less Returns than the size expected if the nilndex parameter is positioned towards the end of the string Arguments byRef attrS AS STRING This references the attribute string from which the function reads byRef nData AS INTEGER nData This references an integer to be updated with the 3 byte data from attr without sign extension byVal
78. 7 18 19 20 21 A connection has been established and msgCtx is the connection handle A disconnection event and msgCtx identifies the handle Immediate Alert Service Alert The 2 4 parameter contains new alert level Link Loss Alert The 2 4 parameter contains new alert level A BLE Service Error The 2 4 parameter contains the error code Thermometer Client Characteristic Descriptor value has changed Indication enable state and msgCtx contains the new value 0 Disabled 1 Enabled Thermometer measurement indication has been acknowledged Blood Pressure Client Characteristic Descriptor value has changed Indication enable state and msgCtx contains the new value 0 Disabled 1 Enabled Blood Pressure measurement indication has been acknowledged Pairing in progress and display passkey supplied in msgCtx A new bond has been successfully created Pairing in progress and authentication key requested Key type Is msgCix is Heart Rate Client Characteristic Descriptor value has changed Notification enable state and msgCtx contains the new value 0 Disabled 1 Enabled Connection parameters update and msgCix Is the conn handle Connection parameters update fail and msgCtx is the conn handle Connected to a bonded master and msgCtx is the conn handle A new pairing has replaced old key for the connection handle specified The connection is now encrypted and msgCtx is the conn handle The supply voltage h
79. 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DiMatteo scmeio 0 Ol 02 pb 07 05 OS OA ale DIM eel ees uuid 0x1853 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read 7 byte timestamp from the index 3 in the string rc BleDecodeTimestamp attrs tsS 3 PRINT nTimestamp StrHexizeS ts Expected Output Timestamp 140D05050A1F18 BLEENCODETIMESTAMP is an extension function BleDecodeSTRING FUNCTION This function reads a maximum number of bytes from an attribute string at a specified offset into a destination string This function will not fail as the output string can take truncated strings BLEDECODESTRING atirS nindex dstS nMaxBytes INTEGER the number of bytes extracted from the attribute string Can be less Returns than the size expected if the nindex parameter is positioned towards the end of the string Arguments byRef attr AS STRING atirs This references the attribute string from which the function reads Ind byVal nindex AS INTEGER MNAEX This is the zero based index into string attr from which data is read byRef dst AS STRING dst This argument is a reference to a string that will be updated with up to nMaxBytes of data from the ind
80. 923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Geing Nosdse Usb Dongle ee LN OGe ep Charactersitic at handle 15 has notify ilG ce ea C hara cers ae tangle WS has indie ar 19 eeced DIM we eres Onana a wilshoell 2 eve eave PUNCTION OnsStareue DIM ror adro adde ms eroe re BileAdvRpE Inte adRotes 2 0 7 10 IF rc 0 THEN rc BleScanRptInit scRpt ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt scRpt ENDIF Pe ee 0 THEN 92 re B lekdgvertstare O0 addrs 50 0 0 gt ENDIF j fopen the gatt client with default notitfy indicare ring burfer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDEUN ORE SUB CloseConnections rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB Ble event handler 25558582 ooo i a 525555 EUNCTTON HndlrBleMsg BYVAL nMsglid BYVAL MCX conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNG Q ELSEIF nMsgID 0 THEN PRINE n Connected so enable notification for char with ceed at 16 atHndl 16 ato 01 00 rc BleGattcWrite conHndl atHndl atS IF rc 0 THEN WALITEVENT END PRIND n enable indication for char with cocd at 19 atHndl 19 atS 02 00 rc BleGattcWrite conHndl atHndl ats IF rc 0 THEN WALITEVENT ENDIF END ENDEUNG i tf Vf M Americas 1 800 492 2320 Option 2 154 Laird Technologies Europe 44 1628 858 94
81. ADBYINDEX is an extension function BleGetADbyTag FUNCTION This function is used to extract a copy of the first advertising data AD element that has the tag byte specified from a string which is assumed to contain the data portion of an advert report incoming or outgoing If multiple instances of that AD tag type are suspected then use the function BleGetADbylIndex to extract Note If the last AD element is malformed then it will be treated as not existing For example it will be malformed if the length byte for that AD element suggests that more data bytes are required than actually exist in the report string BLEGETADBYTAG rptDataS nADtag ADvalS INTEGER a result code Ret ee mn Typical value 0x0000 indicates a successful operation Arguments byREF rptDataS AS STRING rptData This parameter is a string that contains concatenated AD elements which will p have been either constructed for an outgoing advert or will have been received in a scan depends on module variant byVAL nADTag AS INTEGER nADTag This parameter specifies the single byte tag value for the AD element that is to returned in the ADval parameter Only the first instance can be catered for If multiple instances are suspected then use BleAdvADbylndex to extract it byREF ADvalS AS STRING ADvalS When the nth index Is found the data excluding single byte the tag value for that AT element is returned in this parameter Interactive No Command
82. ALL BtnOPress if Biecuec e IF BleAdvertStart 0 addrS 100 10000 0 0 THEN PRINT nAdverts Started PRINT nPress button 0 ro exi n ELSE BRINE a naGdvertersenenn notr Successrul Bae WALTEVENT Americas 1 800 492 2320 Option 2 33 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual Expected Output When connection made with the module Adverts Started Press button 0 to exit BLE Connection 3634 Connected to a bonded master Connection 3634 is now encrypted A new pairing has replaced the old key Disconnected 3634 EX1ICiNGs s Expected Output When no connection made Adverts Started Press button 0 to exit Advert stopped via timeout iy als eel a pee EVDISCON This event is thrown when there Is a disconnection It comes with two parameters Parameter 1 Connection handle Parameter 2 Reason for the disconnection The reason for example can be 0x08 which signifies a link connection supervision timeout which is used in the Proximity Profile A full list of Bluetooth HCI result codes for the reason of disconnection can be determined and are provided here Example EvDiscon sb See in BL600CodeSnippets zip DIM addrs addrs PUNGTION HndlrbBleMsa BYVAL mMsoqid AS INTEGER BYVAL mCex AS INTEGER IF nMsgID 0 THEN PRINT nNew Connection nerx ENDIF
83. AS INTEGER This shall be set to O Interactive No Command Workaround for FW 1 3 57 0 and earlier when there Is radio activity Example BleBondMngrErase sb See in BL6OO00CodeSnippets zip DIMES rc BleAdvertStop BleBondMngrErase 0 For FW 1 4 X Y and newer Example BleBondMngrErase sb See in BL600CodeSnippets zip DIEM ae BleBondMngrErase 0 BLEBONDMNGRERASE is an extension function BleBondMnerGetinfo FUNCTION This function retrieves the MAC address and other information from the trusted device database vid an index Note Do notrely ona device in the database mapping to a static index New bondings will change the position in the database BLEBONDMNGRGETINFO nindex addrS nExtralnfo INTEGER a result code Ret e l ete Typical value 0x0000 indicates a successful operation Arguments byVal nindex AS INTEGER nindex This is an index in the range 0 to 1 less than the value returned by SYSINFO 201 2 adadrS byRef addrS AS STRING Americas 1 800 492 2320 Option 2 183 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual On exit If nindex points to a valid entry in the database this variable contains a MAC address exactly seven bytes long The first byte identifies public or private random adaress The next six bytes are the address byRef nExtralnfo AS INTEGER On exit if
84. ASIC User Manual Advertising and Gatt Client is open Connected so scan remote Gatt Table for ALL services EVDISCPRIM SVC cHndl 2804 svcUuid FE01FE01 sHndl 1 eHndl 3 EVDISCPAIMSVC cHndl 2804 svcUuid FC033344 sHndl 4 eHndl 6 EVDISCPAIMSVC cHndl 2804 svcUuid FE01 DEAD sHndl 7 eHndl 9 EVDISCPRIMSVC cHndl 2804 svcUuid FB804BEF sHndl 10 eHndl 12 EVDISCPRIM SVC cHndl 2804 svcUuid FC033344 sHndl 13 eHndl 15 EVDISCPRIM SVC cHndl 2804 svcUuid FE01 DEAD sHndl 16 eHndl 18 EVDISCPRIMSVC cHndl 2804 svcUuid FE01 FE03 sHndl 19 eHndl 21 EVDISCPRIMSVC cHndl 2804 svcUuid FE01 DEAD sHndl 22 eHndl 24 EVDISCPRIMSVC cHndl 2804 svcUuid 00000000 sHndl 0 eHndl 0 Scan complete Scan for service with uuid OxDEAD EVDISCPRIMSVC cHndl 2804 svcUuid FE01 DEAD sHndl 7 eHndl 9 EVDISCPRIMSVC cHndl 2804 svcUuid F01 DEAD sHndl 16 eHndl 18 EVDISCPRIMSVC cHndl 2804 svcUuid FE01 DEAD sHndl 22 eHndl 65535 BLEDISCSERVICEFIRST and BLEDISCSERVICENEXT are both extension functions BleDiscCharFirst BleDiscCharNext FUNCTIONS These pair of functions are used to scan the remote Gatt Server for characteristics in a service with the help of the EVDISCCHAR message event and when called a handler for the event message must be registered as the discovered characteristics information is passed back in that message A generic or UUID based scan can be initiated The former scans for all characteristics and the latter scans for a characteristic with a particu
85. ATTRREAD event message On EVATTRREAD event message If Galt Status 0 then BleGattcReadData to actually get the data Else Attribute could not be read Call BleGattcRead If BleGattcRead ok then Wait for EVATTRREAD INTEGER a resulf code Typical value 0x0000 Returns Indicates a successful operation and means an EVATTRREAD event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVATTRREAD message will NOT be thrown Arguments byVal connHndl AS INTEGER This is the connection handle as returned in the on connect event for the connHndl connection on which the remote Gatt Server can be accessed This will have beei returned in the EVBLEMSG event message with msgld 0 and msgCix will have been the connection handle byVal attrHndl AS INTEGER attrHndl Set this to the handle of the attribute to read and will be a value in the range 1 to 65535 Americas 1 800 492 2320 Option 2 142 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ffset byVal offset AS INTEGER anos This is the offset from which the data in the attribute is to be read Interactive No Command BLEGATTCREADDATA connHndl attrHndl offset atirDataS This function is used to collect the data from the underlying cache when the EVATTRREAD event message has a success gatt status c
86. B cece cccesecccesscceeseceeeeees 167 168 BIGENCOE 1 6 veeeec eee cececccsseccesscccessceessccesscceenes 158 BS eC OC 2 Fusco cote cicstis cacacnbacteceatamaccestceteneaeghaceas 159 BIS ENC ODS SZ sectesscdewedusiatauevadduwsdeisuveresavevendades 160 BS IC OCS Oe seeds ace a as asstisae aocisesene eectaaeaeasacceecs 157 BleEncodeBITS wersecusdsccuscnsew tives sdasaueetcecioncdcawewure 166 BleEncodeFLOAT escce sees actecacoascnsocesctesennacuscnees 16 BleENCOdESFLOAT wnscsescctgectsesetasaresatseceeaaieiiees 163 BIEENCOGESFLOATEX uu ccc eeecccsseccesscceessceeees 162 BIGENCOGESSTRING cescscdacccssedevecasadocvomsebevecazetess 165 BIEENCOCeETIMESTAMP 1 1 0 cece eeecceeeceeesceecees 164 BLESECMNGRKEYSIZES 63 68 79 113 Be Ce AI essipessi nea Sih 86 BLES V CREGDEVINFO wrecssicercersvccsctesdvccueetencsceess 82 BleVSpClose ou ceeccccccceeseecsseeeeeeesees 19 BIE VSpFIUSN ce ecccccceeeeeeceeeeeeeeeeees 198 Americas 1 800 492 2320 Option 2 207 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Ble V SOIN O cessisse risie ieri e 192 BIS VS DODO cesa R 189 SILOM 0 Yo 0 I 194 BleVSpUartBridge cccccccccccccesseeeeeeeeeees 196 Bluetooth Result Codes cccccccssecnsssensecess 204 Decoding FUNCTIONS wincsesssssacidacseosiatocsssosetevens 167 Encoding FUNGCHOTS sennstocessuawatesaantnaccnteaseseaces 156 EVBLE_ADV_TIMEQOUT n 31 EV
87. BLEMS os pace vaniosenceatnectecatnneseunvoontooetonesgestestea 3 EVBLEM S G occas cossecdescocseceseavxedesvorscheseaetucrerececeas 31 EVOCARE O B reer ern eet renee eet terete 37 BV GARE C oraraa NEEE 42 EVC HARF O arn na 3 7 BV AIR C OD area ENT 39 EYCRAR YAT esere 35 AdB TET 34 BN PY BU Possess 44 FS I E E EEEE 44 EVV OPTAREM PIY cea a a 44 GPIO BV GING lt cccccescussaessavencussesssewsaaseacsasoueietecetenes 19 GPIOUNBINDEVENT csvessestsvetsecttemsestscndvessbmbenes 26 Se Oa TE gsis 24 IZCREADREGG cee ieeeerenned 17 RESET ee 18 SY OUINE E E E 12 SYSINFO S 14 So HERA SAME SE corseira rena 200 UARTOPEN acco eee ee 15 VSP Virtual Serial Port Events 186 188 Laird Technologies
88. D dscHnd1l 11 EVDISCDESC cHnd1l 3790 dscUuid 00000000 dscHnd1l 0 Descriptor Scan complete Scan for service with custom uuid 112233445566778899AABBCCDDEEFFOO EVDISCDESC cHnd1l 3790 dscUuid FC033344 dscHndl 5 EVDISCDESC cHnd1l 3790 dscUuid FC033344 dscHndl 8 EVDISCDESC cHnd1l 3790 dscUuid 00000000 dscHnd1l 0 Descriptor Scan complete Disconnected Peeing ss BLEDISCDESCFIRST and BLEDISCDESCNEXT are both extension functions Americas 1 800 492 2320 Option 2 132 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual BleGattcFindChar FUNCTION This function facilitates a quick and efficient way of locating the details of a characteristic if the uuid Is known along with the uuid of the service containing it and the results will be delived in a EVFINDCHAR event message If the Gatt server table has multiple instances of the same service characteristic combination then this function will work because in addition to the uuid handles to be searched for it also accepts instance parameters which are indexed from O which means the 4th instance of a characteristic with the same uuid in the 3 instance of a service with the same uuid will be located with index values 3 and 2 respectively Given that the results are returned in an event message a handler must be registered for the EVFINDCHAR event Depending on the size of the remote
89. EN PE UIG al FUNCTION BtnOPress PRINT Ue i ale te E ee BENDEUNC FUNCTION HndlrDiscon BYVAL hConn AS INTEGER BYVAL nRsn AS INTEGER AS INTEGER PRINTET Y nConneccion nC omm Closed 0x nRsa ENDFUNC 0 ONEVENT EVBLEMSG CALL HndlrBleMsg ONE VENT EV iDiks CON CALLENS TDI con I Stare adverts IF BleAdvertStart 0 addrS 100 10000 0 0 THEN Americas 1 800 492 2320 Option 2 34 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nAdverts Started n BLSE PRINT n nAdvertisement not successful EN DILE WAL TEVEN Expected Output Adverts Started New Connection 2915 Connection 2915 Closed 0x19 EVCHARVAL This event is thrown when a characteristic has been written to by a remote GATT client It comes with three parameters The characteristic handle that was returned when the characteristic was registered using the function BleCharCommit 2 The Offset 3 The Length of the data from the characteristic value Example EvCharVal sb See in BL600CodeSnippets zip DIM HM hat rc aes comme PUNGTICNSCnStarene DIM ce Nove atiro adRplo addres SCR e atero ia commit service rc BleSvcCommit 1 BleHandleUuidl 0x18EE hSvc rc BleServiceNew 1 BleHandleUuidl6 0x18EE hSvc initialise char write read enabled accept signed writes rc BleCharNew 0x0A BleHan
90. ENDFUNC 1 ONE VENT 2 NOt Pe YBUE CALL HnGibeN ery eur ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT 2 VGRHARCCED CALL HndlrCharceed lf 2Onstartup 0 THEN re BleCharValueRead hMyChar ats PRINT voOUme an Connect ana wr e to nner C CCD cCharscrerictrc PRONE nihe BiGOO will then send you data until burrer 25 ullin BLSE PRINT nFailure OnStartup ENDIF VASE Ee Americas 1 800 492 2320 Option 2 46 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual CloseConnections PRA ATE a apes Expected Output You can connect and write to the CCCD characteristic The BL600 will then send you data until buffer is full Connected to client Notifications have been disabled by client Notifications have been enabled by client NOcii ying Buffer full Notified 1818505336 times Be CG a4 Miscellaneous Functions This section describes all BLE related functions that are not related to advertising connection security manager or GATT BleTxPowerSet FUNCTION This function sets the power of all packets that are transmitted subsequently The actual value is determined by scanning through the value list 4 O 4 8 12 16 20 30 55 so that the highest value that is less than the desired value is selected If the desired value is higher than 55 55 is set For example setting 10
91. Example BleDecodeS16 sb See in BL600CodeSnippets zip DIM Charidancile yiL sveianclle ire DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM attra acere A000 AoA 00A aAa 37 32839 DIM uuid item 0x18953 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read 2 signed bytes from index 2 rc BleDecodeS16 attr vl 2 PRINT ndata im Hex O INTEGER W wl PRINT V ndata in Decimal Yz yl Vane read 2 signed bytes from index 6 rc BleDecodeS16 attrsS vl1 6 PRINT Andata in Hex Ox INTEGER AH yvl PRINE V ndata in Decimal 1 ery lew am Expected Output Americas 1 800 492 2320 Option 2 170 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual in Hex 0x00000302 in Decimal 770 in Hex OxFFFF8786 in Decimal 30842 BLEDECODES16 is an extension function BleDecodeU16 This function reads two bytes from a string at a specified offset into a 32bit integer variable without sign extension If the offset points beyond the end of the string then this function fails BLEDECODEU16 atirS nData nindex INTEGER the number of bytes extracted from the attribute string Can be less than Returns th
92. Firmware Zip file DIM re DIM mv fesse s SS SSS SS SSS SSS SSS SS SS SS SS SS SSS SS SS SS SSS SES Handler for generic BLE messages ee FUNCTION HandlerBleMsg BYVAL nMsgid BYVAL nCtx AS INTEGER SELECT nMsqid CASE 19 PETNE a Powe Bani Namrming ss mcCrx mv ReadPwrSupp1 yMv PRINT Yn gt Supply voltage a6 Readrwrsupol y Mv my CASE ELSE ignore this message ENDSELECT ENDFUNC 1 SSSS SSS SSS SSS SSS SS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSS SSSSSS5 5 Handler to service button O pressed f SSS SSS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SSS SSS SS SS SS SSS SSS 555555555555 DUNG PEON hncite hrm bie AS eh Gri just exit and stop waiting for events ENDFUNC 0 ONEVENT EVBLEMSG CALL HandlerBleMsg ONEVENT EVGPIOCHANT CALL ANd BENET rc GpioBindEvent 1 16 1 Channel ly band to low tranciivon On CRIO pin 16 PRINT nsupply voltage 1s gt Readrwrsupp yMv I mVn mv 2700 rc SetPwrsupplyThreshMv mv Americas 1 800 492 2320 Option 2 202 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nWatting for power supply to fall below mv mv wait for events and messages WALTEVENT PRINT ANE EINen Expected Output Supply voltage is 3343mV Waiting for power supply to fall below 2700mV EXILCiNG 4s SETPWRSUPPLYTHRES
93. GpioRead sb See in Firmware Zip file DIM cignal signal GpioRead 3 PRIND anal Expected Output GPIOREAD is a Module function GpioWrite SUBROUTINE This routine writes a new value to the GPIO pin If the pin number is invalid nothing happens If the GPIO pin has been configured as a PWM output then the nNewValue specifies a value in the range 0 to N where N is the maximum PWM value that generates a 100 duty cycle output a constant high signal and N is a value that is configured using the function GpioConfigPWM If the GPIO pin has been configured as a FREQUENCY output then the nNewValue specifies the desired frequency in Hertz in the range 0 to 4000000 Setting a value of O makes the output a constant low value Setting a value greater than 4000000 clips the output to a 4 MHz signal GPIOWRITE nSigNum nNewValue Arguments byVal nSigNum INTEGER The signal number as stated in the pinout table of the module byVal nNewValue INTEGER The value to be written to the port If the pin is configured as digital then 0 will clear the pin and a non zero value will set it nNewValue o l a If the pin is configured as analogue then the value is written fo the pin If the pin is configured as a PWM then this value sets the duty cycle If the pin is configured as a FREQUENCY then this value sets the frequency nSigNum Interactive No Command Example GpioWrite sb See in Firmware Zip file DIM rc dutycycle fr
94. HMV is an extension function T EVENTS amp MESSAGES smart BASIC is designed to be event driven which makes it suitable for embedded platforms where it is normal to wait for something to happen and then respond To ensure that access to variables and resources doen t end up in race conditions the event handling is done synchronously meaning the smart BASIC runtime engine has to process a WAITEVENT statement for any events or messages to be processed This guarantees that smart BASIC will never need the complexity of locking variables and objects The subsystems which generate events and messages relevant to the routines described in this manual are as follows BLE events and messages as described here Generic Characteristics events and messages as described here Americas 1 800 492 2320 Option 2 203 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 8 MODULE CONFIGURATION There are many features of the module that cannot be modified programmatically which relate to interactive mode operation or alter the behaviour of the smartBASIC runtime engine These configuration objects are stored in non volatile flash and are retained until the flash file system is erased via AT amp F or AT amp F 1 To write to these objects which are identified by a positive integer number the module must be In interactive mode and the co
95. IM char uuid e eon a rud Ss lLohamcheaUuiec Ihe 2 eheee eee ie e UE DiM man mm aeS Eeer M adara O 207 05 ne Jj Metad ta for value aerO DIM mdCecd mdCecd BleAttrMetadata 1 2 0 rc Metadata for CCCD attribute of Characteristic Pre Create a new char I Indicatable not Broadcastable so mdCeced is included but mot mdSccad Can be read not written shown in mdVal as well V IF BleCharNew 0x22 charvuid mdVal mdCced 0 0 THEN PRINT nNew Characteristic created ELSE PRINT nFailed END Expected Output New Characteristic created BLECHARNEW is an extension function BleCharDescUserDesc FUNCTION This function adds an optional User Description Descriptor to a Characteristic and can only be called after BleCharNew has started the process of describing a new Characteristic Americas 1 800 492 2320 Option 2 93 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The BI 4 0 specification describes the User Description Descriptor as a UTF 8 string of variable size that is a textual description of the characteristic value It further stipulates that this attribute is optionally writable and so a metadata argument exists to configure it to be so The metadata automatically updates the Writable Auxilliaries properties flag for the Characteristic This is why that flag
96. INTEGER svcUuidHndI Set this to the service uuid handle which will have been generated either by BleHandleUuid16 or BleHandleUuid128 or BleHandleUuidSibling byVal svcindex AS INTEGER svclIndex This is the instance of the service to look for with the uuid handle svcUvidHndl where 0 is the first instance 1 is the second etc byVal charUuvidHndl AS INTEGER charUuidHndl Set this to the characteristic uuid handle which will have been generated either by BleHandleUuid16 or BleHandleUvid128 or BleHandleUuidSibling byVal charlndex AS INTEGER charlndex This is the instance of the characteristic to look for with the uuid handle charUvidHndl where 0 is the first instance 1 is the second etc Interactive No Command Example BleGattcFindChar sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 134 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ee Remote server has 5 prim services with 16 bit uuid and 3 with 128 bit uuids 3 of the 16 bit uuid are the same value OxDEAD and 2 of the 128 bit uuids are also the same 112233445566778899AABBCCDDEEFF jee i Seievet Ceecivec Using EleGaniweMolwimeelaeic Sulo iinwolkecl iin Ooemilic sci aeng Nordic Usb Dongle Peo 0ee Divine ceo conr e annd a Wiad calc ce 1 asc DUNG TRON SOnms EAE DIM ror adk bo aac o e oR rc pleAdyRotInit a
97. ION This function is used to enable or disable bonding when pairing Note This function will oe deprecated in future releases It is recommended to invoke this function with the parameter set to 0 before calling BleAuthenticate Americas 1 800 492 2320 Option 2 71 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLESECMNGRBONDREQ nBondReq INTEGER a resulf code Reuni Typical value 0x0000 indicates a successful operation Arguments byVal nBondReq AS INTEGER nBondReq 0 Disable 1 Enable Interactive NIG Command Example BleSecMngrBondReq sb See in BL600CodeSnippets zip IF BleSecMngrBondReg 0 0 THEN PRINT nBonding disabled ENDI IE Expected Output Bonding disabled BLESECMNGRBONDREQ is an extension function BleAuthenticate FUNCTION This routine is used to induce the device to authenticate the peer This will be deprecated in future firmware BLEAUTHENTICATE nConnCtx INTEGER a result code penn Typical value 0x0000 indicates a successful operation Arguments byVal nConnCtx AS INTEGER nConnCtx This is the context value provided in the EVBLEMSG 0 message which informed the stack that a connection had been established Interactive Command No See example for BleDisconnect Change rc BleAuthenticate nCtx BLEAUTHENTICATE is an extension function t
98. ITEVENT statement is used as normal to wait for events and messages Depending on the size of the remote GATT server table and the connection interval the scan of all descriptors may take many 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals EVDISCDESC event message This event message WILL be thrown if either BleDissDescFirst or BleDiscDescNext returns a success The message contains 3 INTEGER parameters Connection Handle Descriptor Uvid Handle Handle for the Descriptor in the remote Gatt Table If no more descriptors were discovered because the end of the table was reached then alll parameters will contain O apart from the Connection Handle Descriptor Uvid Handle contains the uuid of the descriptor and supplied as a handle Handle for the Descriptor in the remote Gatt Table is the handle for the descriptor and also is the value to store to keep track of important characteristics in a gatt server for later read write operations BLEDISCDESCFIRST connHandle descUuvidHandle charValHandle A typical pseudo code for discovering descriptors involves first calling BleDiscDescFirst with Information obtained from a characteristics scan and then waiting for the EVDISCDESC event message and depending on the information returned in that message calling BleDiscDescNext which in turn wil
99. LOAT is an extension function Americas 1 800 492 2320 Option 2 176 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleDecodeSFLOAT FUNCTION This function reads two bytes in a string at a specified offset into a couple of 32bit integer variables The decoding results in two variables the 12 bit signed maintissa and the 4 bit signed exponen If the offset points beyond the end of the string then this function falls BLEDECODESFLOAT attrS nMatissa nExponent nIndex INTEGER the number of bytes extracted from the attribute string Can be less Returns than the size expected if the nlndex parameter Is positioned towards the end of the string Arguments attrs byRef attrS AS STRING This references the attribute string from which the function reads byRef nMantissa AS INTEGER This is updated with the 12 bit mantissa from the two byte object If the nExponent is O you MUST check for the following special values nMantissa OxO07FFFFF NaN Not a Number 0x00800000 NRes Not at this resolution OxOO7FFFFE INFINITY 0x00800002 INFINITY 0x00800001 Reserved for future use byRef nExponent AS INTEGER nExponent This is updated with the four bit mantissa If it is zero check the nMantissa for special cases as stated above byVal nindex AS INTEGER This is the zero based index into the string attr from which data
100. N re BleGattcOpen 0 0 ENDIF EMDEUNG vise Americas 1 800 492 2320 Option 2 113 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected EA LEUNG ELSEIF nMsgID 0 THEN PRINT n Connected END ie ENDEUNCG 21 FUNCTION HandlerGattcTout cHndl AS INTEGER PRINT WneEVGATTETOUT connHandle chnal ENDEUNC i Main equivalent eR ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVGATTCTOUT call HandlerGareclourn re OnStarctup WALTEVENT Expected Output EVGATTCTOUT connHandle 123 BleGattcOpen FUNCTION This function is used to Initialise the GATT Client functionality for immediate use so that appropriate buffers for caching GATT responses are created in the heap memory About 300 bytes of RAM is required by the GATT Client manager and given that a majority of BL600 use cases will not utilise it the sacrifice of 300 bytes which is nearly 15 of the available memory is not worth the permament allocation of memory There are various buffers that need to be created that are needed for scanning a remote GATT table which are of fixed size There is however one buffer which can be configured by the smartBASIC apps developer and that is the ring buffer that is used to store Incoming notifiabl
101. Num byVal nEventNum INTEGER The GPIO event number in the range of 0 N which is disabled so that it no longer generates run time events in smart BASIC Note A value of 0 is only valid for the BL600 Interactive No Command Example GpioUnAssignEvent sb See in Firmware Zip file FUNCTION BtnOPress PRINT nHel lo ENDFUNC 1 FUNCTION TmrOTimedOut PRINT nNothing happened ENDPEUNG 0 PRINT Gprokssugmivent Oe ike i ant ONEVENT EVDETECTCHANO CALL BtnOPress ONEVENT EVTMRO CALL TmrOTimedOut PRINT GpioUnAssignEvent 0 n PRINTE peress bueton 0 a TamersStart 0 38000 0 WALTEVENT Americas 1 800 492 2320 Option 2 28 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output O O Press button 0 Nothing happened GPIOUNASSIGNEVENT is a Module function Americas 1 800 492 2320 Option 2 29 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 5 BLE EXTENSIONS BUILT IN ROUTINES MAC Address To address privacy concerns there are four types of MAC addresses in a BLE device which can change as often as required For example an iPhone regularly changes its BLE MAC address and always exposes only its resolvable random address To manage this the usual six o
102. O PRINT BleAuthenticate nCtx GATT Server Functions This section describes all functions related to creating and managing services that collectively define a GATT table from a GATT server role perspective These functions allow the developer to create any Service that has been described and adopted by the Bluetooth SIG or any custom Americas 1 800 492 2320 Option 2 72 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Service that implements some custom unique functionality within resource constraints such as the limited RAM and FLASH memory that is exist in the module A GATT table is a collection of adopted or custom Services which in turn are a collection of adopted or custom Characteristics Although keep in mind that by definition an adopted service cannot contain custom characteristics but the reverse is possible where a custom service can include both adopted and custom characteristics Descriptions of Services and Characteristics are available in the Bluetooth Specification v4 0 or newer and like most specifications are concise and difficult to understand What follows is an attempt to familiarise the reader with those concepts using the perspective of the smartBASIC programming environment To helo understand the terms Service and Characteristic better think of a Characteristic as a container or a pot of data where
103. ORTED BY HOST BT HCI HOST BUSY PAIRING BT HCI CONN REJ DUETO NO SUITABLE CHN FOUND BT HCI CONTROLLER BUSY BT HCI CONN INTERVAL UNACCEPTABLE BT HCI DIRECTED ADVERTISER TIMEOUT BT HCI CONN TERMINATED DUE TO MIC FAILURE BT HCI CONN FAILED TO BE ESTABLISHED Americas 1 800 492 2320 Option 2 205 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Ox1B Ox C Ox1D Ox1E Ox1F 0x20 x2 0x22 0x23 0x24 032o 0x26 0x27 0x28 0x29 0x2A Ox ZC Ox2D Ox ZF Ox ZF 0x30 0x32 9x34 0X39 0x36 Ox37 0x38 0x39 0x3A 0x3B 0Ox3C 0x3D Ox3E Laird Technologies smart BASIC User Manual 10 ACKNOWLEDGEMENTS The following are required acknowledgements to address our use of open source code on the BL600 to implement AES encryption Laird s implementation includes the following files aes c and aes h Copyright c 1998 2008 Brian Gladman Worcester UK All rights reserved LICENSE TERMS The redistribution and use of this software with or without changes is allowed without the payment of fees or royalties providing the following Source code distributions include the above copyright notice this list of conditions and the following disclaimer Binary distributions include the above copyright notice this list of conditions and the following disclaimer in their documentation The name of the copyright holder is not used to endorse products built using
104. PRINT nHorror Commi tCIng advert reports Ty Integer hrc ENDIF BLSE PRINT nBroadcasts have been disabled by client IF ResetAdvReport 0 THEN PRINT nAdvert reports reset BLSE PRINT nError Resetting advert reporto integer ihre ENDIF ENDIF EESE PRINT his lo for some other character tL ENDIF ENDFUNC 1 PUNCTION HadlreChnarVal BYVAl Chearhandie BYVAL OELSE B VAL Len DIM s IF charHandle hMyChar THEN rc BleCharValueRead hMyChar chVals PRINT nNew Char Value chVals END DE ENDFUNC 1 BUNCTEON Hindle Dasconineonm snken dim acdcins eCc BleAdvertStart 0 addrs 20 300000 0 Americas 1 800 492 2320 Option 2 41 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BNDEUNG 1 ONEVENT EVBLEMSG CALL HndilrBleMsg ONEVENT EVCHARSCCD CALL HndlrCharSccd ONEVENT EVUARTRX CALE Hind levartRx ONEVENT EVCHARVAL CALL einer aia aul ONEVENT EVDISCON CATEL andir Dake ele IF OnStartup 0 THEN re BleCharValueRead hMyChar chVal PRINT nCharacteristie Values T ehVals PRINT nWrite a new value to the characteristic then enable broadcasting nThe module will then disconnect and broadcast the new characteristic value PRINT n Press any key fo exter im ELSE PRINT nFailure OnStartup ENDIF WALTEVENT CloseConnections PRINTANE DEINO eN Expected Output Cha
105. PRINT nVso State T BleVvSpInio 0 Expected Output Vsp State 1 Rx DUETer capacity 128 T bD fier Capacity 120 Bytes waiting to be read from rx buffer 0 Free space in tx buffer 128 Vsp State 0 BLEVSPINFO is an extension subroutine BleVSpWrite FUNCTION This function is used to transmit a string of characters from the virtual serial port BLEVSPWRITE strMsg INTEGER Oto N Actual number of bytes successfully written to local transmit ring Returns buffer E tion Local Stack Frame Underflow ASE RERA Local Stack Frame Overflow Arguments byRef strMsg AS STRING The array of bytes to be sent STRLEN strMsg bytes are written to the local transmit ring buffer If STRLEN strMsg and the return value are not the same it implies that tr strMs transmit buffer did not have enough space to accommodate the data J if the return value does not match the length of the original string use STRSHIFTLEFT function to drop the data from the string so subsequent calls to this function only retry with data not placed in the output ring buffer Another strategy is to wait for EVVSPTXEMPTY events then resubmit data Interactive NO Command Americas 1 800 492 2320 Option 2 193 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Related BLEVSPOPEN BLEVSPCLOSE BLEVSPINFO BLEVSPREAD BLEVSPFLUSH Commands Note strMsg c
106. Q ENDTE ENDE endfunc 1 tunction Handler Charbisc chandi cUumd cerop hval asUuid as Integer priat mE Vii Sc CHART T Prints sehmcdi cima print schUudd rnbeqer h cUuld Print Prop 7 CeLror Print valHndi hval Print Sr Veur a a uand IF hVal 0 THEN PRINT nCharacteristic Scan complete EXITEFEUNC Q ELSE re BleDiscCharNext conHnd1 TF re l 0 THEN PRINT neharacterictics Scan abort EXITEFEUNC Q ENDIF ENDIF endfunc 1 Americas 1 800 492 2320 Option 2 125 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual j S333 33 353233 SS 35S255 l Main equivalent J SSS S SS SSS SS SSS SSS SS SS SS SS SS SS SS SS SSS SS SSS SS SS SS SS SSS SS SH SS SSS SS SSS SS SS SS SS SSE ONEVENT EVBLEMSG CALL HndlrBleMsg Onkv ent sh Dils PRIMs Onavent Sh VP Se Chak call HandlerPrimSvc call HandlerCharDisc Register base uuids with the underlying stack otherwise the services with the 128bit uuid s will be delivered with a uuid handle FF000000 UNKNOWN uuid 1122334455667788 992ABBCCDDETEEF TOO uuids StrDehexizes uuids undi BleHandleUvuid128 uuids uuc 1122DEAD556677898993ABBCCDDBERE OQ uuidsS StrDehexizes uuid undi Blethandlevuidl23 unads IF OnStartup 0 THEN PRINT mAGgVeruising BLSE PRINT nea ae On Ear tup ENDI E and Gatt Client is open n
107. RINT nFailed to create a handle BLUSE PRINT Handle ror MRO Uvid 1S Y Integer in ShUmerRS 27 in addins a BNDILE Expected Output Handle for ARS Uuid 2s FEQLIGOD lt 33482739 BLEHANDLEUUID16 is an extension function BleHandleUuid128 FUNCTION This function takes a 16 byte string and converts It into a 32 bit integer handle The handle consists of a 16 bit 2 byte offset into a new 128 bit base UUID The base UUID Is basically created by taking the 16 byte input string and setting bytes 12 and 13 to zero after extracting those bytes and storing them in the handle object The handle also contains an index into an array of these 16 byte base UUIDs which are managed opaquely in the underlying stack The returned handle shall be treated by the developer as an opaque entity and no further logic shall be based on the bit content However note that a string of zeroes represents an invalid UUID handle Please ensure that you use a 16 byte UUID that has been generated using a random number generator with sufficient entropy to minimise duplication as stated in an earlier section and that the first byte of the array is the most significant byte of the UUID BLEHANDLEUUID128 stUuidS INTEGER A handle representing the shorthand UUID If zero which is an invalid Returns UUID handle there is either no soare RAM memory to save the 16 byte base or more than 253 custom base UUIDs have been registered Arguments byRef stUuvid
108. S AS STRING tUvids Any 16 byte string that was generated using a UUID generation utility that has eer enough entropy to ensure that it is random The first byte of the string is the MSB of the UUID that is big endian format Interactive No Command d Example BleHandleUuidl28 sb See in BL600CodeSnippets zip DIM uuics s hnUuidCustom create a custom uuid for my ble widget uuid ced ls 609244 e 7d Cf 164 62b26 uuid Strbehexizes uuid Americas 1 800 492 2320 Option 2 84 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual hUuraCucton Be lehancdleUinadl 23 mmae gt Le hvurdeusrem 0 TEEN PRINT nFailed to create a handle ELSE PRINT Handle for custom Vuid is Interer A RUU rdCucstom x hUuureCustom i e ENDIF hUuidCustom now references an object which points to a base uuid ced9d91366924a1287d56f2747622b2a note 0 s in byte position 2 3 and an offset 0xd913 Expected Output Handle for custom Uuid is FC0O3D913 66856685 BLEHANDLEUUID 128 is an extension function BleHandleUuidSibling FUNCTION This function takes an integer in the range O to 65535 along with a UUID handle which had been previously created using BleHandleUuvid16 or BleHandleUuvid128 to create a new UUID handle This handle references the same 128 base UUID as the one referenced by the UUID hand
109. SUPPLYMV Returns INTEGER the power supply voltage in millivolts Arguments None Interactive Command me Example ReadPwrSupplyMv sb See in Firmware Zip file read and print the supply voltage PRINT nSupply voltage is ReadPwrSupplyMv mv Expected Output Supply voltage is 3343mV READPWRSUPPLYMV is an extension function SetPwrSupplyThreshMv FUNCTION This function sets a supply voltage threshold If the supply voltage drops below this then the BLE_EVMSG event is thrown into the run time engine with a MSG ID of Americas 1 800 492 2320 Option 2 201 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLE_EVBLEMSGID_POWER_FAILURE_LWARNING 19 and the context data will be the current voltage in millivolts Events amp Messages 19 The supply voltage has dropped below the value specified as the argument to this function in the most recent call The context data Is the current reading of the supply voltage in millivolts SETPWRSUPPLYTHRESHMV nThresh INTEGER O if the threshold is successfully set 0x6605 if the value cannot be penne implemented Arguments byVal nThresMv AS INTEGER nThreshMv The BLE_LEVMSG event Is thrown to the engine if the supply voltage drops below this value Valid values are 2100 2300 2500 and 2700 Interactive Command Ne Example SetPwrSupplyThreshMv sb See in
110. SiG ie 7 ss VVAA BBC DID R ROON uus StrDehexizes uus unce Blebandlevurdi23 uus pis C ODES S66 7 Ss SOMA BRC CDI aE Oe uus StrDehexizes uus uHndD BleHand eUuidl28 uus sIdx 2 Cldx 1 didx 1 handle will be 37 Ge BleGatrecringbpesc conkhndl ubnds sildx ulmde cidx UMED didx IF rc 0 THEN BleDiscCharFirst will exit with 0 when operation is complete WALTEVENT BNDL E sIdx 1 cIldx 3 didx 4 does not exist ne BleGarectingbese CONECT SS CE E IF rc 0 THEN Americas 1 800 492 2320 Option 2 139 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleDiscCharFirst will exit with 0 when operation is complete WALTEVENT ENDIF CloseConnections ENDIF ENDFUNC 1 fumetr1onm Handilerbrindbesc cHmdl hmdl as integer Ene Vola DIN IDIDI Se ih Print Schndl chncdil Print deena n AnA IF hndl 0 THEN PRINT nbad NOT find the descripror ELSE PRINT nFound the descriptor at handle hndl PREND Anov lox soldx Char lidn aclhdx dese lex cles ENDIF endfunc 0 asessssassssssssssasassssssse ses ssasa sa sssasseessssassessassesssasesessssssss Main equivalent eaeesassssasssa sa sasas ss assas sas sssea se sasas se sssse ass asssssessssssseesssssssss ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVFINDDESC call HandlerFindDesc Register base uuids wi
111. SvcCommit byRef attrS AS STRING This string contains the initial value of the Value attribute in the Characteristic The content of this string is copied into the GATT table and so the variable can be reused after this function returns byRef charHandle AS INTEGER The composite handle for the newly created Characteristic is returned in this argument It is zero if the function fails with a non zero result code This handle is then used as an argument in subsequent function calls to perform read write actions so it is must be placed in a global smartBASIC variable When a significant event occurs as a result of action by a remote client an event charHandle message is sent to the application which can be serviced using a handler That message contains a handle field corresponding to this composite characteristic handle Standard procedure Is to select on that value to determine which Characteristic the message Is intended for atirS See event messages EVCHARHVC EVCHARVAL EVCHARCCCD EVCHARSCCD EVCHARDESC Interactive No Command Example BleCharCommit sb See in BL600CodeSnippets zip DEFINE BE SERV ECE SECONDARY O DEFINE PLET ERVIK ah ee MUN 1 DIMER DIM attr usrDescs usrDesco A description DIM HAES OVO composite handle for hts primary service DIM mdCharVal mdCharVal BleAttrMetaData 1 1 20 0 rc DIM mdCeed mdCced BleArerMetadata 1 272 007 re DIM mdUsrDsc mdUsrDsc BleAttrMetaData 1 1
112. TA oud E n BLEVSPUARTBRIDGE is an extension subroutine BleVSpFlush SUBROUTINE This subroutine flushes either or both receive and transmit ring buffers This is useful when for example you have a character terminated messaging system and the peer sends a very long message filling the input buffer In that case there is no more space for an incoming termination character A flush of the receive buffer is the best approach to recover from that situation Americas 1 800 492 2320 Option 2 198 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLEVSPFLUSH bitMask ra Local Stack Frame Underflow eee Local Stack Frame Overflow Arguments byVal bitMask AS INTEGER bitMask Bit O is set to flush the Rx buffer Bit 1 is set To flush the Tx buffer Set both bits t flush both buffers Interactive KiS Command Related BLEVSPOPEN BLEVSPCLOSE BLEVSPINFO BLEVSPWRITE BLEVSPREAD Commands Example BleVSpFlush sb See in BL600CodeSnippets zip DIM conHndl EE Open VSp and start advertising 8 SUB Oi Siac DIM rO onn Sexo CRP acids adp adp ac ies ro BleVopOpen 122 128 0 nnal rc BleScanRptInit scRpt rc BleAdvRptAddUuidl128 scRpt hnd1 rc BleAdvRptsCommit adRpt scRpts re p leAdvertstarc 0 addrs 20 300000 0 rc GpioBindEvent 1 16 1 Channel 1 bind to low transition on GPIO pin 16
113. TION This function reads a single byte in a string at a specified offset into a 32bit integer variable without sign extension If the offset points beyond the end of the string this function fails BLEDECODEU8 attrS nData nindex INTEGER the number of bytes extracted from the attribute string Can be less Returns than the size expected if the nlndex parameter is positioned towards the end of the string Arguments attrs byRef attrS AS STRING This references the attribute string from which the function reads byRef nData AS INTEGER nData This references an integer to be updated with the 8 bit data from attr without sign extension byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the nindex string attr is not long enough to accommodate the index plus the number of bytes to read this function falls Interactive No Command Example BleDecodeU8 sb See in BL600CodeSnippets zip DIM echriandie vil svchandle re DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM aters seater o 00 Ol 02 050485 25 87 e3 eo DIM Une 3 uuid 0x1853 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read unsigned byte from index 2 rc BleDecodeU8 attrS vl1 2 PRINT andata ion Hex
114. TION HndirChareeca BYVAL charHamdile BYVAL nVal As INTEGER DIM values IF charHandle hMyChar THEN TE nivel t0x07Z Reel PRINT nIndications have been enabled by client values hello IF BleCharValueIndicate hMyChar value 0 THEN PRINT nFailed to indicate new value ENDI ELSE PRINT nIndications have been disabled by client ENID IL E BLSE PRINT milhte 6 for some other Characreris ruc ENDIE ENDEWNC ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT EVCHARHVC CALE shovel biatG lacie she ONEVENT EVCHARCCCD CALL HndlrCharCccd ONEVENT EVUARTRX CALE Hnd ErUerikx IF OnStartup 0 THEN re BleCharValueRead hMyChar at PRINT nValue or thie characteristic AM Char T als ot abs Americas 1 800 492 2320 Option 2 38 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT nYyou can weice to che COCD characteristic PRINTE nTthe BLOOO will chen incdicarte a new Charactceristie valuen PRINT n Press any key to exit BSE PRINT nFailure OnStartup ENDIF WALTEVENT CloseConnections PETES ne Ien er Expected Output Value of the characteristic 1346437121 is H You can write to the CCCD characteristic The BL600 will then indicate a new characteristic value Press any key to exit Connected to client Indications have been enabled by client Got confirmation of recent indication
115. TLE COMMAND _ PARAMETERS 0x12 BT HCI _ REMOTE USER _ TERMINATED CONNECTION 0x13 BT HCI _ REMOTE DEV TERMINATION DUE TO LOW RESOURCES 0x14 BT HCI _ REMOTE _ DEV TERMINATION _ DUE TO POWER OFF 0x15 BT HCI LOCAL HOST TERMINATED _ CONNECTION 0x16 BT HCI REPEATED _ ATTEMPTS Ox BT HCI PAIRING NOTALLOWED 0x18 BP HCI LMP PDU 0x19 BT HCI UNSUPPORTED REMOTE FEATURE Ox1A Americas 1 800 492 2320 Option 2 204 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BT HCI SCO OFFSET REJECTED BT HCI SCO INTERVAL REJECTED BT HCI SCO AIR MODE REJECTED BT HCI STATUS CODE INVALID LMP PARAMETERS BT HCI STATUS CODE UNSPECIFIED ERROR BT HCI UNSUPPORTED LMP PARM VALUE BT HCI ROLE CHANGE NOT ALLOWED BT HCI STATUS CODE LMP RESPONSE TIMEOUT BT HCI LMP ERROR TRANSACTION COLLISION BT HCI STATUS CODE LMP PDU NOT ALLOWED BT HCI ENCRYPTION MODE NOT ALLOWED BT HCI LINK KEY CAN NOT BE CHANGED BT HCI REQUESTED QOS NOT SUPPORTED BT HCI INSTANT PASSED BT HCI PAIRING WITH UNIT KEY UNSUPPORTED BT HCI DIFFERENT TRANSACTION COLLISION BT HCI QOS UNACCEPTABLE PARAMETER BT HCI QOS REJECTED BT HCI CHANNEL CLASSIFICATION UNSUPPORTED BT HCI INSUFFICIENT SECURITY BT HCI PARAMETER OUT OF MANDATORY RANGE BT HCI ROLE SWITCH PENDING BT HCI RESERVED SLOT VIOLATION BT HCI ROLE SWITCH FAILED BT HCI EXTENDED INQUIRY RESP TOO LARGE BT HCI SSP NOT SUPP
116. VNOTIBUF event Depending on the connection interval the write to the attribute may take many 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals EVNOTIFYBUF event This event message WILL be thrown if BleGattcWriteCmd returned a success The message contains no parameters BLEGATTCWRITECMD connHndl atirHndl atirDataS A typical pseudo code for writing to an attribute which will result in the EVNOTIFYBUF event is as follows Americas 1 800 492 2320 Option 2 149 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Register a handler for the EVNOTIFYBUF event message On EVNOTIFYBUF event message Can now send another write command Call BleGattcWriteCmd If BleGattcWrite ok then Wait for EVNOTIFYBUF INTEGER a resulf code neurs Typical value 0x0000 indicates a successful operation Arguments byVal connHndl AS INTEGER This is The connection handle as returned in the on connect event for the connHndl connection on which the remote Gatt Server can be accessed This will have beel returned in the EVBLEMSG event message with msgid 0 and msgCtx will have been the connection handle byVal attrHndl AS INTEGER The handle for the attribute that is to be written to byRef atirDa
117. ValHandle AS INTEGER charValHandle This is the value attribute handle of the characteristic on which the descriptor scan Is to be performed It will have been acquired from an EVDISCCHAR event Interactive Command ne BLEDISCDESCNEXT connHandle Calling this assumes that BleDiscCharFirst has been called at least once to set up the internal characteristics scanning state machine and that BleDiscDescFirst has been called at least once to start the descriptor discovery process INTEGER a result code Typical value 0x0000 Indicates a successful operation and means an EVDISCDESC event Returns message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCDESC message will NOT be thrown Arguments byVal nConnHandle AS INTEGER This is the connection handle as returned in the on connect event for the connHandle connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgid 0 and msgCt will have been the connection handle Interactive No Command Example BleDiscDescFirst Next sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 128 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ee Remote server has 1 prim service with 16 bit uuid and 1 characteristics 7
118. a result code Rerun Typical value 0x0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This argument is the string that will be written to an attribute byValn AS INTEGER This must be in the range 2046 to 2046 or the function fails The data is written in little endian so the least significant byte is at the lower memory address Note The range Is not 2048 because after encoding the following two byte values have special meaning OxO7FF NaN Not a Number Ox0800 NRes Not at this resolution OxO7FE INFINITY Ox0802 INFINITY Ox0801 Reserved for future use byValn AS INTEGER This value must be in the range 8 to 7 or the function falls byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data is nindex written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails nMatissa nExponent Interactive Command Ne Americas 1 800 492 2320 Option 2 163 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example BleEncodeSFloat sb See in BL600CodeSnippets zip DIMERS DIM attreS attrS s SUB Encode BYVAL mantissa BYVAL exp IF BleEncodeSFloa
119. acteristic is defined with no authentication or encryption requirements a single byte attribute The following properties are enabled WRITE WRITE_NO_RESPONSE The ModemoOut characteristic value attribute is with no authentication or encryption requirements a single byte attribute The following properties are enabled NOTIFY The CCCD descriptor also requires no authentication encryption Americas 1 800 492 2320 Option 2 185 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual For Modemin only bit zero is used which is set by 1 when the client can accept data and 0 when it cannot inverse logic of CTS in UART functionality Bits 1 to 7 are for future use and should be set to 0 For ModemOuTt only bit zero is used which is set by 1 when the client can send data and 0 when it cannot inverse logic of RTS in UART functionality Bits 1 to 7 are for future use and should be set To 0 Note Both flags in Modemin and ModemOut are suggestions to the peer just as in a UART scenario If the peer decides to ignore the suggestion and data is kept flowing the only coping mechanism is to drop new data as soon as internal ring buffers are full Given that the outgoing data is notified to the client the tx fifo characteristic has a Client Configuration Characteristic CCCD which must be set to 0x0001 to allow
120. airing is detected to be in progress the transmit power is automatically reduced so that the bubble of influence is reduced and thus a proximity based enhanced security is achieved To take advantage of this pairing mechanism use the function BleTxPwrWhilePairing to reduce the transmit power for the short duration that the pairing Is in progress Tests have shown that setting a power of 55 using BleTxPwrWhilePairing will create a bubble of about 30cm radius outside which pairing will not succeed This will be reduced even further if the BL600 module Is in a case which affects radio transmissions BleBondMngrErase Note For firmware versions prior to 1 4 X Y this subroutine has a bug It occurs when the subroutine is called during radio activity Workaround when advertising 1 Stop adverts by calling BleAdvertStop 2 Call BleBondMngrErase 3 Restart adverts using BleAdvertStart SUBROUTINE Americas 1 800 492 2320 Option 2 182 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This subroutine deletes the entire trusted device database if the supplied parameter is 0 Other values of the parameter are reserved for future use Note In Interactive Mode the command AT BTD can also be used to delete the database BLEBONDMNGRERASE nFutureUse Arguments aruiurelise byVal nFutureUse
121. ameters request connection interval in range 50ms to 75ms and link supervision timeout of 4seconds with a slave latency of 19 Ce bBleserCurconnerarmns mer sv000 7 750007 400C0007 12 ENDIF CASE 1 BLE EVBLEMSGID DISCONNECT PRINT n Disconnected nCtx EXLTEUNG Q CASE 14 BLE EVBLEMSGID CONN PARMS UPDATE ryc Ble cetCurconnParms mCi intrvl sprvto slat IF rc 0 THEN PRINT nncConn Interval intrvl PRINT nConn Supervision Timeout opvio PRINT nConn Slave Latency slat ENDIF CASE 15 BLE_EVBLEMSGID CONN PARMS UPDATE FAIL PRINT n Conn Parm Negotiation FAILED CASE ELSE PRINT nBle Msg nMsgId ENDSE LECT BNDFUNC ONEVENT dL EVBLEMSG CALL HandlerBleMsg IF BleAdvertStart 0 addrS 25 60000 0 0 THEN PRINT mAGveris Started n PRINT nMake a connection co che BLEOOQOY BLSE PRINT n nacdvercisement not successful ENDILE WALTEVENT Expected Output Unsuccessful Negotiation Americas 1 800 492 2320 Option 2 66 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Adverts Started Make a connection to the BL600 New Connection 1352 Conn Interval T500 Conn Supervision Timeout 7000000 Conn Slave Latency 0 Request new parameters Conn Parm Negotiation FAILED Disconnected L332 Exoected Output Successful Negotiation Adverts Started Make a connection to the BL600
122. andler for the EVATTRNOTIFY event message On EVATTRNOTIRY event BleGattcNotifyRead to actually get the data Process the data Enable notifications and or indications via CCCD descriptors INTEGER a result code Reruns Typical value 0x0000 indicates a successful operation Arguments byRef connHndl AS INTEGER connHndl On exit this will be the connection handle of the gatt server that sent the notification or indication byRef attrHndl AS INTEGER attrHndl On exit this will be the handle of the characteristic value attribute in the notification or indication byRef atirDataS AS STRING attrDataS On exit this will be the data of the characteristic value attribute in the notification or indication It is always from offset O of the source attribute byRef discardedCount AS INTEGER On exit this should contain 0 and it signifies the total number of notifications or indications that got discared because the ring buffer in the gatt client discardedCount manager was full If non zero values are encountered it is recommended that the ring buffer size be increased by using BleGattcClose when the gatt client was opened using BleGattcOpen Interactive Ko Command Example BleGattcNotifyRead sb See in BL600CodeSnippets zip Va i eevee Cesare Usui SleGeiccoWolvormityiNeec Sule suawelsecl sum Ooeidillicia Sele Americas 1 800 492 2320 Option 2 153 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2
123. andom address will be 02412233445566 Upper 2 bits of MAC portion 01 and a non resolvable address will be 031 12233445566 Upper 2 bits of MAC portion 00 Note The MAC address portion in smartBASIC is always in big endian format If you sniff on air packets the same six packets appear little endian format hence reverse order and you will NOT see seven bytes but a bit in the packet somewhere which specifies it to be public or random Americas 1 800 492 2320 Option 2 30 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Events and Messages EVBLE_ADV_TIMEOUT This event is thrown when adverts that are started using BleAdvertStart time out Usage Is as per the example below J Bemol 3 nile inch e oe So See cin ELCO O e Sinise Ss o DIM peerAddrs fj handler to service an advert timeout FUNCTION HndlrBleAdvTimOut PRINT nAdvert stopped via timeout PogMsg sm could use SystemStateSet 0 to switch off Switch off the system requires a power cycle to recover re SystemStateSet 0 ENDFUNC 0 Sec echraicrs Ji Gie Teleheoverestare 0 LOO S000 IF BleAdvertStart 0 peerAddr 100 2000 0 0 THEN PRINT nAdvertisement Successful BLSE PRINT n nAdver
124. annot be a string constant e g the cat but must be a string variable If you must use a const string first save it to a temp string variable and then pass it to the function Use the iOS BL600 Serial app and connect to your BL600 to test this sample app Example BleVSpWrite sb See in BL600CodeSnippets zip DEM 2S te Fo eclaiosS aclelieS Imac eins nandler when VSP tx buffer is empty FUNCTION HandlerVSpTxEmpty AS INTEGER cnt cnttl IF cnt lt 2 THEN txS then this is sent re BleVSpWrite tx S ENDIF ENDFUNC 0 ee BlevspOpen 123 128 0 nnd re BleScanRptInit scRpt ro BileAdyRorAddUumd 23 sekors madi adRpt s rc BleAdvRptsCommit adRpt scRpts addrs bc BleAdvercStart O addr o 20 300000 0 PRINT nDevice name is BleGetDeviceNames cnt 1 tx S send this cata ands re BleVSpWrite tx ONEVENT EVVSPTXEMPTY CALL HandlerVSplxEmpry WAL TEVENT PRINIEST OE EE a Exoected Output Device name is LAIRD BL6O0O0 EXICiINGs ez BLEVSPWRITE is a extension subroutine BleVSpRead FUNCTION Americas 1 800 492 2320 Option 2 194 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This function is used to read the content of the receive buffer and copy it to the string variable supplied BLEVSPREAD strMsg nMaxRead INTEGER Oto N The total
125. are treated as 16 bit integers This is reflected in smartBASIC applications so that INTEGER variables are used to manipulate those values instead of STRINGS Americas 1 800 492 2320 Option 2 156 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleEncode8 FUNCTION This function overwrites a single byte in a string at a specified offset If the string is not long enough then it will be extended with the new extended block uninitialized and then the byte specified is overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODES atirS nData nindex INTEGER a result code Benne Typical value 0x0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This argument is the string that will be written to an attribute byVal nData AS INTEGER nData The least significant byte of this integer is saved The rest is ignored byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data nindex is written to If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended
126. art BASIC User Manual in the EVCHARDESC event message byVal nDescHandle AS INTEGER aDeschHandie This is an index into an opaque array of descriptor handles inside the charHandle and will have been supplied as the second parameter in the EVCHARDESC event message byVal nOffset AS INTEGER nOffset This is the offset into the descriptor attribute from which the data shoud be read and copied into attr byVal nLength AS INTEGER nLength This is the number of bytes to read from the descriptor attribute trom offset nOffset and copied into attr byRef nDescUuidHandle AS INTEGER nDescUuidHandle On exit this will be updated with the uuid handle of the descriptor that got updated byRef attrS AS STRING attrS On exit this string variable contains the new value from the characteristic descriptor Interactive No Command Example BleCharDescRead sb See in BL600CodeSnippets zip DIM de communal nM inans SUB Onsrackue DIMM nS Ve attr eror c nets acdics rc BleSvcCommit 1 BleHandleUuidl6 Ox18FF hSvc 7 Add one or more characteristics rc BleCharNew 0x0a BLleHandleUuidl16 Ox2AFF BleAttrMetadata 1 1 20 1 rc 0 0 Add a user description DIM Ss sS You can change this rc BleCharDescAdd 0x2999 sS BleAttrMetadata 1 1 20 1 rc Commit Characteristic atiro 00 s no niria alert re BleCharCommit hSvc attrs hMyChar rc BleScanRptInit scRpt Add 1 char handle to scan report PeP Ter d EROA Uun ae
127. as dropped below that specified in the most recent call of SetPwrSupplyThreshMv i and msgCtx is the current voltage in milliVolts The connection is no longer encrypted and msgCix is the conn handle The device name characteristic in the GAP service of the local gatt table has been written by the remote gatt client Note Message ID 13 Is reserved for future use An example of how these messages can be used is as follows Example EvBleMsg sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 32 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM aders s addrg W DIMES FUNCTION HndlrBleMseg BYVAL mMsqid AS INTEGER EIV An OA INTEGER SECME OEA CASE 0 PRINT nbBle Connection Y nCtx rc BleAuthenticate nCtx CASE 1 PRINT nDisconnected T nOr n CASE 18 PRINESTAnC Onn eC ton nea aS NOW encrypted CASE 16 PRINT nConnected to a bonded master CASE 17 PRINT nA new pairing has replaced the old key CASE ELS PRINT nUnknown Ble Msg ENDS ELEC ENDEUNC FUNCTION HndlrBlrAdvTimOut PRINT nAdvert stopped via timeout PRINT Anei cing 4 2 ENDFUNC 0 FUNCTION Bend Presse PRINT iE Sb hoes ENDEUNC 0 PRINT proce chume leo Osc PRINT GpvoBindE vent 0 16 0 ONEVENT EVBLEMSG CALL HndlrBleMsg OMEN STINE TAVIS Ea NID APIO a a E r A mO ONEVENT EVGPIOCHANO C
128. at a specified offset treated as a bit array into a destination integer object treated as a bit array of fixed size of 32 This implies a maximum of 32 bits can be read This function will not fail as the output bit array can take truncated bit blocks BLEDECODEBITS attrS nSrcldx dstBitArr nDstidx nMaxgBits INTEGER the number of bits extracted from the attribute string Can be less than Returns the size expected if the nSrcildx parameter is positioned towards the end of the source string or if nDstldx will not allow more to be copied Arguments byRef attrS AS STRING attrS This references the attribute string from which to read treated as a bit array Henc a string of 10 bytes will be an array of 80 bits byVal nSrcldx AS INTEGER MEIGA This is the zero based bit index into the string attr from which data is read E g Americas 1 800 492 2320 Option 2 180 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual the third bit in the second byte is index number 10 byRef dstBitArr AS INTEGER dstBitArr This argument references an integer treated as an array of 32 bits into which data is copied Only the written bits are modified byVal nDstldx AS INTEGER nDstldx This is the zero based bit index into the bit array dstBitArr where the data is written to byVal nMaxBits AS INTEGER This argument specifies the maximum
129. att Svc UUID Handle TE Ble Se ey ee Niery ISIN SIV INCI IIR INWAR a a a Sie EHEN PRINT n nBattery Service attribute written to GATT table PRINT nUUID Handle value NUuidBartt PRINT nService Attribute Handle value hBatSvc Blok PRINT nService Commit Failed PNDTE Americas 1 800 492 2320 Option 2 87 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output Health Thermometer Service attribute written to GATT table UUID Handle value 33482743 Service Attribute Handle value 16 Battery Service attribute written to GATT table UUID Handle value 33482737 Service Attribute Handle value 17 BLESERVICENEW is an extension function BleServiceCommit This function in the BL600 is a dummy function and does not do anything However for portability to other Laird 4 0 compatible modules always invoke this function after the last descriptor of the last characteristic of a service has been committed to the gatt server BLESERVICECOMMIT hService INTEGER a result code SaUn Typical value 0x0000 indicates a successful operation Arguments hService byVal hService AS INTEGER This handle will have been returned from BleServiceNew BleSvcAddincludeSvc FUNCTION Note This function is currently not available for use on this module This function is used to add a reference to a service within
130. attribute may take many 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals BleGattcRead is used to trigger the procedure and BleGattcReadData is used to read the data from the underlying cache when the EVATTRREAD event message is received with a success status EVATTRREAD event message This event message WILL be thrown if BleGattcRead returns a success The message contains 3 INTEGER parameters Connection Handle Handle of the Attribute Gatt status of the read operation Gatt status of the read operation is one of the following values where O implies the read was successfully expedited and the data can be obtained by calling BlePubGattClientReadDatd OxO0000 Success 0x0001 Unknown or not applicable status 0x0100 ATT Error Invalid Error Code 0x0101 ATT Error Invalid Attribute Handle Ox0102 ATT Error Read not permitted 0x0103 ATT Error Write not permitted Ox0104 ATT Error Used in ATT as Invalid PDU Ox0105 ATT Error Authenticated link required Ox0106 ATT Error Used in ATT as Request Not Supported Ox0107 ATT Error Offset specified was past the end of the attribute Ox0108 ATT Error Used in ATT as Insufficient Authorisation Ox0109 ATT Error Used in ATT as Prepare Queue Full OxO10A ATT Error Used in ATT as Attribute not found 0x010B ATT Error Attribute cannot be read or wri
131. ault VSP service using the parameters specified The service s UUID Is 569a1101 b87 490c 92cbh llbabea5l1l67c By default Modem In and ModemOut characteristics are registered in the GATT table with the Rx and Tx FIFO characteristics To suppress Modem characteristics in the GATT table set bit 1 in the nFlags parameter value 2 If the virtual serial port is already open this function fails BLEVSPOPEN txbuflen rxbuflen nFlags svcUuid INTEGER indicating the success of command QO Opened successfully Ox604D Already open Returns Ox604E Invalid Buffer Size Cannot register Service in Gatt Table while BLE Ox604C connected E tion Local Stack Frame Underflow ASEPI Local Stack Frame Overflow Arguments byVal txbuflen AS INTEGER txbuflen Set the transmit ring buffer size to this value If set to O a default value is used by th underlying driver and use BleVsplnto 2 to determine the size byVal rxbuflen AS INTEGER rxbuflen Set the receive ring buffer size to this value If set to O a default value is used by the underlying driver and use BleVsplnfo 1 to determine the size byVal nFlags AS INTEGER This is a bit mask to Customise the driver as follows Set to 1 to try for reliable data transfer This uses INDICATE messages If allowed and if there is a choice Some services only allow NOTIFY and in that case if set to 1 it is ignored Bit 1 31 Reserved for future use Set to 0 byRef svcUuid AS INTEGER On exit
132. bit is NOT specified for the nCharProps argument to the BleCharNew function BLECHARDESCUSERDESC userDescS mdUser INTEGER a result code ESINE Typical value 0x0000 indicates a successful operation Arguments byRef userDescS AS STRING userDesc The user description string to initiliase the Descriptor with If the length of the string exceeds the maximum length of an attribute then this function will abort with an error result code byVal mdUser AS INTEGER This is a mandatory metadata that defines the properties of the User Description mdUser Descriptor attribute created in the Characteristic and will have been pre created using the help of BleAttrMetadata If the write rights are set to 1 or greater the attribute will be marked as writable and the client will be able to provide a user description that overwrites the one provided in this call Interactive Nig Command Example BleCharDescUserDesc sb See in BL600CodeSnippets zip DIM ro Mevascuccess Usir Deseo UsrDesco A description DIM charUuid charUuid BleHandleUuidlo 1 DIM charMet charMet BleAttrMetaData 1 1 20 0 metaSuccess DIM mdUsrDsc mdUsrDsc BleAttrMetaData 1 1 20 0 metaSuccess DiN mi cede md ead E Pleat r Metadata a W720 te C OCD metadata LOr Char initialise char write read enabled accept signed writes indicatable rc BleCharNew 0x4B charUuid charMet 0 mdSccd rc BleCharDescUserDesc usrDesc mdUsrDsc IF rc 0 THEN PRINT
133. bject which defines the permissions for the Broadcastable Yes characteristic SCCD attribute Start the definition of a new characteristic which will be later commited to the GA table in a single transaction Create a metadata object which User Desc defines the permissions for the Descriptor User Desc Descriptor BleAttrMetadata Add parameters for creation of User Desc Descriptor BleCharDescUserDesc Sraction Forma V s Add parameters for creation of Descrini r Presentation Format Descriptor p a BleCharDescPrstnFrmt Add parameters for creation of other Descriptor BleCharDescAdd Create a metadata object which defines the permissions for the other Descriptor BleAttrMetadata Add other Descriptor Commit the Characteristic to the Gatt ServerTable in single transaction BleCharCommit mt Save the handle that is returned as it is used to interact with the More characteristic haracteristics More Services 76 Laird Technologies smart BASIC User Manual Example ServicesAndCharacteristics sb See in BL600CodeSnippets zip Register two Services in the GATT Table Service 1 with 2 Characteristics and J Service 2 with l characteristic Thio implies a tOtal or S Characteristics co manage The characteristic 2 in Service 1 will not be readable or writable but only indicatable The characteristic 1 in Service 2 will not be readable or writable but
134. bs print nhandle nAhndl else print miPailed to read attribute Americas 1 800 492 2320 Option 2 144 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual endif endfunc 0 SSS SSS SSS SS SSS SS SSS SSS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SSS SEE Main equivalent SSS SSS SSS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SS SSS SS SS SS SS SS SS SS SS SS SS SS SS SS SS ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVATTRREAD call HandlerAttrRead FP OnStarcup 0 THEN PRINT nAdvertising and Gatt Client is open n aloha PRINT nbetlure OnStartkup ENDIF WALTEVENT USGI NA Maia peal ie a yy Expected Output Advertising and Gatt Client is open Connected so read attibute handle 3 EVATTRREAD cHndl 2960 attrHndl 3 status 00000000 Attribute read OK Data 00000000 Offset 0 Len 4 handle 3 read attibute handle 300 which does not exist EVATTRREAD cHndl 2960 attrHndl 300 status O00000101 Failed to read attribute Disconnected BMA A ou BLEGATTCREAD and BLEGATTREADDATA are extension functions BleGattcWrite FUNCTION If the handle for an attribute is Known then this function is used to write into an attribute starting at offset 0 The acknowledgement will be returned via a EVATTRWRITE event message Given that the success or fail
135. c Presentation Format descriptor If this exists it s possible for the generic client to display its value and it is safe to read this value BLECHARDESCPRSTNFRMT nFormat nExponent nUnit nNameSpace nNSdesc INTEGER a result code pen Typical value 0x0000 indicates a successful operation Arguments byVal nFormat AS INTEGER Valid range 0 to 255 The format specifies how the data in the Value attribute is structured A list of va values for this argument Is found at hitp developer bluetooth org gatt Pages Formatlypes aspx and the enumeration is described in the BI 4 0 spec section 3 3 3 5 2 At the time of writing the enumeration list is as follows OxOO RFU 0x01 boolean Ox0O2 2bit 0x03 nibble 0x04 uint8 Ox05 uintl2 Ox06 uintl 0x07 uint24 orma 0x08 uint32 0x09 uint48 OxOA uint6 4 OxOB uintl28 OxOC sint8 OxOD sintl2 OxOE sintl OxOF sint24 0x10 sint32 0x11 sint48 0x12 sint64 0x13 sintl28 0x14 float32 0x15 float64 Ox16 SFLOAT 0x17 FLOAT 0x18 duintl 0x19 utf8s OxlA utfl s Ox1B struct Ox1C OxFF RFU byVal nExponent AS INTEGER nExponent Valid range 128 to 127 This value is used with integer data types given by the enumeration in nFormat to further qualify the value so that the actual value is Americas 1 800 492 2320 Option 2 95 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual actual value Characteristic
136. c value tS ELSE PRINT nFavl d to write new characteristic value integer h rc n ENDIF ENDFUNC 0 IF OnStartup 0 THEN DIM atS re BleCharValueRead hMyChar ats PRINT nCharacteristic value attribute at nType a new valuen ELSE PRINT nFailure OnStartup ENDIF ONEVENT EVUARTRX CALL HndilrVarekx ONEVENT EVTMRO CALL HndlrTmroO WAITEVENT PRINTEN nE EIn N Expected Output Characteristic value attribute Hi Send a new value Laira New characteristic value Laird Beso sw BLECHARVALUEWRITE is an extension function BleCharValueNotify FUNCTION Americas 1 800 492 2320 Option 2 103 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual If there is BLE Connection this function writes new data into the VALUE attribute of a Characteristic so that it can be sent as a notification to the GATT client The characteristic is identified by a composite handle that was returned by the function BleCharCommit A notification does not result in an acknowledgement from the client BLECHARVALUENOTIFY charHandle attrS INTEGER a result code tl Typical value 0x0000 indicates a successful operation Arguments byVal charHandle AS INTEGER charHandle This is the handle to the characteristic whose value must be updated which was returned when BleCharCommit was called byRef attrS AS STRING
137. ch in turn will result in another EVDISCCHAR event message and typically is as follows Register a handler for the EVDISCCHAR event message On EVDISCCHAR event message If Char Value Handle 0 then scan is complete Else Process information then call BleDiscCharNext if BleDiscCharNext not OK then scan complete Americas 1 800 492 2320 Option 2 122 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Call BleDiscCharFirst information from EVDISCPRIMSVC If BleDiscCharFirst ok then Wait for EVDISCCHAR Returns Arguments nConnHandle charUvidHandle startAttrHandle endAttrHandle Interactive Command INTEGER a result code Typical value 0x0000 Indicates a successful operation and means an EVDISCCHAR event message WILL be thrown by the smarfBASIC runtime engine containing the results A non zero return value implies an EVDISCCHAR message will NOT be thrown byVal nConnHandle AS INTEGER This is the connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgid 0 and msgCtx v have been the connection handle byVal charUvidHandle AS INTEGER Set this to O if you want to scan for any characteristic in the service otherwise this value will have been generated either by BleHand
138. char value attribute from GOLESeEk v Orset rc BleCharValueRead hMyChar s PRINT nNew Char Value sS ENDIF rc BleAdvertStop rc BleDisconnect conHndl BENDFUNC O J2 SS 552555525 SSS S SSS SSS 5S Se SSS S5 5555555 55 SSS SSS 2555 SSS SSS SS 5 SS J Ger nie conmmMectiom mance e a FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtn conned ncEn ENDFUNC 1 IF OnStartup 0 THEN DIM at rc BleCharValueRead hMyChar at PRiIt WC Weise wetas ere value acctcriburces YratcS Y aConnecert tco BLE0O0 some send a new VAINEN ELSE PRINT nFailure OnStartup ENDIF Americas 1 800 492 2320 Option 2 101 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ONEVENT EVCHARVAL CALL HndlrChar ONEVENT EVBLEMSG CALL HndlrBleMsg WALTEVENT PRITA T all Shp cai Cain ngaa tl Expected Output Characteristic value attribute Hi Connect to BL600 and send a new value New characteristic value Laird ERL INO 4a BLECHARVALUEREAD is an extension function BleCharValueWrite Note For firmware versions prior to 1 4 X Y the module must be in a connection for this function to work FUNCTION This function writes new data into the VALUE attribute of a Characteristic which is in turn identified by a composite handle returned by the function BleCharCommit BLECHARVALUEWRITE charHandle atirS
139. cks HP10 OHH UK Tel 44 0 1628 858 940 Fax 44 0 1628 528 382 Americas 1 800 492 2320 Option 2 2 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual REVISION HISTORY 1 0 1 Feb 2013 Initial Release 1 1 50 0r3 3 Apr 2013 Production Release 1 1 51 0 15 Apr 2013 Incorporate review comments for JG 1 1 51 5 24 Apr 2013 Engineering release 1 1 53 10 8 May 2013 Engineering release with custom service capability 1 1 53 20 12 Jun 2013 Engineering release with Virtual Serial Service capability 1 2 54 0 29 Jun 2013 Production Release L299 26 Jul 2013 Engineering release with PWM amp FREQUENCY output 1 2 55 5 8 Aug 2013 Engineering release with VSP Uart Bridging 1 2 55 8 12 Aug 2013 Engineering release with AI CFG command 1 2 55 12 29 Aug 2013 Engineering release with sysinfo 1 3 57 0 12 Sep 2013 Engineering release with UartCloseEx 1 4 59 0 19 Dec 2013 Engineering release v1 4 59 0 1 5 62 0 4 Jan 2014 Production release v1 5 62 0 Softdevice 6 0 0 1 5 65 0 24 Feb 2014 Engineering release v1 5 65 0 Softdevice 6 0 0 1 5 66 0 28 Mar 2014 Production release v1 5 66 0 Softdevice 6 0 0 1 5 70 0 27 Apr 2014 Production releae v1 5 70 0 Soffdevice 6 0 0 1 5 70 0 r1 28 Apr 2014 Added the VSP flowchart 1 5 70 0 1r2 1 May 2014 Split manuals into Core and BL600 Extension 1 5 70 0 r4 27 Aug 2014 Sync information with Core Manual 1 5 70 0 r5
140. ctet MAC address is qualified on air by a single bit which qualifies the MAC address as public or random If public the format is as defined by the IEEE organization If random it can be up to three types and this qualification is done using the upper two bits of the most significant byte of the random MAC address The exact details and format of how the specification requires this to be managed are not relevant for the purpose of how BLE functionality is exposed in this module and only how various API functions in smartBASIC expect MAC addresses to be provided is detailed here Where a MAC address is expected as a parameter or provided as a response it is always a STRING variable This variable is seven octets long where the first octet is the address type and the the other six octets comprises the usual MAC address in big endian format so that most significant octet of the address Is at offset 1 whether public or random The address type Is Public Random Static Random Private Resolvable WOW N O Randam Private Non resolvable All other values are illegal For example To specify a public address which has the MAC potion as 112233445566 the STRING variable will contain seven octets 001 12233445566 and a variable can be initialized using a constant string by escaping as follows DIM addr addr 00 11 22 33 44 55 66 Likewise a static random address will be 01C12233445566 Upper 2 bits of MAC portion 11 a resolvable r
141. ction or the write_with_no_resp command fails with a result code of 0x6803 BLE_NO_TX_BUFFERS Once the attribute data is transmitted over the air given there are no acknowledges for Notify messages the buffer is freed to be reused This event is thrown when at least one buffer has been freed and so the smarfBASIC application can handle this event to retrigger the data pump for sending data using notifies or writes_with_no_reso commands Note When sending data using Indications this event is not thrown because those messages have to be confirmed by the client which results in a EVCHARHVC message to the smarfBASIC application Likewise writes which are acknowledged also do not consume these buffers Example EvNotifyBuf sb See in BL600CodeSnippets zip DEM OM C har realer COM rine ney Enabled PUNGIIO ONS DIEM ice a ae e a a aCe An Dim ee e a ae aE RA e a aa ea E a aa por tela AC ommi eve with handle hove rc BleServiceNew 1 BleHandleUuidl6 0x18EE hSvc rc BleSvcCommit 1 BleHandleUuidl 0x18EE hSvc initialise char write read enabled accept signed writes notifiable rc BleCharNew 0x12 BleHandleUuidl6 1 BleAttrMetaData 1 0 20 0 rc mdCccd 0 commit char initialised above with initial value hi to service hMyChar rc BleCharCommit hSvc attrs hMyChar commit changes to service rc BleServiceCommit hSvc rc BleScanRptInit scRpt Add 1 service handle to scan report Pe Pike Ndaj Ror MaclimuciiG Se
142. dRpES 2 07 10 IF re 0 THEN rc EleScanRptInit cOCRPLS ENDIF IE e 0 THEN re BleAdvRoesCommit adRpts SCRpES ENDIF LE ve 0 TREN re EB leAdgvertStart 07addr gt 50 0 0 ENDIF lopen the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDERUN C sae SUB CloseConnecrions rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx DIM uu Undo uRndC conmo nC TX IF nMsgID 1 THEN PRINT n n Disconnected EXEEPUNC 0 ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for an instance of char uHndS BleHandleUuidl6 OxDEAD COU NIN 2 SAS ele J The O AEE CID IS ay eile ONC uus StrDehexizes uus unde BleHandlevuidl28 uus sIdx 2 eld ley valbaendile witli bet s2 Be BleGarrchindCher Cconknel uineis sre umel erc IF rc 0 THEN BleDiscCharFirst will exit with 0 when operation is complete WALILTEVENT ENDIF sIdx 1 cldx 3 does not exist re BleGarceririndChar Comme ubinds s Te umne erd IF rc 0 THEN Americas 1 800 492 2320 Option 2 135 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleDiscCharFirst will exit with 0 when operation is complete WALTEVENT ENDIF CloseConnections ENDIF ENDFUNC 1 fonction wamckechmm
143. dRpts 2 0 0 encode service UUID into service data string re Blekncodel6 svcDtas OxleEhE 0 j j aoeend Characteristic value svcDtaS svcDtaS chVals append service data to advert report rc BleAdvRptAppendAD adRpt 0x16 svcDtas commit new advert report and empty scan report rc BleAdvRptsCommit adRpt scRpts EN DEUN ey Ee FUNCTION ResetAdvReport Cinta Oro se h ps initialise new advert report re BleAdvRpEinie adRpto 2 0 20 commit new advert report and empty scan report rc BleAdvRptsCommit adRpt scRpts EMP RUM sige ee Ble event handler ee FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected from client dim addrs Americas 1 800 492 2320 Option 2 40 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleAdvertstaret 0 acddrs 20 300000 0 IF rc 0 THEN PRINT nYou should now see the new characteristic value in the advertisment data ENDIF ELSEIF nMsgID 0 THEN PRINT n Connected to client EN Dir ENDEUNC FUNCTION HndlrUartRx ENDEUNE 0 PUNCTION HndirCharscca BYVAL charHamdile BYVAL nval As INTEGER DIM values IF charHandle hMyChar THEN IF nVal amp 0x01 THEN PRINT nBroadcasts have been enabled by client IF PrepAdvReport 0 THEN rc BleDisconnect conHndl PRINT Wibasconnectancd BLSE
144. dehan cHndl eProp nvaik ae Uuid a gt Inre qe i Print DEVE NDeHAR Prine chodl chin Prit 1 Peeps ee nop print valine nval rra Ley cUurd ans Ua IF hVal 0 THEN PRINS bad NOT rind Ene echarectericr re ELSE PRINT nFound the characteristic at handle hVal PRINT enove ldx sid Cher Tax colds ENDIF endfunc 0 fseessosesaasse ae sss esas sss ess SS Main equivalent ff pases sa ase aa ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVFINDCHAR call HandlerFindChar Register base uuids with the underlying stack otherwise the services with the 128bit uuid s will be delivered with a uvid handle FFO0O0000 UNKNOWN melo WI 3344556677 coll AABeCCDDEBEEOO uuids StrDehexizes uuids uHndl BleHandleUuidl128 uuids CLS 1122DEAD5566779899DABBCCDDBEEF OO uuid StrDehexizes uuid uHndl BleHandleUuidl128 uuids IF OnStartup 0 THEN PRINT nAdvertising and Gatt Client is open n ELSE PRINT Meat ure Ono Lareu e ENDIF WALTEVENT PETTO E auinvopy ey Expected Output Americas 1 800 492 2320 Option 2 136 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Connected so scan remote Gatt Table for an instance of char EVFINDCHAR cHndl 866 Props 2 valHndl 32 ISvcUuid 0 Found the characteristic at handle 32 Svc Idx 2 Char Idx 1 EVFINDCHAR cHndl 866 Props 0 valHndl 0 ISvcUuid 0 Did NOT find th
145. dle rc BleCharValueRead chrHandle attr read 4 signed bytes from index 2 rc BleDecode32 attrS vl1 2 PRINT Andata in Hex Ox INTEGER H yl PRINT ndarta in Decimal eel ah read 4 signed bytes from index 6 rc BleDecode32 attrS vl1 6 PRINT Andata an Hex Ox INTCR Hyl PRINT ndetas in Decimal g syle in Exoected Output Hex 0x85040302 Decimal 2063334654 Hex 0x89888786 Decimal 1987541114 BLEDECODE32 Is an extension function BleDecodeFLOAT FUNCTION This function reads four bytes in a string at a specified offset into a couple of 32 bit integer variables The decoding results in two variables the 24 bit signed mantissa and the 8 bit signed exponent If the offset points beyond the end of the string this function fails BLEDECODEFLOAT attrS nMatissa nExponent nindex INTEGER the number of bytes extracted from the attribute string Can be less Returns than the size expected if the nlndex parameter is positioned towards the end of the string Americas 1 800 492 2320 Option 2 175 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments attrs byRef atirS AS STRING This references the attribute string from which the function reads byRef nMantissa AS INTEGER This is updated with the 24 bit mantissa from the 4 byte object If nExponent is O you MUST check
146. dleUuid16 1 BleAttrMetaData 1 1 20 0 rc 0 0 commit Char initrali zced above with initial value hi to servic hove rc BleCharCommit hSvc attrs hMyChar commit changes to service rc BleServiceCommit hSvc rc BleScanRptInit scRpt Add 1 service handle to scan report Lee Plenn Ppr Addu oe Tea aa ik il i Se i commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addrS 20 300000 0 EN DEUNCG ce SUB CloseConnections rc BleDisconnect conHndl Americas 1 800 492 2320 Option 2 35 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleAdvertStop ENDSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected from client EXLITEFUNG Q ELSEIF nMsgID 0 THEN PRINT n Connected to client ENDIKA ENDFUNC 1 JR New char value handler PUNCTTION HandlerChnarVvali e VAL charhandie BYVAL OFricer ANAS BUU ss IF charHandle hMyChar THEN PRINT n len byte s have been written to char value attribute from OERESEE Orset rc BleCharValueRead hMyChar s PRINT nNew Char Value ss BNDIE CloseConnections ENDE we ONEVENT EVCHARVAL CALL HandlerCharVal ONEVENT EVBLEMSG CALL HndlrBleMsg IF OnStartup 0 THEN re BleCharValueRead hMyChar ats PRINT mlne Characteristic s va
147. e and indicatable characteristics At the time of writing this user manual the default minimum size is 64 unless a bigger one is desired and in that case the input parameter to this function specifies that size A maximum of 2048 bytes is allowed but that can result in unreliable operation as the smartBASIC runtime engine will be starved of memory very quickly Americas 1 800 492 2320 Option 2 114 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Use SYSINFO 2019 to obtain the actual default size and SYSINFO 2020 to obtain the maximum allowed The same information can be obtained in interactive mode using the commands AT 2019 and 2020 respectively Note that when the ring buffer for the notifiable and indicatable characteristics is full Then any new messages will get discarded and depending on the flags parameter the indicates will or will not get confirmed This function is safe to call when the gatt client manager is already open however in that case the parameters are ignored and existing values are retained and any existing gattc client operations are not interrupted It is recommended that this function NOT be called when in a connection BLEGATICOPEN nNotifyBufLen nFlags INTEGER a result code Bein Typical value 0x0000 indicates a successful operation Arguments byVal nNotifyBufLen AS INTEGER nNotifyBufLe
148. e attribute objects must be precreated After they are all created successfully they are committed to the GATT table in a single atomic transaction This function is the first function that SHALL be called to start the process of creating those multiple attribute objects It is used to select the Characteristic properties which are distinct and different from attribute properties the UUID to be allocated for it and then up to three metadata objects for the value attribute and CCCD SCCD Descriptors respectively BLECHARNEW nCharProps nUvidHandle mdVal mdCccd mdSccd INTEGER a result code Seur Typical value 0x0000 indicates a successful operation Arguments byVal nCharProps AS INTEGER This variable contains a bit mask to specify the following high level properties for tr Characteristic that will get added to the GATT table Broadcast capable Sccd Descriptor has to be present Can be read by the client nCharProps Can be written by the client without response Can be written Can be Notifiable Cccd Descriptor has to be present Can be Indicatable Cccd Descriptor has to be present Can accept signed writes 7 Reliable writes byVal nUvidHandle AS INTEGER This soecifies the UUID that will be allocated to the Characteristic either 16 or nUvidHandle 128 bits This variable is a handle pre created using one of the following functions BleHandleUuid16 BleHandleUvid128 BleHandleUuidSibling HWM HB WIN FR oO
149. e characteristic Disconnected EXICING c BLEGATTCFINDCHAR is an extension function BleGattcFindDesc FUNCTION This function facilitates a quick and efficient way of locating the details of a descriptor if the UUID is known along with the UUID of the service and the UUID of the characteristic containing it and the results are delivered in a EVFINDDESC event message If the Gatt server table has multiple instances of the same service characteristic descriptor combination then this function works because in addition to the UUID handles to be searched for it also accepts instance parameters which are indexed from 0 which means the 2 4 instance of a descriptor in the 4th instance of a characteristic with the same UUID in the 3 9 instance of a service with the same UUID is located with index values 1 3 and 2 respectively Given that the results are returned in an event message a handler must be registered for the EVFINDDESC event Depending on the size of the remote GATT server table and the connection interval the search of the characteristic may take many 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals Note Itis not currently possible to scan for characteristics in included services This will be a future enhancement EVFINDDESC event message This event message WILL be thrown if BleGat
150. e descriptor value BNE JELDA PRINT YAnThis is for some other Characteristic ENDIF ENDEUNC 1 ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT EVCHARDESC CALL BPndlrCharbDesc ONEVENT EVUARTRX CALL HndlrUartRx PRINT nOther Descriptor Value OnStartup PRINT nWrite a new value n Press any key to exit n WALTEVENT CloseConnections ore JUNE HE a ENO Expected Output Other Descriptor Value my char desc Write a new value Press any key to exit Connected to client New value for desriptor 0 with uuid FEO12901 is hello EVVSPRX This event is thrown when the Virtual Serial Port service is open and data has arrived from the peer EVVSPTXEMPTY This event is thrown when the Virtual Serial Port service is open and the last block of data in the transmit buffer is sent via a notify or indicate See VSP Virtual Serial Port Events EVNOTIFYBUF When in a connection and attribute data is sent to the GATT Client using a notify procedure for example using the function BleCharValueNotity or when a Write_with_no_response is sent by the Gatt Client to a remote server they are stored in temporary buffers in the underlying stack Americas 1 800 492 2320 Option 2 44 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual There is finite number of these temporary buffers and if they are exhausted the notify fun
151. e size expected if the nlndex parameter is positioned towards the end of the string Arguments attrs byRef attrS AS STRING This references the attribute string from which the function reads byRef nData AS INTEGER nData This references an integer to be updated with the 2 byte data from attr without sign extension byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the nindex string attr is not long enough to accommodate the index plus the number of bytes to read this function falls Interactive Ries Command Example BleDecodeU16 sb See in BL600CodeSnippets zip DIM GhridanciLle vals Chicane esac DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM atte e aee O00 OlW2 Os 0485 eo 87 e235 DIM Wille 3 uuric 0x1853 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuid1l6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read 2 unsigned bytes from index 2 rc BleDecodeUl16 attr S vi 2 PRINT ndata an Hex OT INTEGER Hv PRINT Y ndarta in Decimal Y yil Y n read 2 unsigned bytes from index 6 rc BleDecodeU16 attr vl1 6 Americas 1 800 492 2320 Option 2 171 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT ncara
152. eAdvertotart O0 adars 20 3000070 Exoected Output 00000 BLEADVRPTADDUUID128 is an extension function BleAdvRptAppendAD FUNCTION Americas 1 800 492 2320 Option 2 58 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This function adds an arbitrary AD Advertising record field to the advert report An AD element consists of a LEN TAG DATA construct where TAG can be any value from 0 to 255 and DATA is a sequence of octets BLEADVRPTAPPENDAD advRpt nTag stDataS Relo INTEGER a result code Typical value 0x0000 indicates a successful operation Arguments byRef AdvRpt AS STRING The advert report onto which the AD record is to be appended TAG field for the record Valid range O to FF byRef stDataS AS STRING stDataS This is an octet string which can be 0 bytes long The maximum length is governed by the space available in AdvRpt a maximum of 31 bytes long AdvRpt nTag Interactive No Command Example BleAdvRptAppendAD sb See in BL600CodeSnippets zip DIM scnRpt ad ads 0L 02N 0302 PRINT BleScanRptiInit scnRpts IF BleAdvRptAppendAD scnRpt 0x31 ad 0 THEN 6 bytes will be used up in the ReCOLE PRINT nAD with data ad was appended to the advert report ENDIF Expected Output 0 AD with data 01 02 03 04 was appended to the advert report BLEADVRPTAPPENDAD i
153. eFileSystem sb See in BL600CodeSnippets zip DIM re re EraseFileSystem 1234 IF rc 0 THEN PRINT nFailed to erase file system because incorrect parameter ENDIF 77 laos a OT aS how re EraseFileSystem 1 IF rc 0 THEN PRINT nFailed to erase file system because SIO7 is low ENDIF Expected Output Failed to erase file system because incorrect parameter Failed to erase file system because SIO7 is low 00 ERASEFILESYSTEM is an extension function Input Output Interface Routines I O and interface commands allow access to the physical interface pins and ports of the smart BASIC modules Most of these commands are applicable to the range of modules However some are dependent on the actual I O availability of each module GPIO Events Here n is from 0 to N where N is platform dependent and an event is generated when a preconfigured digital input transition occurs The number of digital inputs that can auto generate is hardware dependent For the EVGPIOCHANn BL600 module N can be 0 1 2 or 3 Use GpioBindEvent to generate these events See example for GpioBindEvent Americas 1 800 492 2320 Option 2 19 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Here n is from 0 to N where N is platform dependent and an event is generated when a preconfigured digital input transition occurs The number of
154. ecial case of the string being exactly 1 character long and containing the system ID is created from the MAC address if and only if an IEEE public address is set If the address is the random static variety this characteristic is omitted byVal regDataListS AS STRING regDataListS The device s regulatory certification data list as defined in the specification It can be set as an empty string to omit submission byVal pnpldS AS STRING The device s plug and play ID as defined in the specification Can be set empty to omit submission Otherwise it shall be exactly 7 octets long where pnplds Byte 0 Vendor ld Source Byte 1 2 Vendor Id Byte 1 is LSB Byte 3 4 Product Id Byte 3 Is LSB Byte 5 6 Product Version Byte 5 Is LSB Americas 1 800 492 2320 Option 2 82 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive No Command Example BleSvcRegDeviInfo sb See in BL600CodeSnippets zip DIM rco manimae mel Nimo Sr INum gt hiwkevop se wRezo oyvslde regDtaLst ome Lele manfNmeS Laird Technologies mdlNum BL600 srlNum empty to omit submission hwRevs 1 0 swRevs 1 0 Syoldoe a empty to omit submission vegbe Lo ale J jemory EO Om Submission pnold r 7 eEMoOEy CO OMIE submTes on rc BleSvcRegDevinfo manfNme mdlNumS srlNumS hwRevs swRevS syslds r
155. eclared above PPINT gud cine dbigloi ee yee Expected Output Device name is LAIRD BL600 Rx buffer flushed Rx buffer flushed CALCI Nags BLEVSPFLUSH is an extension subroutine 6 OTHER EXTENSION BUILT IN ROUTINES This chapter describes non BLE related extension routines that are not part of the core smart BASIC language System Configuration Routines SystemStateSet FUNCTION This function is used to alter the power state of the module as per the input parameter SYSTEMSTATESET nNewState Returns INTEGER a result code Americas 1 800 492 2320 Option 2 200 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The typical value is Ox0000 indicating a successful operation Arguments byVal nNewState AS INTEGER nNewState New state of the module as follows O System OFF Deep Sleep Mode Interactive Command nO Note You may also enter this state when UART Is open and a BREAK condition is asserted Deasserting BREAK makes the module resume through reset i e power cycle Example SystemStateSet sb See in Firmware Zip file Put the module into deep sleep PRINT n SystemStateSet 0 SYSTEMSTATESET is an extension function Miscellaneous Routines ReadPwrSupplyMv FUNCTION This function is used to read the power supply voltage and the value will be returned in millivolts READPWR
156. ed 2 while pairing desired 10 while pairing desired 25 while pairing desired 45 while pairing desired 1000 BLETXPOWERSET is an extension function BleConfigDcDc SUBROUTINE This routine is used to configure the DC to DC converter to one of 3 states OFF ON or AUTOMATIC Americas 1 800 492 2320 Option 2 49 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note Until a future revision when the chipset vendor has fixed a hardware issue at the silicon level this function will not function as stated and any nNewsState value will be interoreted as OFF BLECONFIGDCDC nNewState Returns None Arguments byVal nNewsState AS INTEGER Configure the internal DC to DC converter as follows Newsi O Off nNewState 2 Auto All other On values Interactive No Command Ble onigbo Set for automatic operation BLECONFIGDCDC Is an extension function Advertising Functions This section describes all advertising related routines An advertisement consists of the following A packet of information with a header identifying it as one of four types An optional payload that consists of multiple advertising records referred to as AD in the rest of this manual Each AD record consists of up to three fields Field 1 One octet in length and contains the number of octets that follow it that belong
157. egDtaLst pnplds IP lre THEN PRINT nsSuccess ELSE PRINT neotled 0x INTEGER He JEND IL IE Expected Output BLESVCREGDEVINFO is an extension function BleHandleUuid16 FUNCTION This function takes an integer in the range 0 to 65535 and converts it into a 32 bit integer handle that associates the integer as an offset into the Bluetooth SIG 128 bit 1 byte base UUID which is used for all adopted services characteristics and descriptors If the input value is not in the valid range then an invalid handle 0 is returned The returned handle shall be treated by the developer as an opaque entity and no further logic shall be based on the bit content apart from all O s which represents an invalid UUID handle BLEHANDLEUUID16 nUuid16 INTEGER a nonzero handle shorthand for the UUID Zero is an invalid UUID Returns nande Arguments byVal nUvid16 AS INTEGER nUvid16 nUviId16 is first bitwise ANDed with OxFFFF and the result will be treated as an offset into the Bluetooth SIG 128 bit base VUID Interactive No Command Example BleHandleUuidl6 sb See in BL600CodeSnippets zip DIM uuid Americas 1 800 492 2320 Option 2 83 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM RNUUITAHRS uuid 0x180D this is UUID for Heart Rate Service hUuidHRS BleHandleUuidl16 uuid IF hUuidHRS THEN P
158. el UwTerminal v1 70 command ATZ the CTS indicator will momenterally change from green to red then back to green CTs DSR DCOM RI RTS DTA RESET is a core subroutine ERASEFILESYSTEM FUNCTION This function is used to erase the flash file system which contains the application that invoked this function if and only if the SIO7 input pin is held high Given that SIO7 is high after erasing the file system the module resets and reboots into command mode with the virtual serial port service enabled the module advertises for a few seconds See the virtual serial port service section for more details This facility allows the current autorun application to be replaced with a new one WARNING If this function is called from within SautorunS and the SIO7 input is high then it will get erased and a fresh download of the application is required which can be facilitated over the air ERASEFILESYSTEM nArg Americas 1 800 492 2320 Option 2 18 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Returns INTEGER Indicates success of command O Successful erasure The module reboots lt gt 0 Failure Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments nArg byVal nArg AS INTEGER This is for future use and MUST always be set to 1 Any other value will result in a failure Example Eras
159. en If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum length of an attribute as implemented can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between and 512 BleEncodeSTRING atirS nindex1 strS nindex2 nLen INTEGER a result code Meaus Typical value 0x0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This argument is the string that will be written to an attribute byVal nindex AS INTEGER nindex This is the zero based index into the string attr where the new fragment of data is written If the string attr is not long enough to accommodate the Americas 1 800 492 2320 Option 2 165 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails byRef strS AS STRING strS This contains the source data which is qualified by the nindex2 and nLen arguments that follow byVal nindex2 AS INTEGER nindex2 This is the zero based index into the string str from which data is copied No data is copied if this is negative or greater than the string byValnLen AS INTEGER This soecies the number of bytes from offs
160. enable characteristic value write handler OnEvent EVCHARVAL call HandlerCharVal WALTEVENT Assuming there is a connection and notify has been enabled then a value notification is expedited as follows attrS somevalue re BleCharValueNotify hCharl2 attrS Assuming there is a connection and indicate has been enabled then a value indication is expedited as follows indicate a value for characteristic 2 in gervyvice 1 This handler is called when there is a EVCHARHVC message FUNCTION HandlerCharHvc BYVAL hChar AS INTEGER AS INTEGER IF hChar hCharl2 THEN PRINT Svel Char2 indicate has been confirmed BND ENDEUNC 31 enable charcacceristic value indicacion contem handler OnEvent EVCHARHVC CALG handler Chaxhvie attrS somevalue ro BleCharValuelndicate hCharl2 attrs Americas 1 800 492 2320 Option 2 78 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The rest of this section details all the smart BASIC functions that helo create that framework Events and Messages See also Events and Messages for the messages that are thrown to the application which are related to the generic characteristics API The relevant messages are those that start with EVCHARXxx BleGapSvcinit FUNCTION This function updates the GAP service which is mandatory for all approved devices to expose with the information
161. entNum nSigNum nPolarity patois INTEGER a result code Typical value 0x0000 indicates a successful operation Arguments byVal nEventNum INTEGER nEventNum The GPIO event number in the range of 0 N which will result in the event EVGPIOCHANhn being thrown to the smart BASIC runtime engine byVal nSigNum_ INTEGER igN pe The signal number as stated in the pinout table of the module byVal nPolarity INTEGER States the transition as follows nPolarity 0 Low to high transition 1 High to low transition 2 Either a low to high or high to low transition Interactive NO Command Example GpioBindEvent sb See in Firmware Zip file Americas 1 800 492 2320 Option 2 25 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION BtnOPress PRINT nel lo BND EUNG TO PRINT GpioBindEvent 0 16 1 buEton0 ONEVENT EVGPIOCHANOD CALL BeEnOPress PRINT VaPress burccon 0 WAL TEVEN Expected Output O Press button 0 Hello GPIOBINDEVENT is a Module function GpioUnbindEvent FUNCTION eano E e e a low e a a e a oa ao When event 0 happens call BtnOPress This routine unbinds the runtime engine event from a level transition bound using GpioBindEvent GPIOUNBINDEVENT nEventNum INTEGER a result code Returns Typical value 0x0000 indicates a successful operation Argume
162. eqHz minFreq j Seu Gio pin lb bo ai ou u ang neal so ine eo aol PEIN Weep roccrmume iy 25 0 je ie Ji seew S10 pin gt to PWM out pue minFregq 500 PRINT Goroconkrge wy mmbreg 1024 ae set max pwm value resolution to 1 1024 PRINT Gpresethunc s 2 2 2 vn Americas 1 800 492 2320 Option 2 24 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT Gprosetbune 7253 nim reet sio pin 7 to Frequency output GpioWrite 18 0 set pin 1 to low GpioWrite 18 1 j see pin i to high j Set the PWM output to 25 GpioWrite 5 256 is 1024 4 oek the PREO output o 4 236 Khz GpioWrite 7 4236 Note you can generate a chirp output on sio 7 by starting a timer which expires fevery 100ms and then in the timer handler call GpioWrite 7 xx and then increment xx by a certain value Expected Output 0000 GPIOWRITE is a Module function GpioBindEvent FUNCTION This routine binds an event to a level transition on a specified special I O line configured as a digital input so that changes in the input line can invoke a handler in smart BASIC user code Note In the BL600 module using this function results in over 1 MA of Continuous Current consumption from the power supply If power is important use GpioAssignEvent instead which uses other resources to expedite an event GPIOBINDEVENT nEv
163. eration is complete WALTEVENT wus 1122334455667 8899AABBCCDDEEFEOO PRINT nm nSCanm tor service wih Custom uuid suis uus StrDehexizes uus uHndl BleHandlevuidl28 uus te BilebrseeDesecriree cOmuincdil pineal cValAbrtr Americas 1 800 492 2320 Option 2 129 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual IF rc 0 THEN HandlerDescDisc will exit with 0 when operation is complete WALTEVENT ENDIF ENDIF ENDIE CloseConnections BNDL E ENDFUNC 1 FUNCTION HandlerPrimSvc cHndl svcUuid sHndl eHndl AS INTEGER PRINT A nEVDISCPRIMSVC PRINTE Y chndil chndl PRIND svcUlsd inzegqer jh ov Uudd PRS S S E PRINT eHndl eHndl IF sHndl 0 THEN PRINT nPrimary Service Scan complete EXITFUNG 0 BLSE PRINT nGot first primary service So scan for ALL characteristics sAttr sHndl eAttr eHndl rnei BleDrsceChertirset conbhnd Oy sAbEr eke 1 ae e O UN PRINT Wine CaincecW aracherl selec failil d Dp CEO 10 ENDIF ENDIE endfunc 1 function Handler CharDisc chodil cUurid cProp hval 1SUVuid as Integer Prone S nE DISC COCHAR Orini E CANIS CATA Print chUnid integer h cUuid Prin Props O Prop print valHndl nVval print evolu ins iad IF hVal 0 THEN PRINT nCharacteristic Scan complete EXITEUNCGC Q ELSE PRINT nGot first Characteristic service a
164. ereStare 0 addrs 20 20000070 PRINT nDevice name is BleGetDeviceNameS txS nSend me some text nTo exit the app just tell me n re BleVSpWrite tx S ENDSUB Close connections so that we can run another app without problems Americas 1 800 492 2320 Option 2 195 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SUB CloseConnections DIM FE rc BleDisconnect conHnd1 rc BleAdvertStop BleVspClose ENDSUB ea 553225 55 S2 SS S533 25S 5225S S25 S22 52255252252 S S22 2S 55S 2 i VSP Rx butfer event handler J e FUNCTION HandlerVSpRx AS INTEGER DIM ro xS e9 eS exit rc BleVSpRead rx 20 PRINT nMessagqe from client rxs T user has typed exit Te Ser Pos r2 S gt 0 1s THEN EXITFUNG Q ENDIF ENDFUNC 1 PUNGCTION tHndlreBleMsa BYVAL mMsold BYVAL mex CoOnmmne i me rx IF nMsgID 1 THEN PRINT nDisconnected from client Err euUne 0 ENDIL IE ENDFUNC 1 ONEVENT EVVSPRX CALL HandlerVSpRx ONEVENT EVBLEMSG CALL HndlrBleMsg OnStarrup Calls first subroutine declared above WALTEVENT ClioseConmect rons Ge Callsescecond cubrouleume Cec bared above PRINTANE TE Anne see Expected Output Device name is LAIRD BL600 Messgae from client Whatever data you send from your device Message from client exit EMITTING e 4 BLEVSPREAD
165. eripheral may ignore This value multiplied by the connection interval will not be greater than the link supervision timeout nintervalUs nSuprToutUs nSlaveLatency Note See Note on Slave Latency Interactive Command Ne See previous example BLEGETCURCONNPARMS is an extension function Security Manager Functions This section describes routines which manage all aspects of BLE security such as saving retrieving and deleting link keys and creation of those keys using pairing and bonding procedures Events amp Messages The following security manager messages are thrown to the run time engine using the EVBLEMSG message with msgIDs as follows 9 Pairing in progress and display Passkey supplied in msgCim 10 A new bond has been successfully created Pairing in progress and authentication key requested Type of key is in msgCtx 1 msgCix is 1 for passkey_type which will be a number in the range O to 999999 and 2 for OOB key which Is a 16 byte key Americas 1 800 492 2320 Option 2 68 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual To submit a passkey use the function BLESECMNGRPASSKEY BleSecMngrPasskey FUNCTION This function submits a passkey to the underlying stack during a pairing procedure when prompted by the EVBLEMSG with msgld set to 11 See Events amp Messages BLESECMNGRPASSKEY connHandle
166. ess support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Selection of Command or Bridge Mode is done using the nAutorun input signal When nAutorun is low interactive mode is enabled When it is high and bit 8 in the config register 100 accessed by AT CFG 100 Is set bridge mode is selected the defaule value of config register 100 is Ox8107 which means by default bridge mode Is enabled if SIO7 is held high and nAutorun is high too Note If autorun file exists in the file system the bridge mode is always suppressed regardless of the state of the nAutorun input signal The operation of VSP command and bridge mode is illustrated as per the diagrams on the following page aknowledgmenis to Nicolas Mejia The main purpose of interactive mode operation is to facilitate the download of an autorun smart BASIC application This allows the module to be soldered into an end product without oreconfiguration and then the application can be downloaded over the air once the product has been pre tested It is the smart BASIC application that is downloaded over the air NOT the firmware Due to this principle reason for use in production to facilitate multiple programming stations in a locality the transmit power is limited to 12dBm It can be changed by changing the 109 config key using the command AI CFG The default operation of this virtual serial port service is dependent on one of the digital input lines being pul
167. et nilndex2 to be copied into the aren destination string It is clipped to the number of bytes left to copy after the index Interactive A Command Example BleEncodeString sb See in BL600CodeSnippets zip DIM rO Na EE toe 7 a Helles World jiweice Wor trom Hello World to the attribute at index 2 te BlehmMeodestramg akirs 2 tso gt 3 PRINE attire Expected Output 00 00Wor BLEENCODESTRING is an extension function BleEncodeBlITS FUNCTION This function overwrites some bits of a string at a specified bit offset with data from an integer which Is treated as a bit array of length 32 If the destination string is not long enough it is extended with the new extended block uninitialized Then the bits specified are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum length of an attribute as implemented can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 hence the nDstldx nBitLen cannot be greater than the max attribute length times 8 BleEncodeBITS attrS nDstldx srcBitArr nSrcldx nBitLen INTEGER a result code nen Typical value 0x0000 indicates a successful operation Arguments byRef attrS AS STRING This is the string written to an attribute It is treated as a bit array byVal nDstldx AS INTEGER nDstldx This is the zero based bit
168. ex specified A shorter string will be returned if there are not enough bytes beyond the index nMaxBytes byVal nMaxBytes AS INTEGER y This soecifies the maximum number of bytes to read from attr Interactive No Command Example BleDecodeString sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 179 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM chrHandle vile svechandle re boo decsrecs DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc ABCDEFGHIJ DIM etki o ecmabero 44743 4A AG 47 4a 4A DIM Wie sue 0x1853 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read max 4 bytes from index 3 in the string rc BleDecodeSTRING attrs 3 decStrs 4 PRINT mdo sdecStirs read max 20 bytes from index 3 in the string will be truncated rc BleDecodeSTRING attrs 3 decStr 20 PREM nice deeSiias reod max 4 bytes trom index 14 1m the string nothing at index 14 rc BleDecodeSTRING attrs 14 decStrS 4 PRINT ide decSrrs Expected Output d CDEF dS CDEFGHIJ oo BLEDECODESTRING is an extension function BleDecodeBITS FUNCTION This function reads bits from an attribute string
169. fails Interactive TA Command Example BleEncode32 sb See in BL600CodeSnippets zip DIM re DIM arces accrceS Lairo J welee BCDE to andex 1 re BleFEncode 37 ewrre 0x4544434727 i write TAr to index 0 rc BleEncode8 attrsS 0x41 0 PRINTI atheros an tis Expected Output attrS ABCDE Americas 1 800 492 2320 Option 2 160 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLEENCODE372 Is an extension function BleEncodeFLOAT FUNCTION This function overwrites four bytes in a string at a specified offset If the string is not long enough it is extended with the new extended block uninitialized and then the byte specified Is overwritten If the nlndex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between and 512 BLEENCODEFLOAT atirS nMatissa nExponent nindex INTEGER a result code j Belin Typical value 0x0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This argument is the string that is written to an attribute byVal nMantissa AS INTEGER This value must be in the range 8388600 to 8388600 or the function fails The data Is written in little endian
170. for the following special values nMantissa OxOO07FFFFF NaN Not a Number 0x00800000 NRes Not at this resolution OxOO7FFFFE INFINITY 0x00800002 INFINITY 0x00800001 Reserved for future use byRef nExponent AS INTEGER nExponent This is updated with the 8 bit mantissa If it is zero check nMantissa for special cases as stated above byVal nindex AS INTEGER This is the zero based index into the string attr from which data is read If the nindex string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive v Command Example BleDecodeFloat sb See in BL600CodeSnippets zip DIM chrhHandle vl svcHhandle rc mantissa SXP DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM acer eturo 00 Ol 02 030465 36037 6335 DIM uuic 3 uuid 0x1853 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read 4 bytes FLOAT from index 2 in the string rc BleDecodeFloat attr S mantissa exp 2 PRINT nthe number read is mantissa x 10 exp read 4 bytes FLOAT from index 6 in the string rc BleDecodeFloat attr mantissa exp 6 PRINT nThe number read is mantissa x 10 exp Expected Output The number read is 262914 10 123 The number read is 829626 10 119 BLEDECODEF
171. fragment of data is nindex written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive No Command Example BleEncodeSFloatEx sb See in BL600CodeSnippets zip DIM sce ila Minis say EP Americas 1 800 492 2320 Option 2 162 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM attr aL Lti Ji write 2 147 148 4l ac SELOAT ro index 0 rc BleEncodeSFloatEX attrs 214718330170 rc BleDecodeSFloat attr mantissa exp 0 PRINT AnThe number stored 16 menriceca x0 exp Expected Output The number stored is 214 x 10 7 BLEENCODESFLOAT is an extension function BleEncodeSFLOAT FUNCTION This function overwrites two bytes in a string at a specified offset as short 16 bit float value If the string is not long enough it is extended with the new block uninitialized Then the byte specified is overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODESFLOAT atitrS nMatissa nExponent nindex INTEGER
172. ful operation Arguments byVal nUuvid16 AS INTEGER Value range 0x2905 to 0x2999 Note This is the actual UUID value NOT the handle nUuidl The highest value at the time of writing is 0x2908 defined for the Report Referenc Descriptor See hitp developer bluetooth org gatt descriptors Pages DescriptorsHomePage as for a list of Descriptors defined and adopted by the Bluetooth SIG byRef attrS AS STRING This is the data that will be saved in the Descriptor s attribute byValn AS INTEGER This is mandatory metadata that is used to define the properties of the Descriptor attribute that will be created in the Characteristic and will have been pre created using the help of the function BleAttrMetadata If the write rights are set to 1 or greater then the attribute is marked as writable and so the client will be able to modify the attribute value atirS mdDesc Interactive No Command Example BleCharDescAdd sb See in BL600CodeSnippets zip DIM rc Metasuccess usr Desc UsrDesco A description DIM charUuad echarUurd Bilehandlevuzdls 1 DIM charMet charMet BleAttrMetaData 1 1 20 0 metaSuccess DIM mdUsrDsc mdUsrDsc charMet DIM mdseed MSCE charmer Americas 1 800 492 2320 Option 2 97 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual initialise char write read enabled accept s
173. g the handle will be thrown to the smart BASIC runtime engine BLEDISCONNECT nConnHandle INTEGER a result code Berung Typical value 0x0000 indicates a successful operation Arguments nConnHandle byVal nConnHandle AS INTEGER Specifies the handle of the connection that must be disconnected Interactive No Command Example BleDisconnect sb See in BL600CodeSnippets zip DIM addr o ee aad Sn DIM rce FUNCTION HndlrBleMsg BYVAL nMsgId AS INTEGER BYVAL nCtx AS INTEGER SELECT mMegid CASE 0 PRINT nNew Connection nCtx rc BleAuthenticate nCtx PRINT BleDisconnect nCtx CASE 1 PRINT nbDiseonnected Tnet TAn Boxer UNC Q ENDSE LECT ENDER ULC wi ONEVENT EVBLEMSG CALL HndlrBleMsg IF BleAdvertStart 0 addrsS 100 30000 0 0 THEN PRINT nAdverts Started n ELSE PRINT n nAdvertisement not successful ENDIF WAL TEVENT Expected Output Americas 1 800 492 2320 Option 2 64 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth New Connection 35800 Disconnected 3580 BLEDISCONNECT Is an extension function BleSetCurConnParms FUNCTION This function triggers an existing connection identified by a handle to have new connection parameters For example interval slave latency and link supervision timeout When the request is complete a EVBLEMSG message with msgid 14 and context containing the handle is thrown to
174. gId BYVAL nCtx conkndl mCEx IF nMsgID 1 THEN PRINT n n Disconnected from client EXITFUNGC O ELSEIF nMsgID 0 THEN PRINT n Connected to client ENDINE EIEN IL 55nn CCCD descriptor written handl er DE PUNCGCETON HndirehnarcCcca By VAl charHandle BYVAL mVal AS ENTEGER DIM values IF charHandle hMyChar THEN PRINT ACCeD Vals my eu iF nyal THEN PRINT Notifications have been enabled by client valueS hello IF BleCharValueNotify hnMyChar value 0 THEN PRINT nrPatled to nmotmiy new value INTEGER A rc ELSE PRINT nSuccessftul notification Of new value EXLEPUNC 30 ENDIF ELSE PRINT Notifications have been disabled by client EADIE ELSE PRINT nrn io FOr some orher Characroristio HNDI E ENDEUNC ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT VCHARCCED CALL HndleCharceced IE Onstartup 0 THEN rc BleCharValueRead hMyChar ats PRINT AnCharacteristic Value zats PRINT Manou can Connect and wri e to che CCCD characteristic PRINT nThe BL600 will then notify your device of a new characteristic valuen ELSE PRINT nratlure OnStartup ENDIF WALTEVENT CloseConnections PRINT ADE al eri ale peers Expected Output Americas 1 800 492 2320 Option 2 105 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Characteristic Value Hi You can connect and
175. h smart BASIC User Manual This extremely low probability of generating the same UUID Is why there is no need for a central register maintained by the Bluetooth SIG for custom UUIDs Please note that Laird does not warrant or guarantee that the UUID generated by this website or any other utility is Unique It is left to the judgement of the developer whether to use it or not Note lf the developer does intend to create custom Services and or Characteristics then it is recommended that a single UUID is generated and be used from then on as a 128 bit 16 byte company developer unique base along with a 16 bit 2 byte offset in the same manner as the Bluetooth SIG This will Then allow up to 65536 custom services and characteristics to be created with the added advantage that it will be easier to maintain a list of 16 bit integers The main reason for avoiding more than one long UUID is to keep RAM usage down given that 16 bytes of RAM is used to store a long UUID Smart BASIC functions have been provided to manage these custom 2 byte UUIDs along with their 16 byte base UUIDs In this document when a Service or Characteristic is described as adopted it implies that the Bluetooth SIG has published a specification which defines that Service or Characteristic and there is a requirement that any device claiming to support them SHALL have approval to prove that the functionality has been tested and verified to behave as per that specificati
176. h No Man In The Middle MITM Protection Encrypted with Man ln The Middle MITM Protection Signed with No Man In The Middle MITM Protection not available Signed with Man In The Middle MITM Protection not available Note In early releases of the firmware 4 and 5 are not available byVal nWriteRights AS INTEGER This soecifies the write rights and shall have one of the following values Om A OJN O No Access Open 2 Encrypted with No Man ln The Middle MITM Protection 3 Encrypted with Man In The Middle MITM Protection 4 Signed with No Man In The Middle MITM Protection not available 5 Signed with Man ln The Middle MITM Protection not available Note In early releases of the firmware 4 and 5 are not available byVal nMaxDataLen AS INTEGER This soecifies the maximum data length of the VALUE attribute Range Is from to 512 bytes according to the BI specification the stack implemented in the module may limit it for early versions At the time of writing the limit is 20 bytes byVal flsVariableLen AS INTEGER Set this to non zero only if you want the attribute to automatically shorten it s length according to the number of bytes written by the client For example if the initial length is 2 and the client writes only 1 byte then if this is O then only the first byte gets updated and the rest remain unchanged If this parameter Is set to 1 then when a single byte is written the attribute will shorten it
177. hind this is that when you come across a 16 bit UUID it implies that a specification will have been published by the Bluetooth SIG whereas using a 128 bit UUID does NOT require any central authority to maintain a register of those UUIDs or specifications describing them The lack of requirement for a central register is important to understand in the sense that if a Custom service or characteristic needs to be created the developer can use any publicly available UUID sometimes also known as GUID generation utility These utilities use entropy from the real world to generate a 128 bit random number that has an extremely low probability to be the same as that generated by someone else at the same time or in the past or future As an example at the time of writing this document the following website hitp www quidgenerator com online guid generator aspx offers an immediate UUID generation service although it uses the term GUID From the GUID Generator website How unique is a GUID 128 bits is big enough and the generation algorithm is unique enough that if 1 000 000 000 GUIDs per second were generated for 1 year the probability of a duplicate would be only 50 Or if every human on Earth generated 600 000 000 GUIDs there would only be a 50 probability of a duplicate Americas 1 800 492 2320 Option 2 73 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetoot
178. ier bags each containing one or more pots of data The GATT Client remote end of the wireless connection needs to see those carrier bags to determine the groupings and once it has identified the pots it will only need to keep a list of references to the pots it is interested in Once that list is made at the client end it can throw away the carrier bag Americas 1 800 492 2320 Option 2 75 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Similarly in The module once the GATT table is created and after each Service is fully populated with one or more Characteristics there is no need to keep that carrier bag However as each Characterstic is placed in the carrier bag using the appropriate smartBASIC API function a receipt will be returned and is referred to as a char_handle The developer will then need to keep those handles to be able to read and write and generally interact with that particular characteristic The handle does not care whether the Characteristic is adopted or custom because from then on the firmware managing it behind the scenes in smartBASIC does not care Therefore from the smartBASIC app developer s logical perspective a GATT table looks nothing like the table that is presented in most BLE literature Instead the GATT table is purely and simply just a collection of char_hand
179. igned writes indicatable rc BleCharNew 0x4B charUuid charMet 0 mdSccd rc BleCharDescUserDesc usrDescS mdUsrDsc r e BikeCiherDescrrsinb rink Ox0R 2 032 1A 0x0 00000 Le ee J other descriptors af Perea Add the other Descriptor 0x29XX first one ey faa DIM mdChrDsc mdChrDsc BileAttrMeradata l 0 20 0 metasuccess DIMA tree e someon lic rc BleCharDescAdd 0x2905 attrs mdChrDsc tar Add the other Descriptor 0x29XX second one VF deen attrs some value2 re rctBleCharDescAdd 0x2906 ae cio maChr DSC a Add the other Descriptor O0x29xx last one VY tae pet SOMenWellucs bC re b leCharbDescAdd 0x290 7 7 atrres mdChrbse IP ee 0 THEN PRINT nOther descriptors added successfully ELSE PRINT nFailed LOAN Bes Exoected Output Other descriptors added successfully BLECHARDESCADD is an extension function BleCharCommit FUNCTION This function commits a Characteristic which was prepared by calling BleCharNew and optionally BleCharDescUserDesc BleCharDescPrstnFrmt or BleCharDescAdd It is an instruction to the GATT table manager that all relevant attributes that make up the Characteristic should appear in the GATT table in a single atomic transaction If it successfully created a single composite Characteristic handle is returned which should not be confused with GATT table attribute handles If the Characteristic was not accepted then this function retur
180. imum of 2 attributes one similar in function as the aforementioned Service attribute and the other the actual data container then properties for the value attribute must be specified Here properties refers to properties for the attribute not properties for the Characteristic container as a whole These also exist and must be specified but that is done in a different manner as explained later For example the value attribute must be specified for read write permission and whether It needs security and authentication to be accessed If the Characteristic is capable of notification and indication the client implicitly must be able to enable or disable that This is done through a Characteristic Descriptor which is also another attribute The attribute will also need to have a metadata supplied when the Characteristic Is created and registered in the GATT table This attribute if it exists is called a Client Characteristic Configuration Descriptor or CCCD for short A CCCD always has 2 bytes of data and currently only 2 bits are used as on off settings for notification and indication A Characteristic can also optionally be capable of broadcasting Its value data in advertisements For the GATT client fo be able to control this there is yet another type of Characteristic Descriptor which also needs a metadata object to be supplied when the Characteristic is created and registered in the GATT table This attribute if it exists is called a
181. ird Technologies smart BASIC User Manual Arguments byVal nTxPower AS INTEGER Specifies the new transmit power in dBm units to be used for all subsequent Tx nTxPower pucker The actual value is determined by scanning through the value list 4 O 4 8 12 16 20 30 55 so that the highest value that is less than the desired value is selected If the desired value is higher than 55 55 is set Interactive No Command Example BleTxPwrWhilePairing sb See in BL600CodeSnippets zip DICAP dp 1000 re BleTxPwrWhilePairing dp PRINT ieee ane aC PRINT nlx power while pairing desired dp actual gt SysInfo 2018 dp 8 re BleTxPwrWhilePairing dp PRINT nlx power while pairing desired dp 7 actual m Sysinto 201s dp 2 re BleTxPwrWhilePairing dp PRINT nlx power while pairing desired do actual Sysinro 201s dp 10 re BleTxPwrwWhilePairing dp PRINT nTx power while pairing desired dp actual SysInfo 2018 dp 25 TC BleTxPwrwhilePairing dp PRINT Ant power while pairing desired dp actual Sysinto 2013 dp 45 re BletxPwrwhilePaiving dp PRINT nTx power while pairing desired dp actual SysInfo 2018 dp 1000 ro BletxPurwWhiilerairing dp PRINT nTx power while pairing desired dp actual Ti Sysitnto 2018 Expected Output while pairing desired 1000 while pairing desired 8 while pairing desir
182. irdtech com bluetooth smart BASIC User Manual PRIM Goueseu Pune 3 72 Digital In Goro pan 3 weak pull we resistor PRINT GpioSetFunc 4 3 0 Analog In Gpio pin 4 default settings PRINT GpioSetFunc 5 1 0x12 internal pull up on gpio5 and wake from deep sleep Wien there 1s cransil lion trom high eo Low Expected Output OO GPIOSETFUNC is a Module function GpioConfigPwm FUNCTION This routine configures the PWM Pulse Width Modulation of all output pins when they are set as a PWM output using GpioSetFunc function described above Note This is a sticky configuration calling it affects all PWM outputs already configured It is advised that this is called once at the beginning of your application and not changed again within the application unless all PWM outputs are deconfigured and then re enabled after this function is called The PWM output is generated using 32 bit hardware timers The timers are clocked by a 1 MHz clock source A PWM signal has a frequency and a duty cycle property the frequency Is set using this function and is defined by the nMaxkResolution parameter For a given nMaxResolution value given that the timer is clocked using a 1 MHz source the frequency of the generated signal is 1000000 divided by nMaxkResolution Hence If nNMinFreqHz is more than the 1000000 nMaxrResolution this function will fail with a non zero value The nMaxResolution can also be viewed as defining the reso
183. is is the zero based index into the string attr from which the data is read If the nindex string attr is not long enough to accommodate the index plus the number of bytes to read this function falls Interactive Ki Command Example BleDecodeS8 sb See in BL600CodeSnippets zip DEM chvnancdre im reene ne DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM attr a atenmo VO Ol 0s 04 85 66 87 e338 39 DIM uuic 3 uuric 0x1853 create random service just for this example rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle create char and commit as part of service commited above rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read signed byte from index 2 rc BleDecodeS8 attrS vl1 2 PRINT ndata in Hex Ox INTEGER H vil PRINT Vadatea in Decimal Y3 ylz yn read signed byte from index 6 two s complement of 122 rc BleDecodeS8 attrS vl1 6 PRINT Andata aon Hex Ox INTEGER IH v1 PRINT ndata in Decimal yl a Expected Output Hex 0x00000002 Decimal 2 Hex OXFFFFFF86 Decimal 122 BLEDECODESS8 Is an extension function BleDecodeU8 Americas 1 800 492 2320 Option 2 168 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNC
184. ith handle nSvcuuad rc BleServiceNew 1 BleHandleUuid1lo 0x1 SEE hsvc initialise characteristic readable rc BleCharNew 0x02 BleHandleUuid16 1 charMet 0 0 Add user descriptor variable length attrs my char desc rc BleCharDescUserDesc attr BleAttrMetadata 1 1 20 1 rc2 ASSECTRO rC2 20 ASSErTRC 6c 33 L Commit char initialised above with initial value char value to service howe attr2S char value rc BleCharCommit hSvc attr2 hMyChar J Gomme Service to CATT table rc BleServiceCommit NSvce re BleAdyort otari 0 acddrs 20 300000 0 ENDFUNC attr SUB CloseConunecriens rc BleDisconnect conHndl rc BleAdvertStop rc GpioUnbindEvent 1 ENDSUB PUNCTION HnidlicBleMso BYVAL mnMsqid BYVAL NCE conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected from client En Danie 0 ELSEIF nMsgID 0 THEN PRINT n Connected to client ENE ENDFUNC 1 PUNCTION Hndilrveatrers ENDEUNG 0 Americas 1 800 492 2320 Option 2 43 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION HndlrCharDesc BYVAL hChar AS INTEGER BYVAL hDesc AS INTEGER AS INTEGER dim cura re IF hChar hMyChar THEN rc BleCharDescRead hChar hDesc 0 20 duid a Perce 0 VAN PRINT nNew valus tor d sriptor shWesc with uwuid imteger h duad ier eae ioe PRINT nCould not read th
185. k es Mower lei le in commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts rc BleAdvertStart 0 addrs 50 0 0 ENDPUNG rE SUB GloseConnmecrlons rc BleDisconnect conHnd1 rc BleAdvertStop BNDSUB SUB SendData DIMEC OnE IF ntfyEnabled then RIL ga oie ie auiave DO xS SomeData rc BleCharValueNotify hMyChar txS Americas 1 800 492 2320 Option 2 45 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Counu Counte Uh ice PRINT n Buffer full PRINCE notin te T ecouri times ENDINE ENDSUB i ai aai Ble event handler a i i i i FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsgID 0 THEN PRINT n Connected to client BLSALE AMSCGLD WHUN PRINT n Disconnected from client EXITFUNG Q ENDINE ENDEUNG i i Tx Buffer free handler Bo i i aaa LUNG LION nd ir Ncny But SendData ENDEUNC 0 OF MMMM 7 7 CCCD descriptor written handler I PUNCGT TON Hndireharecea ByVAlL ehaerhoandle BrYVAl nVval AS INTEGER DIM values txs IF charHandle hMyChar THEN if Vel THEN PRINT Notifications have been enabled by client ntfyEnabled 1 txS Hello rc BleCharValueNotify hMyChar txs ELSKE PRINT nNotifications have been disabled by client ntfyEnabled 0 ENDIF ELSE PRINT TAn Thio rS ror come other characteri Cic ENDI E
186. l result in another EVDISCDESC event message and typically is as follows Register a handler for the EVDISCDESC event message On EVDISCDESC event message If Descriptor Handle 0 then scan is complete Else Process information then call BleDiscDescNext Americas 1 800 492 2320 Option 2 127 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual if BleDiscDescNext not OK then scan complete Call BleDiscDescFirst information from EVDISCCHAR If BleDiscDescFirst ok then Wait for EVDISCDESC INTEGER a result code Typical value 0x0000 Returns Indicates a successful operation and means an EVDISCDESC event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCDESC message will NOT be thrown Arguments byVal nConnHandle AS INTEGER This is the connection handle as returned in the on connect event for the connHandle connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgid 0 and msgCtx will have been the connection handle byVal descUuidHandle AS INTEGER descUuidHandI Set this to O if you want to scan for any descriptor in the characteristic e otherwise this value will have been generated either by BleHandleUuid16 or BleHandleUvid128 or BleHandleUuidSibling byVal char
187. lar UUID the handle of which must be supplied and is generated by using either BleHandleUvid16 or BleHandleUvid128 If instead it is known that a Gatt table has a specific service and a specific characteristic then a more efficient method for locating details of that characteristic is fo use the function BleGattcFindChar which is described later While the scan Is in progress and waiting for the next piece of data from a Gatt server the module will enter low power state as the WAITEVENT statement is used as normal to wait for events and messages Depending on the size of the remote GATT server table and the connection interval the scan of all characteristics may take many 100s of milliseconds and while this is in progress it is sate to do Americas 1 800 492 2320 Option 2 121 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals Note Itis not currently possible to scan for characteristics in included services This will be a future enhancement EVDISCCHAR event message This event message is thrown if either BleDiscCharFirst or BleDiscCharNext returns a success The message contains 5 INTEGER parameters Connection Handle Characteristic Uuid Handle Characteristic Properties Handle for the Va
188. le supplied as the inout parameter The returned handle shall be treated by the developer as an opaque entity and no further logic shall be based on the bit content apart from all O s which represents an invalid UUID handle BLEHANDLEUUIDSIBLING nUvidHandle nUvid16 INTEGER a handle representing the shorthand UUID and can be zero which is an SCUTIS invalid UUID handle if nUuidHandle is an invalid handle in the first place Arguments byVal nUvidHandle AS INTEGER nUvidHandle A handle that was previously created using either BleHandleUuil 6 or BleHandleUuid128 byVal nUvidI6 AS INTEGER nUvid16 A UUID value in the range 0 t0 65535 which will be treated as an offset into the 128 bit base UUID referenced by nUvidHandle Interactive No Command Example BleHandleUuidSibling sb See in BL600CodeSnippets zip PIM whl Hurd Uui nUuid2 will have the same base uuid as hUuidl create a custom uuid for my ble widget uuids ced9d91366924a1287d56f2764762b2a wuids StrDehexizes uuids hUuridil BlenandleUurdl2s iuids IF hUuidl 0 THEN PRINT nFailed to create a handle ELSE PRING Handle for custom Uline ios rnteger NU RUUTd i Aa Uu aa ENDIF Americas 1 800 492 2320 Option 2 85 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual hUuidl now references an object which points to a base uuid ced90
189. leUuid1 6 or BleHandleUuvid128 or BleHandleUuidSibling byVal startAttrHandle AS INTEGER This is the attribute handle from where the scan for characteristic will be started and will have been acquired by doing a primary services scan which returns the start and end handles of services byVal endAttrHandle AS INTEGER This is the end attribute handle for the scan and will have been acquired by doing a primary services scan which returns the start and end handles of services No BLEDISCCHARNEXT connHandle Calling this assumes that BleDiscCharFirst has been called at least once to set up the internal Characteristics sc Returns Arguments nConnHandle Interactive Command Americas 1 800 492 23 anning state machine It scans for the next characteristic INTEGER a result code Typical value 0x0000 Indicates a successful operation and means an EVDISCCHAR event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCCHAR message will NOT be thrown byVal nConnHandle AS INTEGER This is The connection handle as returned in the on connect event for the connection on which the remote Gatt Server can be accessed This will have ber returned in the EVBLEMSG event message with msgid 0 and msgCtx will have been the connection handle No 20 Option 2 123 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless sup
190. led high externally Consult the hardware manual for more information on the input pin number By default it is SIO7 on the module but if can be changed by setting the config key 100 via AI CFG When SIO 7 is attached to VCC Does Sautorun file exist Yes Run autorun Virtual Serial Port app Normal Mode Does Sautoruns ile ever end Virtual Serial Port Command Mode and UART simultaneously Americas 1 800 492 2320 Option 2 187 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual When SIO 7is attached to GND Does r nun r autorun autorun file exist app b Does Sautoruns Command Mode You can interact with the BL600 over the air via the Virtual Serial Port Service using the Laird iOS or Android BL600 Serial app available free on the Apple App Store and Google Play Store respectively You may download smart BASIC applications using a Windows application which will be available for free from Laird The PC must be BLE enabled using a Laird supplied adapter Contact your local FAE for details As most of the AT commands are functional you may obtain information such as version numbers by sending the command AT 3 to the module over the alr Note that the module enters interactive mode only if there is no autorun application or if the a
191. length between and 512 BLEENCODE16 atirS nData nindex INTEGER a result code Kenin Typical value 0x0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This argument is the string that will be written to an attribute byVal nData AS INTEGER nData The two least significant bytes of this integer is saved The rest is ignored byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data nindex is written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive No Command Example BleEncodel6 sb See in BL600CodeSnippets zip DIM aie Fatir arrcti o nema PRINT natin S artis write CD to index 2 rc BleEncodel6 attrS 0x4443 2 Arwa en AB to andex 0 2227 will be tononred rc BleEncodel6 atiro 0x22224241 0 fwrite EE CO Index 3 rc BleEncodel6 attr 0x4645 4 PRINT V narccrS mow ware ine Americas 1 800 492 2320 Option 2 158 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Expected Output ALTYS Lai ro attrsS now ABCDEF BLEENCODE 16 is an extension function BleEncode24 FUNCTION This func
192. les that reference the characteristics data containers which have been registered with the underlying GATT table in the BLE stack A particular char_handle is in turn used to make something happen to the referenced characteristic data container using a smart BASIC function and conversely if data Is written into that characteristic data container by a remote GATT Client then an event is thrown in the form of a message into the smart BASIC runtime engine which will get processed If and only if a handler function has been registered by the apps developer using the ONEVENT statement With this simple model in mind an overview of how the smart BASIC functions are used to register Services and Characteristics is illustrated in the flowchart on the right and sample code follows Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Create a UUID Handle for Service 16 128 BleHandleUuid Commit a PRIMARY or SECONDARY service which returns a service handle BleSvcCommit Create a UUID Handle for Characterisitic 16 128 BleHandleUuid Create a metadata object which defines the permissions for the characteristic value attribute BleAttrMetadata Create a metadata object which Notifiable OR Yes defines the permissions for the Indicatable characteristic CCCD attribute Create a metadata o
193. ling with an appropriate result code byVal nUvidHandle AS INTEGER This is a handle to a 16 bit or 128 bit UUID that identifies the type of Service nUuidHandle function provided by all the Characteristics collected under it It will have been ore created using one of the three functions BleHandleUuid 1 6 BleHandleUuvid128 or BleHandleUuidSibling byRef hService AS INTEGER If the Service attribute is created in the GATT table then this will contain a composite handle which references the actual attribute handle This is then hService i a subsequently used when adding Characteristics to the GATT table If the function fails to install the Service attribute for any reason this variable will contain 0 and the returned result code will be non zero Interactive No Command Example BleServiceNew sb See in BL600CodeSnippets zip DEFINE BLE SERVICE SECONDARY 0 DEFINE BLE SERVICE PRIMARY il DIM THRE Sve composite handle for hts primary service DIM hUMtdHT hUuidhT Blenhandleumid ls 0x1 809 HI Sve UUID Handle LE BU a lei EE VINCE IIR E Inlshies Sie EIN PRINT nHealth Thermometer Service attribute written to GATT table PRINT nUULD Handle value T NUuidhT PRINT nService Attribute Handle value hHtsSvc BLSE PRINT nService Commit Failed SENDI IE DIM hBatSvc composite handle for battery primary service or we could have reused nHtsSve DIM RUU Pari hUnpidBatc Blehandlevund gt Ox1s0r B
194. low p Local Stack Frame Overflow Arguments None Interactive Nio Command Related BLEVSPINFO BLEVSPOPEN BLEVSPWRITE BLEVSPREAD BLEVSPFLUSH Commands Use the iOS BL600 Serial app and connect to your BL600 to test this sample app Example BleVspClose sb See in BL600CodeSnippets zip DIM ES ise CPP r a aE ac Glico mince nandler when VSP tx buffer is empty FUNCTION HandlerVSpTxEmpty AS INTEGER PRINT n nVSP tx buffer empty BleVspClose ENDFUNC 0 PRINT nDevice name is BleGetDeviceNames Open the VSP advertise Ce BleVepopen 126 123 0 7 nnd mo Blescankorlnie SscRors re BleAdvRptAddUuidl128 scRpts hnd1 ECE pe o r4 re BleAdvRptsCommit adRpt scRpts addr rc BleAdvertStart 0 addrs 20 300000 0 Americas 1 800 492 2320 Option 2 191 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This message will send when connected to client tx S Sond this carta ang will close when scene re BleVSpWrite tx ONEVENT EVVSPITXEMPTY CALL HamdlerVsplxEmpey WALTEVENT ESN EL Sa ae sLighe ange Expected Output Device name is LAIRD BL600 VSP tx buffer empty ERICI Nesi BLEVSPCLOSE is an extension subroutine BleVSpinfo FUNCTION This function is used to query information about the virtual serial port such as buffer lengths whether the port i
195. lue Attribute of the Characteristic Included Service Uvid Handle If no more characteristics were discovered because the end of the table was reached then alll parameters will contain O apart from the Connection Handle Characteristic Uuid Handle contains the uuid of the characteristic and supplied as a handle Characteristic Properties contains the properties of the characteristic and is a bit mask as follows Bit O Set if BROADCAST is enabled Bit 1 Set if READ is enabled Bit 2 Set if WRITE_WITHOUT_RESPONSE is enabled Bit 3 Set if WRITE is enabled Bit 4 Set if NOTIFY is enabled Bit 5 Set if INDICATE is enabled Bit 6 Set if AUTHENTICATED_SIGNED_WRITE is enabled Bit 7 Set if RELIABLE_WRITE is enabled Bit 15 Set if the characteristic has extended properties Handle for the Value Attribute of the Characteristic is the handle for the value attribute and Is the value fo store to keep track of important characteristics in a gatt server for later read write operations Included Service Uuid Handle is for future use and will always be 0 BLEDISCCHARFIRST connHandle charUuvidHandle startAttrHandle endAtirHandle A typical pseudo code for discovering characteristic involves first calling BleDiscCharFirst with information obtained from a primary services scan and then waiting for the EVDISCCHAR event message and depending on the information returned in that message calling BleDiscCharNext whi
196. lue is sats PRINT nWrite a new value to the characteristic n BLSE PRINT Tinfarlure Onotartup BNDIE WALTEVENT 21S UN AL SS ov db EIn has gt Expected Output The characteristic s value is Hi Write a new value to the characteristic Connected to client 5 byte s have been written to char value attribute from offset 0 New Char Value Hello Disconnected from client EXILCiNGi sa Americas 1 800 492 2320 Option 2 36 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual EVCHARHVC This event is thrown when a value sent via an indication to a client gets acknowledged If comes with one parameter the characteristic handle that was returned when the characteristic was registered using the function BleCharCommit Example EVCHARHVC charHandle See example that is provided for EVCHARCCCD EVCHARCCCD This event is thrown when the client writes to the CCCD descriptor of a characteristic It comes with two parameters The characteristic handle returned when the characteristic was registered with BleCharCommit 2 The 16 bit value in the updated CCCD attribute Example EvCharCccd sb See in BL600CodeSnippets zip DIM hnMy hia ro atl Comumedk FUNCTION OnStartup DIM re hovo meta uccse s dalo allen adRoto addr CRpt atere Hi DIM svcUuid svcUuid 0xI8EE DIM
197. lution of the PWN output in the sense that the duty cycle can be varied from 0 to nMaxResolution The duty cycle of the PWM signal is modified using the GpioWrite command For example a period of 1000 generates an output frequency of 1KHz a period of 500 and a frequency of 2Khz etc On exit the function returns with the actual frequency in the nMinFreqHz parameter GPIOCONFIGPWM nMinFreqHz nMaxResolution INTEGER a result code Returns a Most typical value 0x0000 indicates a successful operation Arguments byRef nMinFreqHz AS INTEGER nMinFreqHz On entry this variable contains the minimum frequency desired for the PWM output On exit if successful it contains the actual frequency of the PWM output f byVal nMaxResolution INTEGER nMaxResolution D This soecifies the duty cycle resolution and the value to set to get a 100 duty Americas 1 800 492 2320 Option 2 22 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual cycle Interactive No Command Example GpioConfigPWM See in Firmware Zip file DIM re Da nine c hl 27 RES we want a minimum frequency of 500Hz so that we can use a 100Hz low pass filter to create an analogue output which has a 100Hz bandwidth nFreqHz 500 we want a resolution of 1 1000 in the generated analogue output nMaxValUs 1000 PRINT GpioConfigPWM nFreqHz nMaxRes
198. m STRING size 1 for run time only implementation ne 3 for compiler included Reason for reset 5000 8 Self Reset due to Flash Erase 9 ATZ 10 Self Reset due to smart BASIC app invoking function RESET 2002 Timer resolution in microseconds 2003 Number of timers available in a smart BASIC Application 2004 Tick timer resolution in microseconds Interactive NO Command j example Sysinfo sb See in Firmware Zip file PRINT wsyclmbo 2005 SVS INE OZ OOS A eeen On emer Pe ns sinew 000 Ho SCS IINIEO LOO BASIC compiler HASH value PRINT nsvysinto Uxs0l0 SYSINPOVOxs010 77 Code memory page size from FICK Expected Output For BL600 Sysinroe L000 1313489536 oyosInTto 2003 8 ovolnrio yx Lg 1024 SYSINFO is a core language function Americas 1 800 492 2320 Option 2 13 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SYSINFOS FUNCTION Returns an informational string value depending on the value of varld argument SYSINFOS varld Returns STRING Value of information corresponding to integer ID requested Exceptions Local Stack Frame Undertlow Local Stack Frame Overflow Arguments varld byVal varld AS INTEGER An integer ID which is used to determine which information is to be returned as described below The Bluetooth address of the module It is seven bytes long Fir
199. mmand AT CFG must be used which is described in detail here To read current values of these objects use the command AT CFG described here Predefined configuration objects are as listed under details of the AT CFG command 9 MISCELLANEOUS Bluetooth Result Codes There are some operations and events that provide a single byte Bluetooth HCI result code e g the EVDISCON message The meaning of the result code Is as per the list reproduced from the Bluetooth Specifications below No guarantee is supplied as to ifs accuracy Consult the specification for more Result codes in grey are not relevant to Bluetooth Low Energy operation and are unlikely to appear BT HCI STATUS CODE SUCCESS 0x00 BT HCI STATUS CODE UNKNOWN BTLE COMMAND 0x01 BT HCI STATUS CODE UNKNOWN CONNECTION IDENTIFIER 0x02 BT HCI HARDWARE FAILURE 0x03 BT HCI PAGE TIMEOUT 0x04 BT HCI AUTHENTICATION FAILURE 0x05 BT HCI STATUS CODE PIN OR KEY MISSING 0x06 BT HCI MEMORY CAPACITY EXCEEDED 0x07 BT HCI CONNECTION TIMEOUT 0x08 BT HCI CONNECTION LIMIT EXCEEDED 0x09 BT HCI SYNC CONN LIMI TO A DEVICE EXCEEDED OxO0A BT HCI ACT COONECTION ALREADY EXISTS OxOB BT HCI _ STATUS _CODE _ COMMAND DISALLOWED 0Ox0C BT HCI CONN REJECTED DUE TO LIMITED RESOURCES Ox 0D BT HCI CONN REJECTED DUE TO SECURITY REASONS Ox0OE BY HCl BI HCI CONN REJECTED DUE TO BD ADDR OxOF BT HCI CONN ACCEPT TIMEOUT EXCEEDED 0x10 BT HCI UNSUPPORTED FEATURE ONPARM VALUE Oxll BT _HCI _STATUS _CODE _ INVALID B
200. mple code demonstrating usage and expected output Events and Messages The nature of GATT Client operation consists of multiple queries and acting on the responses Due to the connection intervals being vastly slower than the speed of the cpu responses can arrive many 10s of milliseconds after the precudure was triggered which are delivered to an app using an event or message Since these event messages are tightly coupled with the appropriate commands all but one will be described when the command that triggers them Is described The event EVGATTCTOUT is applicable for all Gatt Client related functions which result in transactions over the air The Bluetooth specification states that if an operation is initiated and Is not completed within 30 seconds then the connection shall be dropped as no further Gatt Client transaction can be initiated EVGATTCTOUT event message This event message WILL be thrown if a Gatt Client transaction takes longer than 30 seconds It contains 1 INTEGER parameter Connection Handle Example EVGATTCTOUT sb See in BL600CodeSnippets zip a DIM rG eo mime POUNETIONVOnstareup DIM te adROto addr CRpt tc BleAdyRkotInit adRots 27 0 10 IF rc 0 THEN rc BleScanRptInit scRpt ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpts scRpt ENDIF LE e 0 THEN lt re BleAdvertStart 0 addrs 50 0 0 ENDIF lopen the gatt client with default notify indicate ring buffer size IF rc 0 THE
201. mplete Call BleDiscServiceFirst If BleDiscServiceFirst ok then Wait for EVDISCPRIMSVC INTEGER a result code Typical value 0x0000 Indicates a successful operation and means an EVDISCPRIMSVC event Returns message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVDISCPRIMSVC message will NOT be thrown Arguments byVal nConnHandle AS INTEGER This is the connection handle as returned in the on connect event for the nConnHandle connection on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle byVal startAtirHandle AS INTEGER This is the attribute handle from where the scan for primary services will be sian nance started and you can typically set it to O to ensure that the entire remote Gatt Server is scanned byVal uuvidHandle AS INTEGER idHandle Set this to O if you want to scan for any service otherwise this value will ue have been generated either by BleHandleUuid16 or BleHandleUuid 128 or BleHandleUuidSibling Americas 1 800 492 2320 Option 2 117 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive Command no BLEDISCSERVICENEXT connHandle Calling this assumes that BleDiscServiceFirst has been called at least once t
202. n This is the size of the ring buffer used for incoming notifiable and indicatable characterstic data Set to 0 to use the default size byVal nFlags AS INTEGER Bit 0 Set to 1 to disable automatic indication confirmations if buffer is nFlags full Then the Handle Value Confirmation will only be sent when BleGattcNotifyRead is called to read the ring buffer Bit 1 31 Reserved for future use and must be set to Os Interactive No Command Example BleGattcOpen sb See in BL600CodeSnippets zip DAL eb sieve ropen the gatt client with default notify indicate ring buffer size re BleGattcOpen 0 0 IF rc 0 THEN PRINT nGatt Client is now open ENDIF open the client with default notify indicate ring buffer size again rc BleGattcOpen 128 1 IF rc 0 THEN PRINT nGatt Client is still open because already open ENDIF Expected Output Gatt Client is now open Gatt Client is still open because already open BLEGATTCOPEN Is an extension function Americas 1 800 492 2320 Option 2 115 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleGattcClose SUBROUTINE This function is used to close the GATT client manager and Is safe to call if it is already closed It is recommended that this function NOT be called when in a connection BLEGATTCCLOSE Arguments None Interactive No Command Example
203. nd manage those procedures to enable a smartBASIC application to map the table Americas 1 800 492 2320 Option 2 112 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual These helper functions have been written to help gather the handles of all the rows which contain the value type for appropriate characteristics as those are the ones that will be read or written to The smartBASIC internal engine also maintains data objects so that it is possible to interact with descriptors associated with the characteristic In a nutshell the table scanning process will reveal characteristic handles as handles of handles and these are then used in other GATT client related smartBASIC functions to interact with the table to for example read write or accept and process incoming notifications and indications This encapsulated approach is to ensure that the least amount of RAM resource Is required to implement a GATT Client and given that these procedures operate at soeeds many orders of magnitude slower compared to the speed of the cou and energy consumption is to be kept as low as possible the response to a command will be delivered asynchnornously as an event for which a handler will have to be specified in the user smartBASIC application The rest of this chapter describes all the GATT Client commands responses and events in detail along with exa
204. ndicate hMyChar value LE rel 0 gt THEN PRINT nFailed to indicate new value INTEGER H rc ELSE PRINT nSuccessful indication of new value EET P UNG 1 ENE BLSE PRINT Indications have been disabled by client INDICE ATOE PRINT nilhas is for Some other characteristic BNDIE ENDEUNG 1 aenasss2nss58 5555555555555 5 5555555555555 5555555555555 5 555555555 555555555555 5 Indication Acknowledgement Handler aenesssssss58 5555555555555 5 5555555555555 5 5555555555555 5 555555555 5555555555 5 5 FUNCTION HndlrChrHvc BYVAL charHandle IF charHandle hMyChar THEN PRINT n nGot confirmation of recent indication BLSE PRINT n mGor Confirmation of Some other indication charlandle EN DIiLE ENDE UIC 20 ONEVENT EVBLEMSG CALL HndlrBleMsg ONEVENT TEVCHARCCCD ALL Hudlrehmavcecd Americas 1 800 492 2320 Option 2 107 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ONEVENT EVCHARHVC CALL Hndlrehrive IF OnStartup 0 THEN re BleCharValueRead hMyChar at PRINT nCharacteristic Value sabes PRINT anyo can Connect and Write to the CCCD Characteristic PRINT nThe BL6OOO will then indicate a new characteristic value n BLSE PRINT nFailure OnStartup ENDIF WALITEVENT rc BleDisconnect conHnd1l rc BleAdvertStop UNE SANE ICIN aae Expected Output Characteristic Val
205. ndicate ring buffer size LF re 0 THEN re BleGattcOpen 0 0 ENDIF ENDFUNC xe Close connections so that we can run another app without problems Americas 1 800 492 2320 Option 2 147 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual SUB ClosetConnecrrons rc BleDisconnect conHndl1 rc BleAdvertStop BNDSUB FUNCTION HndilrBleMsg BYVAL nMsgid BYVAL mCtex DIM uHndA conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNC Q ELSEIF nMsgID 0 THEN PRINT n Connected so write to attibute handle 3 atHndl 3 ats 01 02 03 04 rc BleGattcWrite conHndl atHndl at IF rc 0 THEN WALILTEVENT ENDIF PRINT nwrite to attibute handle 300 which does not exist atHndl 300 rc BleGattcWrite conHndl atHndl atS IF rc 0 THEN WALILTEVENT ENDIF CloseConnections ENDIF ENDEUNG 1 function HandVverAcreEerWeleSs cundi annd nots as Integer dim nOrste nAnhndl ars Pranic EVAT TRWAI TE T Drine Arnd ema Pring M atir rnndi ranndal print status integer n nots if nSts 0 then Print S nAttr bute write OK else print nPailed to write attribute endif endfunc 0 a Main equivalent sasossssasssesaesasessss aaa ONEVENT EVBLEMSG CALL HndlrBleMsg OnEvent EVATTRWRITE call HandlerAttrWrite IF OnStartup 0 THEN PRINT nAdvertising and Gatt Client i
206. ndleUvid128 or BleHandleUuidSibling Note When a GATT Client queries a GATT Server for services over a BLE connection it will only get a list of PRIMARY services SECONDARY services are a mechanism for multiple PRIMARY services to reference single instances of shared Characteristics that are collected in a SECONDARY service This referencing is expedited within the definition of a service using the concept of INCLUDED SERVICE which itself is just an attribute that is grouped with the PRIMARY service definition An Included Service is expedited using the function BleSvcAddlncludeSvc which is described immediately after this function This function now replaces BleSvcCommit and marks the beginning of a service definition in the gatt server table When the last descriptor of the last characteristic has been registered the service definition should be terminated by calling BleServiceCommit BLESERVICENEW nSvcType nUuvidHandle hService Returns INTEGER a result code Americas 1 800 492 2320 Option 2 86 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Typical value 0x0000 indicates a successful operation Arguments byVal nSvcType AS INTEGER This will be O for a SECONDARY service and 1 for a PRIMARY service and all other nSvcType values are reserved for future use and will result in this function fai
207. nindex AS INTEGER This is the zero based index into the string attr from which data is read If the atirS nindex string attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive No Command Example BleDecodeU24 sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 173 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM chenancile vi eweh ame le re DIM mdVal mdVal BleAttrMetadata 1 1 50 0 rc DIM oette e aer mA OO OAO 03 0485 so 37 33 357 DIM uuic 3 uuid 0x18953 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl16 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHandle rc BleCharValueRead chrHandle attr read 3 unsigned bytes from index 2 rc BleDecodeU24 attr vl1 2 PRINT andata an Hex Ox INTEGER A vl PRINT Y ndarta in Decimal Ys nicl Gan read 3 unsigned bytes from index 6 rc BleDecodeU24 attr vl1 6 PRINT ndate ian Hex Ox INTEGER Hy PRINT Y ndata in Decimal g yig n Expected Output data in Hex 0x00040302 Gata in Decimal 262914 data in Hex 0x00888786 data in Decimal 8947590 BLEDECODEU24 Is an extension function BleDecode32 FUNCTION This function reads four bytes in a st
208. nindex points to a valid entry in the database this variable contains a nExtralnfo composite integer value where the lower 16 bits are the eDIV Bit 16 is set if the IRK Identity Resolving Key exists for the trusted device and bit 17 is set if the CSRK Connection Signing Resolving Key exists for the trusted device Interactive No Command Example BleBondMngrGetInfo sb See in BL600CodeSnippets zip define BLE INV INDEX 24619 DIM re addr cx inio ro BleBondMngrGetInfo 0 addrS exInfo Extract info of device at index 1 IF rc 0 THEN PRINT nMAC address addr PRINT ninfo exinio ERLCE LE rC BLE TNV TNDEX THEN PRINT mlnvalad index BNDILE Expected Output when valid entry present in database MAC address 00 BC Bl1 F3x3 AB Into 9743537 Expected Output with invalid index Invalid index BLEBONDMNGRGETINFO is an extension function Virtual Serial Port Service Managed Test When Dongle and Application are Available This section describes all the events and routines used to interact with a managed virtual serial port service Managed means there is a driver consisting of transmit and receive ring buffers that isolate the BLE service from the smarfBASIC application This in turn provides easy to use API functions Note The driver makes the same assumption that the driver in a PC makes If the on air connection equates to the serial cable there is no assumption that the cable is f
209. nologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Valid values O to 16383 seconds O disables the timer makes if continuous 115 This is used to specify the UART baudrate when Virtual Serial Mode Service is active and UART bridge mode is enabled Valid values 1200 2400 4800 9600 14400 19200 28800 38400 57600 76800 115200 230400 250000 460800 921600 1000000 Note If an invalid value is entered then the default value of 9600 is used 116 In VSP UART bridge mode this value specifies the latency in milliseconds for data arriving via the UART and transfering to VSP and then onward on air This mechanism ensures that the underlying bridging algorithm waits for up to this amount of time before deciding that no more data Is going to arrive fo fill a BLE packet and so flushes the data onwards Note Given that the largest packet size takes 20 bytes if more than 20 bytes arrive then the latency timer is overridden and the data is immediately sent Interactive Command YES AI CFG is a core Command Note These values revert to factory default values if the flash file system is deleted using the AT amp F interactive command AT BTD COMMAND Deletes the bonded device database from the flash AT BID Returns nOO r Arguments None Interactive Command TE gt This is an interactive mode command and MUST
210. ns a non zero result code which conveys the reason and the handle argument that is returned has a special invalid handle of 0 The characteristic handle that is returned refers to an internal opaque object that is a linked list of all the attribute handles in the Characteristic This implies that there is a minimum of one for Americas 1 800 492 2320 Option 2 98 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual the characteristic value attribute and more as appropriate For example if the Characteristic s property specified is notifiable then a single CCCD attribute also exists Note In the GATT table when a Characteristic is registered there are actually a minimum of two attribute handles one for the Characteristic Declaration and the other for the Value However there is no need for the smart BASIC apps developer to ever access it so it is not exposed Access is not required because the Characteristic was created by the application developer and so shall already know its content which never changes once created BLECHARCOMMIT hService attrS charHandle INTEGER a result code Beinn Typical value 0x0000 indicates a successful operation Arguments byVal hService AS INTEGER hService This is the handle of the service that this Characteristic shall belong to which in tu was created using the function Ble
211. nsuauetigeunastiabtonemaaueesnia 182 Virtual Serial Port Service Managed Test When Dongle and Application are Available ccccccsseeeeeeeees 184 6 Other Extension Built in Routines cccccecececececeeeteteeeeeteceseseseseseceeeeueueuanauatatatatatatanatatas 200 System CON TCUPAT OM ROUTINES cccassetconsanstasnsncaestenoatssennsaaictidonnacatedeansacidaneciisa E E Ea 200 Miscelaneos ROUTE mpare en a E E E E 201 7 Events amp Messages n annsnnnnnnnnnnnnnnnnrnnnrrnnnrnnnrrnnnennnnrnnnennnnrnnnernnnrnnnrrnnnennnnrnnnennnnrnnne nennen nnne 203 8 Mod le Com guration scscraiccasteascadsesccducadeaecedsatecdeanavasaueseseddeanivanced saranceavaneecudtasenduaniteccadeasas 204 9 Miscellaneous eaen aE ERAAN EEREN 204 lO ACkhowledge Ments asrirsrrisiirrnireinirrinrin eris abni rtn nii DNNN i 206 EK ae ee ee ee ee ee ee eee 207 Americas 1 800 492 2320 Option 2 4 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 1 INTRODUCTION Documentation Overview This BL600 Extension Functionality user guide provides detailed information on BL600 specific smart BASIC extensions which provide a high level managed interface to the underlying Bluetooth stack in order to manage the following GATT table Services characteristics descriptors advert reports Gatt server client operation Advertisments and connections BLE
212. nt manager Is opened using BleGattcOpen it is possible to specify the size of the ring buffer If a value of O is supplied then a default size is created SYSINFO 2019 in a smartBASIC application or the interactive mode command AT 2019 will return the default size Likewise SYSINFO 2020 or the command AT 2020 will return the maximum size Americas 1 800 492 2320 Option 2 152 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Data that arrives via notifications or indications get stored in the ring buffer and at the same time a EVATTRNOTIFY event is thrown to the smartBASIC runtime engine This is an event in the same way an incoming UART receive character generates an event that is no data payload is attached to the event EVATTRIOTIFY event message This event WILL be thrown when an notification or an indication arrives from a gatt server The event contains no parameters Please note that if one notification indication arrives or many like in the case of UART events the same event mask bit is asserted The paradigm being that the smartBASIC application is informed that it needs to go and service the ring buffer using the function BleGattcNotifyRead BLEGATTCNOTIFYREAD connHnd1 attrHndl atirDataS discardCount A typical pseudo code for handling and accessing notification indication data is as follows Register a h
213. nterval and then have a non zero slave latency For example a keyboard could set the connection interval to 1000 msec and slave latency to 0 In this case key presses are reported to the central device once per second a poor user experience Instead the connection interval can be set to e g 50 msec and slave latency to 19 If there are no key presses the power use Is the same as before because 19 1 50 equals 1000 When a key is pressed the peripheral knows that the central device will poll within 50 msec so it can send that keypress with a latency of 50 msec A connection interval of 50 and slave latency of 19 means the slave is allowed to NOT acknowledge a poll for up to 19 poll messages from the central Americas 1 800 492 2320 Option 2 65 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual device Interactive No Command Example BleSetCurConnParms sb See in BL600CodeSnippets zip Dil ise DIM adcar s ador g W FUNCTION HandlerBleMsg BYVAL nMsgid AS INTEGER BYVAL SN CE AS INTEGER DIM intve vilken S lene SELECT nisoid CASE O0 BLE EVBLEMSGID CONNECT PRINT n New Connection nCtx re Bb FeGereurconnbParms NOt meni Sorc znO Slat IF rc 0 THEN PRENE no mine inte terol a tee ete ell PRINT nConn Supervision Timeout sprvto PRINT nConn Slave Latency slat PRINT n nRequest new par
214. nts byVal nEventNum INTEGER nEventNum The GPIO event number in the range of 0 N which is disabled so that it no longer generates run time events in smart BASIC Interactive No Command Example GpioUnbindEvent sb See in Firmware Zip file FUNCTION BtnOPress PRINT nHel lo EN DEUNG wi FUNCTION Imre OTimedOur PRINT nNothing happened ENDFUNC O PRINT CpioBindEvent 0 U6 a je mn ONEVENT EVGPIOCHANO CALL BtnOPress ONEVENT EVTMRO CALL TmrOTimedOut PRINT GprcoUnbindgE vent 0 Vn PRINT 2 VaPrese buccon 0n TimerStart 0 8000 0 Americas 1 800 492 2320 Option 2 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth 26 Laird Technologies smart BASIC User Manual WALTEVENT Expected Output O O Press button 0 Nothing happened GPIOUNBINDEVENT is a Module function GpioAssignEvent FUNCTION This routine assigns an event to a level transition on a specified special I O line configured as a digital input Changes in the input line can invoke a handler in smart BASIC user code Note In the BL600 this function results in around 4UA of continuous current consumption from the power supply It is impossible to assign a polarity value which detects either level transitions GPIOASSIGNEVENT nEventNum nSigNum nPolarity INTEGER a result code Seire Typical value 0x0000 indicates a successful operation Argument
215. o return value implies an EVFINDDESC message will NOT be thrown Arguments byVal connHndl AS INTEGER This is the connection handle as returned in the on connect event for the connecti connHndl on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCix will have been the connection handle byVal svcUuHndl AS INTEGER svcUuHndlI Set this to the service uuid handle which will have been generated either by BleHandleUuvid16 or BleHandleUuid128 or BleHandleUuidSibling byVal svcidx AS INTEGER svcldx This is the instance of the service to look for with the uuid handle svcUvidHndl where O is the first instance 1 is the second etc byVal charUuHndl AS INTEGER charUuHndl Set this to the characteristic uuid handle which will have been generated either by BleHandleUuvid16 or BleHandleUuvid128 or BleHandleUuidSibling byVal charldx AS INTEGER charldx This is the instance of the characteristic to look for with the uuid handle charUvidHnal where 0 is the first instance 1 is the second etc byVal descUuHndl AS INTEGER descUuHnd1 Set this to the descriptor uuid handle which will have been generated either by BleHandleUuid16 or BleHandleUvid128 or BleHandleUuidSibling byVal descldx AS INTEGER descldx This is the instance of the descriptor to look for with the uuid handle charUvidHnal where 0 is the first instance 1 is the second etc Interactive
216. o not set this to e g 100 ms byVal nFilterPolicy AS INTEGER Specifies the filter policy for the whitelist consisting of all bonded masters as follows O Disable whitelist Filter scan request allow connection request from any Filter connection request allow scan request from any 3 Filter scan request and connection request If the filter policy is not O the whitelist is enabled and filled with all the adaresses of all the devices in the trusted device database No BleAdvertStart sb See in BL6o00CodeSnippets zip Psaddns BUNGLE SkndileB ike Ady lim O PRINT nAdvert stopped via timeout PRATEN E I En pa cn ENDFUNC 0 Americas 1 800 492 2320 Option 2 52 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual The advertising interval is set to 25 milliseconds The module will stop advertising after 60000 ms 1 minute IF BleAdvertStart 0 addrS 25 60000 0 0 THEN PRINT nAdverts Started PRINT nIf you search for bluetooth devices on your device you should see Phacd BLCOO TM ELSE PRINT n nAdvertisement not successful ENDTE OE VIANA EVB CE EDC AME UTEE AE Hn E TEA EmO WALTEVENT Expected Output Adverts Started If you search for bluetooth devices on your device you should see Laird BLGOU Advert stopped via timeout ELCO BLEADVERTSTART is an extension function
217. o set up the internal primary services scanning state machine INTEGER a result code Typical value 0x0000 Indicates a successful operation and it means an EVDISCPRIMSVC event Returns message WILL be thrown by the smarfBASIC runtime engine containing the results A non zero return value implies an EVDISCPRIMSVC message will NOT be thrown Arguments byVal nConnHandle AS INTEGER This is The connection handle as returned in the on connect event for the nConnHandle connection on which the remote Gatt Server can be accessed This will have bee returned in the EVBLEMSG event message with msgid 0 and msgCtx will have been the connection handle Interactive No Command Example BleDiscServiceFirst Next sb See in BL600CodeSnippets zip ee Remote server has 5 prim services with 16 bit uuid and 3 with 128 bit uuids 3 of the 16 bit uuid are the same value OxDEAD and j 2 on the 123 bit uuids are also Ene same 1172334455660 7 330 09A 2EBCeDDE EE Jay i Seiever e e l Ussing BikeGeaiiccllolise emis We Slo O ska Coeailicio sere A Using horde Wc Dongle Pe Louge Divine cine Colmmcle And N mums PUNCTION OnsotaneuS DUM rO Tado r waldchaoruns hpir re pileAdvRpelnie adkpes 2 07 10 IE re 0 THEN re BleSeankoe Inve skp ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpt scRpt ENDIF LE e 0 TEEN 2 re BleAdgvertStlarc O addro 50 0 0 ENDIF open the gatt client with default notify indicate
218. ode INTEGER a result code seme Typical value 0x0000 indicates a successful operation Arguments byVal connHndl AS INTEGER This is the connection handle as returned in the on connect event for the connHndl connection on which the remote Gatt Server can be accessed This will have beel returned in the EVBLEMSG event message with msgid 0 and msgCix will have been the connection handle byRef attrHndl AS INTEGER attrHndl The handle for the attribute that was read is returned in this variable Will be the same as the one supplied in BleGattcRead but supplied here so that the code can be stateless byRef offset AS INTEGER The offset into the attribute data that was read is returned in this variable Will be offset the same as the one supplied in BleGattcRead but supplied here so that the code can be stateless ttrDatas byRef atirDataS AS STRING onary The attribute data which was read is supplied in this parameter Interactive nis Command Example BleGattcRead sb See in BL600CodeSnippets zip Joy Remote server has 3 prim services with 16 bit uuid First service has one characteristic whose value attribute is at handle 3 and has read write props Te U Seiove Geese e Meine BleGanicewoliteccl Sulo iimvolecl iin Oceiivice Scie Sng Nordio Usb Dongle Peo 000 Dill Macro Comin ean nOr aea HUNG iG VOns pacene DIM ror adheres addr SORE re BileAdvRpreInit adRpts 2 0 10 TE w 0 THEN 9
219. odems Their values are kept over a power cycle but are deleted if the AT amp F command is used to clear the file system If a required configuration key isn t listed below use the functions NvRecordSet and NvRecordGet to set and get these keys respectively The num value syntax is used to set a new value and the num syntax is used to query the current value When the value is read the syntax of the response Is 27 Oxhhhhhhhh dddd where Oxhhhhhhhh is an eight hexdigit number which is O0 padded at the left and dddd is the decimal signed value Americas 1 800 492 2320 Option 2 Fi Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual AT CFG num value or AT CFGnum Returns If the contig key is successfully updated or read the response Is n00O r Arguments num Integer Constant The ID of the required configuration key All of the configuration keys are stored as an array of 16 bit words value Integer_constant This is the new value for the configuration key and the syntax allows decimal octal hexadecimal or binary values This is an Interactive mode command and MUST be terminated by a carriage return for it to be processed The following Configuration Key IDs are defined 40 Maximum size of locals simple variables 4 Maximum size of locals complex variables 42 Maximum depth of nested user defined f
220. of information corresponding to integer ID requested Exceptions Local Stack Frame Underflow Local Stack Frame Overflow Arguments varld byVal varld AS INTEGER An integer ID which is used to determine which information is to be returned as described below ID of device Each platform type has a unique identifier BL600 module value 0x42460600 Version number of module Firmware For example W X Y Z is returned as a 32 bit value made up as follows W lt lt 26 X lt lt 20 Y lt lt 6 Z Americas 1 800 492 2320 Option 2 12 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual where Y is the build number and Z is the sub build number 33 BASIC core version number 601 Flash File System Data Segment Total Soace 602 Flash File System Data Segment Free Soace 603 Flash File System Data Segment Deleted Space 611 Flash File System FAT Segment Total Soace 612 Flash File System FAT Segment Free Soace 613 Flash File System FAT Segment Deleted Space 631 NvRecord Memory Store Segment Total Soace 632 NvRecord Memory Store Segment Free Soace 633 NvRecord Memory Store Segment Deleted Space 1000 BASIC compiler HASH value as a 32 bit decimal value 1001 How RAND generates values O for PRNG and 1 for hardware assist 1002 Minimum baudrate 1003 Maximum baudrate 1004 Maximu
221. on Arguments byVal charHandle AS INTEGER charHandle This is the handle to the characteristic whose value must be read which was returned when BleCharCommit was called byRef atirS AS STRING attrs This string variable contains the new value from the characteristic Americas 1 800 492 2320 Option 2 100 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive No Command Example BleCharValueRead sb See in BL600CodeSnippets zip DIM NMyChar eC aC Olniam endl PUNCTIONM ONGEA DIM rer Svc SCRE sod h to cleo at ibis a a hii commit service rc BleServiceNew 1 BleHandleUuidl6 Ox18EE hSvc initialise char write read enabled accept signed writes rc BleCharNew 0x0A BLleHandleUuidl16 1 BleAttrMetaData 1 1 20 0 rc 0 0 commit Char initialised above With initial value hi to service hsvc rc BleCharCommit hSvc attrs hMyChar commit changes to service re BileServicegommie Nove initialise scan report Ge BleScankoel Mikel Sseckprs Add 1 service handle to scan report wea 2 Lee veo NCCU UACLLS SOc a a commit reports to GATT table adRpt is empty rc BleAdvRptsCommit adRpt scRpts ec BleAdvertStart 0 addrs 150 00 0 ENDFUNG re PUNCTION Hnidtrehar BYVAL ehehndit BYVALwObEsel BryAl Len dim s IF chrHndl hMyChar THEN PRINT n len byte s have been written to
222. on Currently there is no requirement for custom Service and or Characteristics to have any approval By definition interoperability is restricted to just the provider and implementer A Service is an abstraction of some collectivised functionality which if broken down further into smaller components would cease to provide the intended behaviour A couple of examples in the BLE domain that have been adopted by the Bluetooth SIG are Blood Pressure Service and Heart Rate Service Each have sub components that map to Characteristics Blood Pressure is defined by a collection of data entities like for example Systolic Pressure Diastolic Pressure Pulse Rate and many more Likewise a Heart Rate service also has a collection which includes entities such as the Pulse Rate and Body Sensor Location A list of all the adopted Services is at http developer bluetooth org gatt services Pages ServicesHome aspx Laird recommends that if you decide to create a custom Service then it is defined and described in a similar fashion so that your goal should be to get the Bluetooth SIG to adopt it for everyone to use in an interoperable manner These Services are also assigned 16 bit UUIDs value 0x18xx and are referenced in some of the smart BASIC API functions described in this section Services as described above are a collection of one or more Characteristics A list of all adopted characteristics is found at hitp developer bluetooth org gatt characte
223. on Use the iOS BL600 Serial app and connect to your BL600 to test this sample app Example VSpEvents sb See in BL600CodeSnippets zip DEM 1250S 166 SCINOES a RPE eiclolieS laimellL nandler for data arrival FUNCTION HandlerBleVsSpRx AS INTEGER erint the data that arrived DIM n tees m BleVSpRead rz gt 20 PRINT Var xs ENDEUNG 1 nandler when VSP tx buffer is empty FUNCTION HandlerVSpTxEmpty AS INTEGER IF x 0 THEN re BileVspWrei re txs x ENDIF ENDEUNG PRINT nDevice name is BleGetDeviceNames Open the VSP re BlevVspopen 12s 128 0 nnd j iMtevealise a scan report re BleScanRptInit scRpt Advertise the VSP service in the scan report so that it can be seen by the client Coy BleNeyRpEeAddUundil 73 sekpie nnd adRpt W re BleAdvRptsCommit adRpt scRpts addrS because we are not doing a DIRECT advert cc BleAdvertStart 0 addrs 20 300000 0 Now advertising so can be connectable ONE VENT EVVSEPRX CALL HandlerBleVSpRx ONEVENT EVVSPTXEMPTY CALL HandlerVSpTxEmpty txS tx buffer empty PRINT nUse the 20S BLCOO Serial app to test this wait for events and messages WALTEVENT BleVSpOpen FUNCTION Americas 1 800 492 2320 Option 2 189 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This function opens the def
224. out is automatically set to 1280 ms When filter policy is enabled the whitelist consisting of all bonded masters is submitted to the underlying stack so that only those bonded masters result in scan and connection requests being serviced Note nAdvTimeout is rounded up to the nearest 1000 msec BLEADVERTSTART nAdvType peerAddrS nAdvinterval nAdvTimeout nFilterPolicy INTEGER a result code eum Typical value 0x0000 indicates a successful Operation If a Ox6A01 resultcode Is received it implies whitelist has been enabled but the Flags AD in the advertising report is set for limited and or general discoverability The solution is to resubmit a new advert report which is made up so that the nFlags argument to BleAdvRptinit function is O The BT 4 0 spec disallows discoverability when a whitelist is enabled during advertisement see Volume 3 Sections 9 2 3 2 and 9 2 4 2 Arguments byVal nAdvType AS INTEGER Specifies the advertisement type as follows O ADV_IND Invites connection requests nAdvlype ADV_DIRECT_IND Invites connection from addressed device 2 ADV_SCAN_IND Invites scan requests for more advert data 3 ADV_NONCONN_IND Does not accept connections and or active scans Americas 1 800 492 2320 Option 2 51 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual peerAddrs nAavinterval nAdvTimeout
225. pare Queue Full OxO10A ATT Error Used in ATT as Attribute not found OxO10B ATT Error Attribute cannot be read or written using read write blob requests 0x010C Error Encryption key size used is insufficient 0x010D Error Invalid value size Ox010E Error Very unlikely error OxO10F Error Encrypted link required 0x0110 Error Attribute type is not a supported grouping attribute Ox0111 Error Encrypted link required 0x0112 Error Reserved for Future Use range 1 begin 0x017F Error Reserved for Future Use range 1 end 0x0180 Error Application range begin 0x019F Error Application range end 0x0140 Error Reserved for Future Use range 2 begin OxO1LDF Error Reserved for Future Use range 2 end OxO1EO Error Reserved for Future Use range 3 begin OxO1LFC Error Reserved for Future Use range 3 end OxOLFD Common Profile and Service Error Client Characteristic Configuration Descriptor improperly configured OxO1LFE Common Profile and Service Error Procedure Already in Progress OxOLFF Common Profile and Service Error Out Of Range BLEGATTCWRITE connHnd1I attrHndl atirDataS A typical pseudo code for writing to an attribute which will result in the EVATTRWRITE event message and typically is as follows Americas 1 800 492 2320 Option 2 146 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Register a handle
226. plied in BleGapSvclnit if the nameWritable parameter was 0 otherwise it can be different EVBLEMSG event Is thrown with msgid 21 when the GATT client writes a new value and is the best time to call this function BLEGETDEVICENAMES STRING the current device name in the local GATT table It is the same as that supplied in BleGapSveclnit if the nameWritable parameter was O Bouin otherwise it can be different EVBLEMSG event is thrown with msgid 21 when the GATT client writes a new value Arguments None Interactive No Command Example BleGetDeviceNameS sb See in BL600CodeSnippets zip DiMivceydvchimes Amen tbe appr nce MinC Conni nw MaxGonmlnt Coume le lO sk PRINT n DevName BleGetDeviceName Changing device name manually dvcNmesS My BL600 nmeWrtble 0 apprnce 768 Minconnint 500000 MaxConniInt 1000000 ConnSupTO 4000000 sL 0 re BleGapovelnte avelmes menr tole apernce MinConmine MaxConmink Conmouel sik PRINT n New DevName BleGetDeviceNameS Expected Output DevName LAIRD BL600 New DevName My BL6OO BLEGETDEVICENAMEG is an extension function Americas 1 800 492 2320 Option 2 81 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BleSvcRegDevinfo FUNCTION This function is used to regi
227. port lairdtech com www lairdtech com bl uetooth smart BASIC User Manual Example BleDiscCharFirst Next sb See in BL600CodeSnippets zip Ty Remote server has 1 prim service with 16 bit uuid and 8 characteristics where js unid ere Vo bit land 3 are 128 tout 3 of the 16 bit uuid are the same value OxDEAD and 2 of the 128 bit uuids are also the same 112233445566778899AABBCCDDEEFF lee J Sever Cee e sing Eleea e oll pie e he r Sulo iinvolkecl iin Ooemilice sci deang Nordic Ush Dongle PC10000 DIM ve abs coming and nade A Tr Ar PUNCTION OnStarctup DIM ro Tadre adda a e RoE re pileAdvEpelnie adkpts 2 07 10 Iere O THEN ee BleSscankpelnie sckpts ENDIE IF rc 0 THEN rce BleAdvRptsCommit adRpt scRpt ENDIF Le re 0 TREN re B lekdvertotart 07add gt 50 0 0 ENDIF lopen the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDERUN C size SUB CloseConnections rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx DIM uus CoOmindl nmCrx lt IF nMsgID 1 THEN PRINT n n Disconnected pL ONG 0 ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for first service PRINT n and a characeristic scan will be initiated in the event rc BleDiscServiceFirst con Hndl 0 0 IF rc 0 THEN wait for start and end handles for first primary service
228. provided If it is not called before adverts are started default values are exposed Given this is a mandatory service unlike other services which need to be registered this one must only be initialised as the underlying BLE stack unconditionally registers if when Starting up The a service contains five characteristics as listed at the following site htt developer bluetooth org gatt services Pages ServiceViewer asox U org bluetooth servic e generic access xml BLEGAPSVCINIT deviceName nameWritable nAppearance nMinConninterval nMaxConninterval nSupervisionTout nSlaveLatency INTEGER a result code Bevin Typical value Ox0000 indicates a successful operation Arguments byRef deviceName AS STRING deviceName The name of the device e g Laird_Thermometer to store in the Device Name characteristic of the GAP service Note When an advert report is created using BLEADVRPTINIT this field is read from the service and an attempt is made to append it in the Device Name AD If the name Is too long that function fails to Initialise the advert report and a default name is transmitted It is recommended that the device name submitted in this call be as short as possible byVal nameWritable AS INTEGER nameWritable If non zero the peer device is allowed to write the device name Some profiles allow this to be made optional byVal nAppearance AS INTEGER Field lists the external appearance of the device and updates the
229. r 0x0E exponent 2 unit Ox271A amount concentration mole per cubic metre namespace 0x01 Bluetooth SIG Jl Sie scrine om 90 0000 umkmomwn IF BleCharbescPrstnerme Ox0E 2 0x27 1A 0x01 020000 0 THEN PRINT nPresentation Format Descriptor added ELSE PRINT nPresentation Format Descriptor not added ENDI E Expected Output Americas 1 800 492 2320 Option 2 96 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Char created and User Description A description added Presentation Format Descriptor added BLECHARDESCPRSTNFRMT is an extension function BleCharDescAdd Note This function has a bug for firmware versions prior to 1 4 X Y FUNCTION This function is used to add any Characteristic Descriptor as long as its UUID is not in the range Ox2900 to 0x2904 inclusive as they are treated specially using dedicated API functions For example 0x2904 is the Presentation Format Descriptor and it is catered for by the API function BleCharDescPrstnFrmt Since this function allows existing future defined Descriptors to be added that may or may not have write access or require security requirements a metadata object must be supplied allowing that to be configured BLECHARDESCADD nUuid16 attrS mdDesc INTEGER a result code Reine Typical value 0x0000 indicates a success
230. r that AD element Is returned in this parameter Interactive No Command Example BleAdvGetADbyIndex sb See in BL600CodeSnippets zip DIM Te adlo ado ius NADTIg ADval gt AD with length 6 bytes tag OxDD adio A OCA DDA TI 22 33 44 55 AD with length 7 bytes tag OxDA adZs 07 EE AA BB VCC DD EE VEE cruLllaD S eel ad2 ERTE ew ss e ea aA aa rc BleGetADbyIndex 0 fullADS nADTag ADval IF rc 0 THEN PRINT nFirst AD element with tag Ox INTEGER H nADTag is StrHexizeS ADvalS ELSE PRINTS Wabirorykeadmung AD ein GER on icc ENDIF rc BleGetADbyIndex 1 fullADS nADTag ADval IF rc 0 THEN PRINT nSecond AD element with tag Ox INTEGER H nADTag is We SterHexi1zes Abvals ELSE PRINT A OERO reading Abs INTEGER He LOB Will fail because there are only 2 AD elements rc BleGetADbyIndex 2 fullADS nADTag ADval S IF rc 0 THEN PRINT nThird AD element with tag 0x INTEGER H nADTag is StrHexizeS ADvalS Americas 1 800 492 2320 Option 2 60 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual ELSE PRINT niwror reading AD INTEGER Htc ENDIF Expected Output 06DD11223344550 7 EEAABBCCDDEEFF First AD element with tag 0x000000DD is 1122334455 Second AD element with tag 0x000000EE is AABBCCDDEEFF Error reading AD 00006060 BLEGET
231. r for the EVATTRWRITE event message On EVATTWRITE event message If Gale olatus 0 Chen Attribute was written successfully Else Attribute could not be written Call BleGattcWrite If BleGattcWrite ok then Wait for EVATTRWRITE INTEGER a result code sum Typical value 0x0000 indicates a successful operation Arguments byVal connHndl AS INTEGER This is the connection handle as returned in the on connect event for the connecti connHndl on which the remote Gatt Server can be accessed This will have been returned in the EVBLEMSG event message with msgld 0 and msgCix will have been the connection handle byVal attrHndl AS INTEGER attrHinall The handle for the attribute that is to be written to byRef atirDataS AS STRING attrData The attribute data to write Interactive i Command Example BleGattcWrite sb See in BL600CodeSnippets zip Remote server has 3 prim services with 16 bit uuid First service has one characteristic whose value attribute is at handle 3 and has read write props a Selever Cescicsc a aE E a a a a T O tian a ae eT unng No de Usb Dongle Pelion LIM ao ae e Onn aandaa an PONG RiGN Om Siecnse ito4 DIM ro adore adda seh Dine to PleAdyRotInNit adRot 2 0 10 IF rc 0 THEN rc BleScanRptInit scRpt ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpts scRpt ENDIF TF reo O THEN re BleAdvertStart 0 addrs 50 0 0 2 ENDIF open the gatt client with default notify i
232. racteristic Value Hi Write a new value to the characteristic then enable broadcasting The module will then disconnect and broadcast the new characteristic value Press any key to exit Connected to client New Char Value hello Broadcasts have been enabled by client Diseconnecling es Disconnected from client You should now see the new characteristic value in the advertisment data Dy a hoe Wels ee EVCHARDESC This event is thrown when the client writes to writable descriptor of a characteristic which is not a CCCD or SCCD as they are catered for with their own dedicated messages If comes with two parameters The characteristic handle that was returned when the characteristic was registered using the function BleCharCommit 2 An index into an opaque array of handles managed inside the characteristic handle Both parameters are supplied as is as the first two parameters to the function BleCharDescRead Example EvCharDesc sb See in BL600CodeSnippets zip Americas 1 800 492 2320 Option 2 42 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual DIM BMC har se aes COmmmela Ot iNeicDecsic ts FUNCTION OnStartup DMG lio VG cia peak Din pe acdisc mesChious mlOuNe e 1a wilins sacle wie mae 7 elle eats telat DIM charMet charMet BleAttrMetaData 1 0 20 0 rce Comin eve w
233. rd Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Bits 8 31 Must be Os If nFuncType DIGITAL_OUT Values O Initial output to LOW 1 Initial output to HIGH Output is PWM Pulse Width Modulated Output See function 2 GpioConfigPW for more configuration The duty cycle is set using function Gpiowrite Output is FREQUENCY The frequency Is set using function GpioWrite where O switches off the output any value in range 1 4000000 generates an output signal with 50 duty cycle with that frequency Bits 4 6 output drive capacity O Standard 1 Standard O High 1 Standard O Standard 1 High O High 1 High O Disconnect 1 Standard O Disconnect 1 High 0 Standard 1 Disconnect 7 O High 1 Disconnect If nFuncType ANALOG _IN O Use the system default 10 bit ADC 2 3 scaling 0x13 10 bit ADC 1 3 scaling 0x11 10 bit ADC unity scaling Interactive Command Ne Note The internal reference voltage Is 1 2V with 1 5 accuracy WARNING This subfunc value is global and once changed will apply to all ADC inputs Example GpioSetFunc sb See in Firmware Zip file Americas 1 800 492 2320 Option 2 21 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www la
234. ring at a specified offset into a 32bit integer variable If the offset points beyond the end of the string this function fails BLEDECODE32 attrS nData nindex INTEGER the number of bytes extracted from the attribute string Can be less Returns than the size expected if the nlndex parameter is positioned towards the end of the string Arguments attrs byRef attrS AS STRING This references the attribute string from which the function reads byRef nData AS INTEGER nData This references an integer to be updated with the 3 byte data from attr after sign extension Ind byVal nindex AS INTEGER MNAEX This is the zero based index into the string attr from which data is read If the string Americas 1 800 492 2320 Option 2 174 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual attr is not long enough to accommodate the index plus the number of bytes to read this function fails Interactive No Command Example BleDecode32 sb See in BL600CodeSnippets zip DIM chr bandle vil svenand le inc DIM mdVal mdVal BleAttrMeradata 1 1 50 0 xe DIM aeter arero OO Ol V02 03 04 853587 383897 DIM uuid uuid 0x1853 rc BleServiceNew 1 BleHandleUuidl6 uuid svcHandle rc BleCharNew 0x07 BleHandleUuidl6 0x2A1C mdVal 0 0 rc BleCharCommit svcHandle attrS chrHandle rc BleServiceCommit svcHan
235. ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF EN DEUNe sae SUB Closetonnecrions rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB Americas 1 800 492 2320 Option 2 118 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx DIM uu ConHndl nCex IF nMsgID 1 THEN PRINT n n Disconnected EXITFUNG 0 ELSEIF nMsgID 0 THEN PRINT n Connected so scan remote Gatt Table for ALL services ke BlebiseServicerirse conhndl 0 0 IF rc 0 THEN HandlerPrimSvc will exit with 0 when operation is complete WALTEVENT PRINT nascan for service wich uuid 0 DE AD uHndl BleHandleUuidi6 0xDEAD re BlebiseServicerirst Conima IMOR IF rc 0 THEN HandlerPrimSvc will exit with 0 when operation is complete WALTEVENT Wie 1122334455607 7 609 9AABBCCDDERE HOO PRINT mScane for service with custom uuid uus wus StrDehexizes uus thine Blehandlevurdil2 3 uus nei Blebieeservyicerirser Cconumdl 07 unmel IF rc 0 THEN HandlerPrimSvc will exit with 0 when operation is complete WALTEVENT BNDIE EADIE ENDIE CloseConnections ENDIF ENDEUNG 1 asnesssassss2 55525555255 5555 5555555555555 55 5555559555555 5 555555555 555555555 5 EVDISCPRIMSVC event handler 5555559555555 5 555 55555555555 5 BUNCTION
236. ristics Pages CharacteristicsHome dspx YOu should note that these descriptors are also assigned 16 bit UUIDs value Ox2Axx and are referenced in some of the API functions described in this section Custom Characteristics will have 128 bit 16 byte UUIDs and API functions are provided to handle those too Note If you intend to create a custom Service or Characteristic and adopt the recommendation stated above of a single long 16 byte base UUID so that the service can be identified using a 2 byte UUID then allocate a 16 bit value which is not Americas 1 800 492 2320 Option 2 14 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual going to coincide with any adopted values to minimise confusion Selecting a similar value is possible and legal given that the base UUID Is different The recommendation is just for ease of maintenance Finally having prepared a background to Services and Characteristics the rest of this introduction will focus on the specifics of how to create and manage a GATT table from a perspective of the smart BASIC API functions in the module Recall that a Service has been described as a carrier bag that groups related characteristics together and a Characteristic is just a data container pot Therefore a remote GATT Client looking at the Server which is presented in your GATT table sees multiple carr
237. rnnrnnrnnrnnrrnrrnrrnrrurrnnrnnrnnrnnrnnrnnne 18 Miscellaneous Routines ccccccsseccccesececeesececeuscccsesececeusececeueceesuaececcuececsueceesunecessunecessusecesenecessuneceeseeeesenecetsenecets 18 mod OU WATS aOR OUI INES cae ace cet cree ccsmorstaceuesssesanstunbootosasaanedanetaussaseunastanheederssanavetathtaucsssaunastaneeadetasanavctsen 19 5 BLE Extensions Bult I ROUDIMGS a csscccssnasetesscasntesicacncteaeacates E E 30 VCC SS Sire cere a setve Sere stairere datas cicaitaciawns cvs eintsteasb a aadye data E A A 30 FE VES SGI Seg SS tg E E Seneca EE E E E E E enon opt oases baci een oar E E Tees 31 Miscelaneos FUNCOMS stcretat eatoceeteaee therein E E n Pon tance saps tienen aioe E aetna toa aa ea noe eneaeaeeenenetenneanae 47 AOV SAE FONE WIONIS aeaea aa E EEE E E 50 Connection UNC TONS caattciensuhsacciswst talrcanctnesaisin a caumautanosaannsdairueethuctalanninkanmaiieanousensnhelnnanttacitacsmsonsainantianssdclesanshincdesancenaaeden 63 Security Manager FUNCTIONS cccccscccssccesecneecceecceeeeeeeeeeeeeeeeeseeeeeeeeeeeeseeeeeeeeeeeeeeeeeeeeeeeeeseeeseeeeeueeneeeseueeeusenaeeseneeaaees 68 GT SEV OG FUNC HOW e A E A AA A A EN 72 GAT WEE FONCION arinrin E E EE E 111 Attribute Encode FUNCHONS ogres arai E E E E E 156 Attribute D coaine FUNCUONS cncsscsvsaaccsciencitencsanmatapnessiaiividescuesuwal E E T 167 Parine Bondine UCU OIN SececececececeuemnccatCoueeiceuaorssedemoteseumencanhdcmensamusnetecestmeteneusentanestmeisuenaneta
238. rom index 0 in new char value New Descriptor Data 4C61697264 gt Length 5 Descriptor UULD Feule 399 BEML Cin esa BLECHARDESCREAD is an extension function Americas 1 800 492 2320 Option 2 110 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual GATT Client Functions This section describes all functions related to GATT Client capability which enables interaction with GATT servers at the other end of the BLE connection The Bluetooth Specification 4 0 and newer allows for a device to be a GATT server and or GATT Client simultaneously and the fact that a peripheral mode device accepts a connection and in all use cases has a GATT server table does not preclude it from interacting with a GATT table in the central role device which is connected to it These GATT Client functions allow the developer to discover services characteristics and descriptors read and write to characteristics and descriptors and handle either notifications or indications To interact with a remote GATT server it is important to have a good understanding of how it is constructed and the best way Is to see it as a table consisting of many rows and 3 visible columns handle type value and at least one more column which is not visible but the content will affect access to the data column 16 bit Handle Type 16 or 128 bit Value 1 to 512 bytes
239. rom the same source as prior to the disconnection This is analogous to the way that a PC cannot detect such in similar cases The module can present a serial port service in the local GATT Table consisting of two mandatory characteristics and two optional characteristics One mandatory characteristic is the TX FIFO and the other is the RX FIFO both consisting of an attribute taking Up to 20 bytes Of the optional characteristics one is the Modemin which consists of a single byte and only bit O is used as a CTS Americas 1 800 492 2320 Option 2 184 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual type function The other is ModemOuTt also a single byte which is notifiable only and Is used to convey an RTS flag to the client By default configurable via AT CFG 112 Laird s serial port service is exposed with UUID s as follows The UUID of the service Is 569a1101 b87 490c 92cb 1llbad5ea5l1l67c The UUID of the rx fifo characteristic Is 569a2001 b87 490c 92cbh 1lba5ea5l1l67c The UUID of the tx fifo characteristic is 569a2000 b87 490c 92cbh 1llbad5ea5l1l67c The UUID of the ModemlIn characteristic is 569a2003 b87 490c 92cbh 1llba5ea5l167c The UUID of the ModemoOut characteristic is 569a2002 b87 490c 92ch l1lbab5ea5l67c Note Laird s Base 128bit UUID Is 569aXXXX b87 490c 92cb 1lba5ea5167c where XXXX is a
240. s byVal nEventNum INTEGER The GPIO event number in the range of 0 N which results in the event PEVENINURI EVDETECTCHANn being thrown to the smart BASIC runtime engine Note A value of 0 Is only valid for the BL600 nSigNum byVal nSigNum INTEGER The signal number as stated in the pinout table of the module byVal nPolarity INTEGER States the transition as follows 0 Low to high transition nPolarity sp 1 High to low transition 2 Either a low to high or high to low transition Note This is not available in the BL600 module Interactive NO Command Example GpioAssignEvent sb See in Firmware Zip file FUNCTION BtnOPress PRINT nHel lo ENDFUNC O Americas 1 800 492 2320 Option 2 217 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual PRINT GpioAssignEvent 0 16 1 Assign event 0 to high low transition on siol ott om ONEVENT EVDETECTCHANO CALL BtnOPress When event 0 is detected call BtnOPress PRINT Vnbrees buccon 0 WALTEVENT Expected Output O Press button 0 Hello GPIOASSIGNEVENT is a Module function GpioUnAssignEvent FUNCTION This routine unassigns the runtime engine event from a level transition assigned using GpioAssignEvent GPIOUNASSIGNEVENT nEventNum INTEGER a result code Berne Typical value 0x0000 indicates a successful Operation Arguments nEvent
241. s already open or how many bytes are waiting in the receive buffer to be read BLEVSPINFO infold Returns INTEGER The value associated with the type of UART information requested Local Stack Frame Underflow E ti meee ee Local Stack Frame Overflow Arguments byVal infold AS INTEGER This soecifies the information type requested as follows if the port is open O 0 if closed 1 if open 3 if open and there is a BLE connection and 7 if the transmit fifo characteristic CCCD has been updated by the infold Client to enable notifies or indications Receive ring buffer capacity 2 Transmit ring buffer capacity 3 Number of bytes waiting to be read from receive ring buffer 4 Free space available in transmit ring buffer Eee BLEVSPOPEN BLEVSPCLOSE BLEVSPWRITE BLEVSPREAD BLEVSPFLUSH Commands Interactive No Command Americas 1 800 492 2320 Option 2 192 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Example BleVspInfo sb See in BL600CodeSnippets zip DIM ANGL LG fQ lose VSP If it as Open BleVSpClose re Blevspopen 176 02870 nnd PRINT ovico otatte Blevsoilmro PRINT AnP buffer capacity T Blevsoinko 1 PRINT nT butter Capacity gt Blev opno PRINT nBytes waliting to be read from rx bufler gt BileVoolnie 3 PRINT nPree space am tx butter BlevSpinto 4 BleVspClose
242. s an extension function BleGetADbylndex FUNCTION This function is used to extract a copy of the nth zero based advertising data AD element from a string which is assumed to contain the data portion of an advert report incoming or outgoing Note Ifthe last AD element is malformed it will be treated as not existing For example it will be malformed if the length byte for that AD element suggests that more data bytes are required than actually exist in the report string Americas 1 800 492 2320 Option 2 59 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual BLEGETADBYINDEX nIndex rptDataS nADtag ADvalS INTEGER a result code Benin Typical value 0x0000 indicates a successful Operation Arguments byVAL nindex AS INTEGER nindex This is a zero based index of the AD element that will be copied into the output data parameter ADval byREF rptDataS AS STRING This parameter is a string that contains concatenated AD elements which will rptDatas have been either constructed for an outgoing advert or will have been received in a scan depends on module variant byREF nADTag AS INTEGER nADTag When the nth index is found the single byte tag value for that AD element is returned in this parameter byREF ADvalS AS STRING ADval S When the nth index is found the data excluding single byte the tag value fo
243. s open n ELSE PRINT het lune OnStarkup Americas 1 800 492 2320 Option 2 148 Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Laird Technologies smart BASIC User Manual ENDIF WALTEVENT PRINTO olde ICI ng ean Expected Output Advertising and Gatt Client is open Connected so read attibute handle 3 EVATTRWRITE cHndl 2687 attrHndl 3 status 00000000 Attribute write OK Write to attibute handle 300 which does not exist EVATTRWRITE cHndl 2687 attrHndl 300 status 00000101 Failed to write attribute Disconnected Fo LG ye BLEGATTCWRITE Is an extension function BleGattcWriteCmd FUNCTION If the handle for an attribute is known then this function is used to write into an attribute at offset Owhen no acknowledgment response is expected The signal that the command has actually been transmitted and that the remote link layer has acknowledged Is by the EVNOTIFYBUF event Note that the acknowledgement received for the BleGattcWrite command is from the higher level GATT layer not to be confused with the link layer ack in this case All packets are acknowledged at link layer level If a packet fails to get through then that condition will manifest as a connection drop due fo the link supervision timeout Given that the transmission and link layer ack of this write operation is indicated in an event message a handler must be registered for the E
244. s outside that range it is ignored Set the value to 1 to have it ignored and then all further UUID arguments will also be ignored byVal uuid3 AS INTEGER UUID in the range O to FFFF if the value is outside that range it Is ignored Set the value to 1 to have it ignored and then all further UUID arguments will also be ignored byVal uuid4 AS INTEGER UUID in the range O to FFFF if the value is outside that range it Is ignored Set the value to 1 to have it ignored and then all further UUID arguments will also be ignored byVal uuid5 AS INTEGER UUID in the range O to FFFF if the value is outside that range it is ignored Set the value to 1 to have it ignored and then all further UUID arguments will also be ignored byVal uuid AS INTEGER Uuid UUID in the range 0 to FFFF if the value Is outside that range it is ignored Set the value to 1 to have if ignored AdvRpt Uuid1 Uuid2 Uuid3 Uuid4 Uuid5 Interactive No Command Example BleAdvAddUuidl6 sb See in BL600CodeSnippets zip DIM adyRpLU yiae DIM discovMode discovMode 0 DIM advAppearance advAppearance 1 DIM maxDevName maxDevName 10 rc BleAdvRptInit advRpt discovMode advAppearance maxDevName BatteryService 0x180F DEVE Ionics Sows O SON Ie BicAdvkprAdavuidlo adk tS Uxle0r OxI n T al i 1 O TREN PRINTE a0 Service List AD added BND Only the battery and device information services are included in the advert repor
245. so that the least significant byte is at the lower memory address Note The range is not 2048 because after encoding the following two byte values have special meaning OxO7FFFFFF NaN Not a Number OxO8000000 NRes Not at this resolution OxO7FFFFFE INFINITY Ox08000002 INFINITY Ox0800000 Reserved for future use byVal nExponent AS INTEGER This value must be in the range 128 to 127 or the function fails byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data is nindex written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails nMatissa nExponent Interactive No Command Example BleEncodeFloat sb See in BL600CodeSnippets zip Dive DIM attrS attrg V7 wrLice 1234567 x 10 54 as FLOAT cto index 2 PRINT BleEncodeFLOAT attr 123456 54 0 i Wel e le SASG x Os Too ae T LOR to nee e and aae w pen because the exponent is too large it has to be lt 127 Americas 1 800 492 2320 Option 2 161 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual if BlebmeoderPLOAT atiro 1234567 1000 2 0 THEN PRINT nFailed to encode to FLOAT ENDIF jiweiee 1000000
246. st byte is OO 4 for IEEE public address and 01 for random public address Next six bytes are the address A random public address unique to this module May be the same value as In 4 above unless AT MAC was used to set an IEEE mac address It is seven bytes long First byte is OO for IEEE public address and 01 for random public address Next six bytes are the address Interactive Command oe Example SysInfo sb See in Firmware Zip file PRs Wiss ios 4 PRINT nevycoime or 4 PRINT nSysInfo 0 LSS INPRO 1 J acres On neee SCS NBOs 4 soul luce wancdem adde No SYSINEOS 0 Exoected Output SysiInfos 4 O1 FA 84 D7H D9 03 SysiInfos 14 O1L FA 84 D7H D9 03 Sysinice 0 SYSINFOS is a core language function Americas 1 800 492 2320 Option 2 14 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual UART Universal Asynchronous Receive Transmit UartOpen FUNCTION This function is used to open the main default uart peripheral using the parameters specified See core manual for further details UARTOPEN baudrate txbuflen rxbuflen stOptions byVal stOptions AS STRING This string can be a constant MUST be exactly 5 characters long where each character is used to specify further comms parameters as follows Character Offset DTE DCE role request O T DITE C DCE Parity stOptions
247. ster the Device Information service with the GATT server The Device Information service contains nine characteristics as listed at the following website http developer bluetooth org gatt services Pages Service Viewer asox U org bluetooth servic e device information xml The firmware revision string will always be set to BL600 vW X Y Z where W X Y Z are as per the revision information which is returned to the command AT 4 BLESVCREGDEVINFO manfNameS modelNumS serialNumS hwRevsS swRevs sysldS regDataListS pnpld FUNCTION INTEGER a result code Returns neee Typical value 0x0000 indicates a successful operation Arguments maniNawes byVal manfNameS AS STRING The device manufacturer Can be set empty to omit submission miodeiNums byVal modelNumS AS STRING The device model number Can be set empty to omit submission serialNum byVal seriaINumS AS STRING ad The device serial number Can be set empty to omit submission hwRevs byVal hwRevs AS STRING The device hardware revision string Can be set empty to omit submission swRev byVal swRevS AS STRING The device software revision string Can be set empty to omit submission byValsysidS AS STRING The device system ID as defined in the specifications Can be set empty to omit submission Otherwise it shall be a string exactly 8 octets long where Byte 0 4 Manufacturer Identifier sysld Byte 5 7 Organisationally Unique Identifier For the sp
248. stic is stored in a Value attribute a byte array Multibyte Characteristic Descriptors content are stored similarly Those bytes are manipulated in smartBASIC applications using STRING variables Attioute data is stored in little endian format This section describes decoding functions that allow attribute strings to be read trom smaller bytewise subfields more efficiently than the generic STRXXXX functions that are made available in smart BASIC Please note that CCCD and SCCD Descriptors are special cases as they are defined as having just 2 bytes which are treated as 16 bit integers mapped to INTEGER variables in smartBASIC BleDecodeS8 FUNCTION This function reads a single byte in a string at a specified offset into a 32bit integer variable with sign extension If the offset points beyond the end of the string then this function fails and returns Zero BLEDECODESS8 attrS nData nindex Returns INTEGER a result code Americas 1 800 492 2320 Option 2 167 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Typical value 0x0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This references the attribute string from which the function reads byRef nData AS INTEGER nData This references an integer to be updated with the 8 bit data from attr after sign extension byVal nindex AS INTEGER Th
249. sult code Ret ar l lia Typical value 0x0000 indicates a successful operation Arguments atirS byRef attr AS STRING Americas 1 800 492 2320 Option 2 164 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This argument is the string that is written to an attribute byRef timestampS AS STRING timestampsS This is an exactly 7 byte string as described above For example 5 May 2013 10 31 24 is entered 14 O0D 05 05 0A 1F 18 byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data is written If the string attr is not long enough to accommodate the index plus NAEK the length of the fragment it is extended If the new length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function fails Interactive Ne Command Example BleEncodeTimestamp sb See in BL600CodeSnippets zip DIM COS DIM attrS attrg write the timestamp lt 5 May 2013 10 31 24 gt too la UD O 05 0A le ie PRINT BleEncodeTimestamp attrs tsS 0 Expected Output BLEENCODETIMESTAMP is an extension function BleEncodeSTRING FUNCTION This function overwrites a substring at a specified offset with data trom another substring of a string If the destination string is not long enough it is extended with the new block uninitialized Then the byte is overwritt
250. t INTEGER a result code Sen Typical value 0x0000 indicates a successful operation Arguments byRef advRpts AS STRING GAVRPIS This contains an advert scan report Interactive No Command dm ce 3 Clas rc BleScanRptInit s dns BleGetDeviceNameS Add device name to scan report rc BleAdvRptAppendAD ss 0x09 dn print nFree space in scan report BleAdvRptGetSpace s bytes Expected Output Free space in scan report 18 bytes BLESCANRPTINIT is an extension function BleAdvRptAddUuid16 FUNCTION This function is used to add a 16 bit UUID service list AD Advertising record to the advert report This consists of all of the 16 bit service UUIDs that the device supports as a server BLEADVRPTADDUUID16 advRpt nUvid1 nUvid2 nUvid3 nUuid4 nUuid5 nUuid Returns INTEGER a result code Americas 1 800 492 2320 Option 2 56 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Typical value 0x0000 indicates a successful operation Arguments byRef AdvRpt AS STRING The advert report onto which the 16 bit uuids AD record is added byVal uuid AS INTEGER UUID in the range O to FFFF if the value is outside that range it is ignored Set the value to 1 to have it ignored and then all further UUID arguments will also be ignored byVal uuid2 AS INTEGER UUID in the range O to FFFF if the value i
251. t Expected Output Americas 1 800 492 2320 Option 2 57 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual UUID Service List AD added BLEADVRPTADDUUID16 is an extension function BleAdvRptAddUuid128 FUNCTION This function is used to add a 128 bit UUID service list AD Advertising record to the advert report specified Given that an advert can have a maximum of only 31 bytes if is not possible to have a full UUID list unless there is only one to advertise BLEADVRPTADDUUID128 advRpt nUvidHandle INTEGER a result code Serm Typical value 0x0000 indicates a successful operation Arguments dvRot byRef AdvRpt AS STRING GaVNP The advert report into which the 128 bit uuid AD record is to be added byVal nUvidHandle AS INTEGER nUvidHandle This is handle to a 128 bit uuid which was obtained using the function j BleHandleUuid128 or some other function which returns one such as BleVSpOpen Interactive No Command Example BleAdvAddUuid128 sb See in BL600CodeSnippets zip DIEM SS e OPPE r aclisjos evelcies 5 aa SCRpL Y PRINT Blescankorlnib SCRE Open the VSP PRINT BleVspOpen 128 126 0 And Advertise the VSPservice in a scan report PRINT BleAdvRptAddUuid128 scRpts hnd1 adRpt PRINT BleAdvRptsCommit adRpt scRpt addrS because we are not doing a DIRECT advert PRINT EBl
252. t attr mantissa exp 2 0 THEN PRINT nFailed to encode to SFLOAT ELSE PRINT nSsuccesc ENDIF ENDSUB Encodel l2 4 1 1234 x IO Encode ik TO 1234 x 10 10 will fail because exponent too large Encode 10000 0 10000 x 10 0 will fail because mantissa too large Expected Output Success Failed to encode to SFLOAT Failed to encode to SFLOAT BLEENCODESFLOAT is an extension function BleEncodeTIMESTAMP FUNCTION This function overwrites a seven byte string into the string at a specified offset If the string is not long enough it is extended with the new extended block uninitialized and then the byte specified is overwritten The seven byte string consists of a byte each for century year month day hour minute and second If year month Is zero it is taken as not noted year and all the other fields are set zero not noted For example 5 May 2013 10 31 24 will be represented as 14 0D 05 05 0A 1F 18 If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum length of an attribute as implemented can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 Note When the attr string variable is updated the two byte year field is converted into a 16 bit integer Hence 14 0D gets converted to DD 07 BLEENCODETIMESTAMP atirS timestamps nlndex INTEGER a re
253. t handle hval PRINE nSean for ALL Desce cValAttr hVal re BleDisecDesecrirst conknelll 0 cvalatrtr IF rec 0 THEN PRINT nScan descriptors failed op I OIE 10 ENDIF ENDL endfunc 1 Americas 1 800 492 2320 Option 2 130 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual J4 EVDISCDESC event hancler tunction HandlerDescDisc cHmdily cUuid handl as Integer Prints aV S OERS PLint Venn Cn print adscuurd 1mteger hn cUuid Print Fasehmal gt timed IF ancl O THEN PRINT nDescriptor Scan complete EXITFUNG 0 BLSE rc BleDiscDescNext cHndl IP cec 0 THEN PRINT Y nDescriptor scan abort EXITFUNG 0 ENDIF ENDIF endrunce 1 feoeaassesssaassssssasssesssssss5 M Main equivalent faaeessa sess sss 3 555555555 aaa ONEVENT EVBLEMSG CALL HndlrBleMsg OnEveme RYVDLSCPRIMSVC call HandlerPrimSvc OnEvenr EVDISCCHAR call HandlerCharDisc OnE vent EVDISCDESC Call HandlerbesecDise Register base uuids with the underlying stack otherwise the services with the 128bit uuid s will be delivered with a uuid handle FFO00000 UNKNOWN one SM eS SAPS BGG 7 5 3 SVN SIO ID Da slo 00 uuidS StrDehexizesS uuids uHndl BleHandleUuidl28 uuids ones 1122DEAD5566778899PAABBCCDDBEBEOO uuLd S StrreDehexizes uudis uHndl BleHandleUuidl28 uuid Ie OnStartup
254. t tab gt optional_verbose_explanation will be missing in resource constrained platforms like the BL600 modules The verbose explanation is a constant string and since there are over 1000 error codes these verbose strings can occupy more than ten kilobytes of flash memory The hex number in the response is the error result code consisting of two digits which can be used to help investigate the problem causing the failure Rather than provide a list of all the error codes in this manual you can use UWTerminal to obtain a verbose description of an error when it is not provided on a platform To get the verbose description click on the BASIC tab in UWTerminal and if the error value is hhhh enter the command ER Oxhhhh and note the Ox prefix to hhhh This is illustrated in Figure 2 ite Ee Terminal BASIC Contig About CTS DSA CCO Fie ma UwTerminal v6 22 GENERIC FAIL COMS9 9600 N 8 1 icr COMMAND Tx 39 71 Rx 2428 Figure 2 Optional verbose explanation You can also obtain a verbose description of an error by highlighting the error value right clicking and selecting Lookup Selected ErrorCode in the Terminal window If you get the text UNKNOWN RESULT CODE OxHHHH please contact Laird for the latest version of UWterminal The following are BL600 specific AT commands AT CFG COMMAND AI CFG Is used to set a non volatile configuration key Configuration keys are are comparable to S registers in m
255. taS AS STRING The attribute data to write attrHndl attrDataS Interactive Command ne Example BleGattcWriteCmd sb See in BL600CodeSnippets zip aA Remote server has 3 prim services with 16 bit uuid First service has one characteristic whose value attribute is at handle 3 and has read write props fy i Seicver cescirec Using BileGanieWoliieliceCmel Sully slinvolkecl iin _Clocidilicis sei j 7 Werng Nordic ich Dongle e 00Ge DIM se 7 eco eonna unnd abled PUNeETICN POnsbaneue DIM Tee adkor m addr y Selves re BleAdvRpEIni amp adRpio 2 0 10 IE re 0 THEN re BleScankoc init ScRets ENDIF IF rc 0 THEN rc BleAdvRptsCommit adRpts scRpt ENDIF te re 0 THEN re BleAdVvVertStare U0 addrs 50 0 0 gt ENDIF open the gatt client with default notify indicate ring buffer size IF rc 0 THEN re BleGattcOpen 0 0 ENDIF ENDEUNG re SUB CloseConnections Americas 1 800 492 2320 Option 2 150 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual rc BleDisconnect conHnd1 rc BleAdvertStop ENDSUB FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx DIM uHndA conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected CPU 10 ELSEIF nMsgID 0 THEN PRINT n Connected so write to attribute handle 3 atHndl 3 aoe Ol so 04 rc BleGattcWriteCmd conHndl atHndl at
256. tarctup DIM ice oe ees a e ado adda a ae E Ha Din m eoe ma aea E REA e a aa ie ln a EE Me a e por ea Commit sve With handle ih yv u rc BleServiceNew 1 BleHandleUuidl6 0x18EE hSvc initialise char write read enabled accept signed writes notifiable rc BleCharNew 0x22 BleHandleUuidl6 1 BleAttrMetaData 1 0 20 0 rc mdCccd 0 commit char initialised above with initial value hi to service hMyChar rc BleCharCommit hSvc attrs hMyChar commit changes to service Americas 1 800 492 2320 Option 2 106 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual eC B leservyuceConmait Nove rc BleScanRptInit scRpt s Add 1 service handle to scan report PCP ATEOA T UUT de Seige liSwie i e all commit reports to GATT table adRpt S is empty rc BleAdvRptsCommit adRpt scRpts CC BILA Tvert Core O addres 50 00 PNP UNC ace FUNCTION HndlrBleMsg BYVAL nMsgId BYVAL nCtx conHndl nCtx IF nMsgID 1 THEN PRINT n n Disconnected from client EXITFUNG Q ELSEIF nMsgID 0 THEN PRINT n Connected to client ENDIF ENDEUNC al a e i 7 CCCD descriptor written handler OF a aaa aaa aaa FUNCTION HndlrCharGecd BYVAL ehanan BYVAL nvVali DIM values IF charHandle hMyChar THEN Pies Wace CD vals nyval Ie nyal THEN PRINT Indications have been enabled by client value hello rc BleCharValueI
257. tcFindDesc returned a success The message contains 2 INTEGER parameters Connection Handle Handle of the Descriptor If the specified instance of the service characteristic descriptor is not present in the remote Gatt Server Table then all parameters will contain O apart from the Connection Handle Handle of the Descriptor is the handle for the descriptor and is the value to store to keep track of important descriptors in a gatt server for later read write operations for example CCCD s to enable notifications and or indications BLEGATTCFINDDESC connHndl svcUuHndl svcldx charUuHndl charldx descUuHndl descldx A typical pseudo code for finding a descrirpotor involves calling BleGattcFindDesc which in turn will result in the EVFINDDESC event message and typically is as follows Americas 1 800 492 2320 Option 2 137 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Register a handler for the EVFINDDESC event message On EVFINDDESC event message If Descriptor Handle 0 then Descriptor not found Else Descriptor has been found Call BleGattcFindDesc If BleGattcFindDesc ok then Wait for EVFINDDESC INTEGER a result code Typical value 0x0000 Returns Indicates a successful operation and means an EVFINDDESC event message WILL be thrown by the smartBASIC runtime engine containing the results A non zer
258. tech com bluetooth smart BASIC User Manual Further note that if a service has INCLUDED services then they shall be installed in the GATT table immediately after a Service is created using BlesvcCommit and before BleCharCommit The BT 4 0 specification mandates that any included service attribute be present before any characteristic attributes within a particular service group declaration BleSvcAddincludeSvc hService INTEGER a result code ti Typical value 0x0000 indicates a successful operation Arguments byVal hService AS INTEGER hService This argument will contain a handle that was previously created using the functiol BleSvcCommiit Interactive No Command Example BleSvcAddIncludeSvc sb See in BL600CodeSnippets zip define BLE SERVICE SECONDARY O define BRE oth Een PRIMARY 1 aaa a a A eee A SE a ae ee dim Mbaeove composite handle for batteru primary service dim re or we could have reused nHtsSvc dim metaSuccess DIM charMet charMet BleAttrMetaData 1 1 10 1 metaSuccess DIM ss s gt Hello initial value of char in Battery Service DIM hBatChar te PIE ery ee Nen ELER ERVI CEE EC ONDAR Te Cand ura OBa rc BleCharNew 3 BleHandleUuidl Ox2A1C charMet 0 0 be BilkeChaerConmie mBartsve so 7 ibarchar re BleServiceCommit hBatSvc DIM NACS sve composite handle for hts primary service EG AS BIE era een EEE ERV EERE MAR T E Ean eaa O EO H Swe BleServiceCommit
259. th smart BASIC User Manual BLEDECODEBITS is an extension function Pairing Bonding Functions This section describes all functions related to the pairing and bonding manager which manages trusted devices The database stores information like the address of the trusted device along with the security keys At the time of writing this manual a maximum of 4 devices can be stored in the database The command AT 2012 or at runtime SYSINFO 2012 returns the maximum number of devices that can be saved in the database The type of information that can be stored for a trusted device Is The MAC address of the trusted device The eDIV and eRAND for the long term key A 16 byte Long Term Key LTK The size of the long term key A flag fo indictate if the LTK is authenticated Man In The Middle MITM protection A 16 byte Indentity Resolving Key IRK A 16 byte Connection Signature Resolving Key CSRK Whisper Mode Pairing BLE provides for simple secure pairing with or without man in the middle attack protection To enhance security while a pairing is in progress the specification has provided for Out of Band pairing where the shared secret information is exchanged by means other than the Bluetooth connection That mode of pairing is currently not exposed Laird have provided an additional mechanism for bonding using the standard inbuilt simple secure pairing which is called Whisper Mode pairing In this mode when a p
260. th the underlying stack otherwise the services with the 128bit uuid s will be delivered with a uuid handle FFO0O0000 UNKNOWN uuid WIL Pe SS Eig 33 Seve eC IP DA ene OO uuids StrDehexizes uuids uHndl BleHandleUuidl128 uuid s uudis 1122DEAD55667789899PABBCCDDBEBE OO uuidsS StrDehexizeS uuids uHndl BleHandleUuidl28 uuid TERON Cor Up O THEN PRINT nAdvertising and Gatt Client is open n ELSE PRINT iP emiuirerOnsterrue ENDIF WALTEVENT PRITS AAE ICINE Expected Output Americas 1 800 492 2320 Option 2 140 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth Advertising and Gatt Client is open Connected so scan remote Gatt Table for ALL services EVFINDDESC cHnd1l 1106 dscHndl 37 Found the descriptor at handle 37 Svc Idx 2 Char Idx 1 desc Idx 1 EVFINDDESC cHnd1l 1106 dscHndl 0 Did NOT find the descriptor Disconnected EXITING a BLEGATTCFINDDESC is an extension function BleGattcRead BleGattcReadData FUNCTIONS If the handle for an attribute is Known then these functions are used to read the content of that attribute from a specified offset in the array of octets in that attribute value Given that the success or failure of this read operation is returned in an event message a handler must be registered for the EVATTRREAD event Depending on the connection interval the read of the
261. the pot comes with space to store the data and a set of properties that are officially called Descriptors in the BT spec In the pot analogy think of Descriptor as colour of the pot whether it has a lid whether the lid has a lock or whether it has a handle or a spout etc For a full list of these Descriptors online see hitp developer bluetooth org gatt descriptors Pages DescriptorsHomePage aspx These descriptors are assigned 16 bit UUIDs value 0x29xx and are referenced in some of the smartBASIC API functions if you decide to add those to your characteristic definition To wrap up the loose analogy think of Service as just a carrier bag to hold a group of related Characterisics together where the printing on the carrier bag is a UUID You will find that from a smartBASIC developer s perspective a set of characteristics is what you will need to manage and the concept of Service Is only required at GATT table creation time A GATT table can have many Services each containing one or more Characteristics The differentiation between Services and Characteristics is expedited using an identification number called a UUID Universally Unique Identifier which Is a 128 bit 16 byte number Adopted Services or Characteristics have a 16 bit 2 byte shorthand identifier which is just an offset plus a base 128 bit UUID defined and reserved by the Bluetooth SIG and custom Service or Characteristics shall have the full 128 bit UUID The logic be
262. this software without specific written permission DISCLAIMER This software is provided as is with no explicit or implied warranties in respect of its properties including but not limited to correctness and or fitness for purpose Issue 09 09 2006 This is an AES implementation that uses only 8 bit byte operations on the cipher state there are options to use 32 bit types if available The combination of mix columns and byte substitution used here is based on that developed by Karl Malbrain His contribution is acknowledged Americas 1 800 492 2320 Option 2 206 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual INDEX 7 lt i its i gt lage en ne or ey 10 11 AT MAC cress ceccswucdersbencenasianatascieastnacioosdasnewesds 1 ATFRUN RE 7 BleDecode32 ssssssssrsseresersssrsssrsseersssreseee 174 BleDecodeBIlTS snenssesssesssersssrsssesssersssssses 180 BIEDECOCEFLOAT ou ceeccceessccesscceessceeees 175 BICD SCOG CS 1 6 mssacesincsessnsvecsceaiaraactoevanicondenanees 170 BIEDECOCES 24 wie cceecccsscccesscccsscccessceesssceenes 172 BIEDECOCESFLOAT oo cc eee ceecccesscccesscceessceeees 177 BIEDECOCE STRING 20 2 ce ceceecceesscccsssceessceeees 179 BleDECOCdeTIMESTAMP eeceeeecceeececeesceeees 178 eye 5B O B 0 oarenien 171 BIEDECOMEU2A oii ee ccescccsscceessccesscceessceenes 173 BIEDECOCEU
263. tion BleAdvRptsCommit FUNCTION This function is used to commit one or both advert reports If the string is empty then that report type Is not updated If both strings are empty this call will have no effect The advertisements will not happen until they are started using BleAdvertStart function BLEADVRPTSCOMMIT advRpt scanRpt INTEGER a result code Benin Typical value 0x0000 indicates a successful operation Americas 1 800 492 2320 Option 2 62 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Arguments byRef advRpt AS STRING advRpt The most recent advert report scanRpt byRef scanRpt AS STRING The most recent scan report Note If any one of the two strings is not valid then the call will be aborted without Updating the other report even if this other report is valid Interactive Command RO Example BleAdvRptsCommit sb See in BL600CodeSnippets zip DIM adyvkpE a0vRpito DIN SCRE oc RpL N DIM discovMode discovMode 0 DIM advApprnce advApprnce 1 DIM maxDevName maxDevName 10 PRINT BleAdvRptInit advRpt S discovMode advApprnce maxDevName PRIN EAT cw NClclWaclls ecwmixces Uscl sO Oxi sa i i i i PRY E leAdyRp pto C ommit ady RPE SeRDEOo Only the advert report will be updated Expected Output BLEADVRPTSCOMMIT is an extension function Connection Functions
264. tion overwrites three bytes in a string at a specified offset If the string is not long enough then it will be extended with the new extended block uninitialized and then the bytes specified are overwritten If the nindex is such that the new string length exceeds the maximum attribute length this function fails The maximum attribute length can be obtained using the function SYSINFO n where n is 2013 The Bluetooth specification allows a length between 1 and 512 BLEENCODE24 attrS nData nindex INTEGER a result code cen Typical value 0x0000 indicates a successful operation Arguments attrs byRef attrS AS STRING This argument is the string that will be written to an attribute nDat byVal nData AS INTEGER ara The three least significant bytes of this integer is saved The rest is ignored byVal nindex AS INTEGER This is the zero based index into the string attr where the new fragment of data is amde written If the string attr is not long enough to accommodate the index plus the length of the fragment it is extended If the extended length exceeds the maximum allowable length of an attribute see SYSINFO 2013 this function will fail Interactive No Command Example BleEncode24 sb See in BL600CodeSnippets zip DIM re DIM Maris Miwab bm o lace J weite BCD to index 1 rc BleFncode24 attr 0x444342 1 weite A to index 0 rc BleEncodes attrS 0x41 0 j write EF to index 4 rc BleFncodel6 attr 0x46
265. tised until BLEADVRPTSCOMMIT is called This report is for use with advertisement packets BLEADVRPTINIT advRptS nFlagsAD nAdvAppearance nMaxDevName INTEGER a result code Renin Typical value 0x0000 indicates a successful Operation Arguments byRef advRpts AS STRING advRpt This will contain an advertisement report byVal nFlagsAD AS INTEGER Specifies the flags AD bits where bit O is set for limited discoverability and nFlaasAD bit 1 is set for general discoverability Bit 2 will be forced to 1 and bits 3 amp 4 ags will be forced to 0 Bits 3 to 7 are reserved for future use by the BT SIG and must be set to 0 Note If a whitelist is enabled in the BleAdvertStart function then both Americas 1 800 492 2320 Option 2 54 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Limited and General Discoverability flags MUST be 0 as per the BI 4 0 specification Volume 3 Sections 9 2 3 2 and 9 2 4 2 byVal nAdvAppearance AS INTEGER Determines whether the appearance advert should be added or omitted as follows Omit appearance advert Add appearance advert as specified in the GAP service which Is supplied via the BleGapSveclnit function byVal nMaxDevName AS INTEGER nMaxDevName The n leftmost characters of the device name specified in the GAP service If this value is set to 0 then the device name Is not included
266. tisement not successful EN DE ONEVENT EBVELE ADV TIMEOUT CALN Hnd1lrBleAdvTimOut WAL TEVENT Expected Output Advert Started Advert stopped via timeout EVBLEMSG The BLE subsystem is capable of informing a smart BASIC application when a significant BLE related event has occurred It does this by throwing this message as opposed to an EVENT which is akin to an interrupt and has no context or queue associated with it The message contains two parameters The first parameter subsequently called msgID identifies what event was triggered the second parameter subsequently called msgCtx conveys some context data associated with that event The smart BASIC application must register a handler function which takes two integer arguments to be able to receive and process this message Americas 1 800 492 2320 Option 2 31 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Note The messaging subsystem unlike the event subsystem has a queue associated with it unless the queue Is full all of the messages remain pending until they are handled Only messages that have handlers associated with them get inserted into the queue This is to prevent unhandled messages from filling that queue The following table provides a list of triggers and associated context parameter KR W IND JO 10 1 12 14 15 16 1
267. tten using read write blob requests Americas 1 800 492 2320 Option 2 141 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 0x010C ATT Error Encryption key size used is insufficient OxO10D ATT Error Invalid value size OxO10E ATT Error Very unlikely error OxO10F ATT Error Encrypted link required Ox0110 ATT Error Attribute type is not a supported grouping attribute OxO111 ATT Error Encrypted link required Ox0112 ATT Error Reserved for Future Use range 1 begin OxO17F ATT Error Reserved for Future Use range 1 end Ox0180 ATT Error Application range begin 0x019F ATT Error Application range end 0x01A0 ATT Error Reserved for Future Use range 2 begin OxO1DF ATT Error Reserved for Future Use range 2 end OxO1EO ATT Error Reserved for Future Use range 3 begin OxO1FC ATT Error Reserved for Future Use range 3 end OxO1FD ATT Common Profile and Service Error Client Characteristic Configuration Descriptor CCCD improperly configured OxO1FE ATT Common Profile and Service Error Procedure Already in Progress OxO1FF ATT Common Profile and Service Error Out Of Range BLEGATTCREAD connHnd1I attrHndl offset A typical pseudo code for reading the content of an attribute calling BleGattcRead which in turn will result in the EVATTRREAD event message and typically is as follows Register a handler for the EV
268. ue Hi You can connect and write to the CCCD characteristic The BL600 will then indicate a new characteristic value Connected to client CCCD Val 0 Indications have been disabled by client CCCD Val 2 Indications have been enabled by client Successful indication of new value Got confirmation of recent indication PALCI BLECHARV ALUEINDICATE is an extension function BleCharDescRead FUNCTION This function reads the current content of a writable Characteristic Descriptor identified by the two parameters supplied in the EVCHARDESC event message after a Gatt Client writes to it In most cases a local read is performed when a GATT client writes to a characteristic descriptor attribute The write event is presented asynchronously to the smart BASIC application in the form of an EVCHARDESC event and so this function is most offen accessed from the handler that services that event BLECHARDESCREAD charHandle nDescHandle nOffset nLength nDescUvidHandle atirS INTEGER a result code Betis Typical value 0x0000 indicates a successful operation Arguments byVal charHandle AS INTEGER charHandle This is the handle to the characteristic whose descriptor must be read which was returned when BleCharCommit was called and will have been supplie Americas 1 800 492 2320 Option 2 108 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth sm
269. unctions and subroutines 43 The size of stack for storing user functions simple variables 44 The size of stack for storing user functions complex variables 45 The size of the message argument queue length 100 Enable Disable Virtual Serial Port Service when in interactive mode Valid values are Ox0000 Disable Ox000 1 Enable Ox80nn Enable ONLY if signal pin nn on module is HIGH OxCOnn Enable ONLY if signal pin nn on module is LOW Ox81nn Enable ONLY if signal pin nn on module is HIGH and auto bridged to UART when connected OxC Inn Enable ONLY if signal pin nn on module is LOW and auto bridged to UART when connected ELSE Disable 101 Virtual Serial Port Service to use INDICATE or NOTIFY to send data to client O Prefer Notify Else Prefer Indicate This is a preference and the actual value is forced by the property of the TX characteristic of the service 102 This is the advert interval in milliseconds when advertising for connections in interactive mode and AT parse mode Valid values 20 to 10240 milliseconds 103 This is the advert timeout in milliseconds when advertising for connections in interactive mode and AT parse mode Valid values 1 to 16383 seconds Americas 1 800 492 2320 Option 2 8 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 104 105 106 107 108 109 110 111 112 11
270. ure of this write operation is returned in an event message a handler must be registered for the EVATTRWRITE event Depending on the connection interval the write to the attribute may take many 100s of milliseconds and while this is in progress it is safe to do other non Gatt related operations like for example servicing sensors and displays or any of the onboard peripherals EVATTRWRITE event message Americas 1 800 492 2320 Option 2 145 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual This event message WILL be thrown if BleGattcWrite returns a success The message contains 3 INTEGER parameters Connection Handle Handle of the Attribute Gatt status of the write operation Gatt status of the write operation is one of the following values where 0 implies the write was successfully expedited Ox0000 Success 0x0001 Unknown or not applicable status 0x0100 ATT Error Invalid Error Code 0x0101 ATT Error Invalid Attribute Handle Ox0102 ATT Error Read not permitted Ox0103 ATT Error Write not permitted Ox0104 ATT Error Used in ATT as Invalid PDU Ox0105 ATT Error Authenticated link required Ox0106 ATT Error Used in ATT as Request Not Supported Ox0107 ATT Error Offset specified was past the end of the attribute Ox0108 ATT Error Used in ATT as Insufficient Authorisation Ox0109 ATT Error Used in ATT as Pre
271. utorun application exits to interactive mode by design Hence in normal operation where a module is expected to have an autorun application the virtual serial port service will not be registered in the GATT table If the application requires the virtual serial port functionality then it shall have to be registered programmatically using the functions that follow in subsequent subsections These are easy to use high level functions such as OPEN READ WRITE CLOSE VSP Virtual Serial Port Events In addition to the routines for manipulating the Virtual Serial Port VSP service when data arrives via the receive characteristic it is stored locally in an underlying ring buffer and then an event is generated Similarly when the transmit buffer is emptied events are thrown from the underlying drivers so that user smart BASIC code in handlers can perform user defined actions The following Is a list of events generated by VSP service managed code which can be handled by user code Americas 1 800 492 2320 Option 2 188 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual EVVSPRX This event is generated when data has arrived and has been stored in the local ring buffer to be read using BleVSpRead EVVSPTXEMPTY This event is generated when the last byte is transmitted using the outgoing data characteristic via a notification or indicati
272. write OK enable indication for char with cccd at 19 EVATTRWRITE cHndl 877 attrHndl 19 status 00000000 Attribute write OK EVATTRNOTIFY Event BleGattcNotifyRead cHndl 877 attrHndl 15 data BAADCODE discarded 0 EVATTRNOTIFY Event BleGattcNotifyRead cHndl 877 attrHndl 18 data DEADBEEF discarded 0 EVATTRNOTIFY Event BleGattcNotifyRead cHndl 877 attrHndl 15 data BAADCODE discarded 0 EVATTRNOTIFY Event BleGattcNotifyRead cHndl 877 attrHndl 18 data DEADBEEF discarded 0 BLEGATTCNOTIFYREAD Is an extension function Attribute Encoding Functions Data for Characteristics are stored in Value attributes arrays of bytes Multibyte Characteristic Descriptors content is stored similarly Those bytes are manipulated in smart BASIC applications using STRING variables The Bluetooth specification stipulates that multibyte data entities are stored communicated in little endian format and so all data manipulation is done similarly Little endian means that a multibyte data entity will be stored so that lowest significant byte is position at the lowest memory address and likewise when transported the lowest byte will get on the wire first This section describes all the encoding functions which allow those strings to be written to in smaller bytewise subfields in a more efficient manner compared to the generic STRXXXX functions that are made available in smart BASIC Note CCCD and SCCD Descriptors are special cases they have two bytes which
273. www lairdtech com bluetooth smart BASIC User Manual Handle for the Value Attribute of the Characteristic is the handle for the value attribute and Is the value to store to keep track of important characteristics in a gatt server for later read write operations Included Service Uuid Handle is for future Use and will always be 0 BLEGATTCFINDCHAR connHandle svcUvidHndl svcindex charUvidHndl charlndex A typical pseudo code for finding a characteristic involves calling BleGattcFindChar which in turn will result in the EVFINDCHAR event message and typically is as follows Register a handler for the EVFINDCHAR event message On EVFINDCHAR event message If Char Value Handle 0 then Characteristic not found Else Characteristic has been found Call BleGattcFindChar If BleGattcFindChar ok then Wait for EVFINDCHAR INTEGER a result code Typical value 0x0000 Returns Indicates a successful operation and it means an EVFINDCHAR event message WILL be thrown by the smartBASIC runtime engine containing the results A non zero return value implies an EVFINDCHAR message will NOT be thrown Arguments byVal nConnHandle AS INTEGER This is the connection handle as returned in the on connect event for the connHandle connection on which the remote Gatt Server can be accessed This will have bee returned in the EVBLEMSG event message with msgld 0 and msgCtx will have been the connection handle byVal svcUuidHndl AS
274. x2903 Value Descriptor 2 SCCD Americas 1 800 492 2320 Option 2 111 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual 0x0009 Ox2803 earns Value Handle Value Characteristic 1 Start UUID3 Ox000A Value Value 1 to 512 bytes Actual data UUID3 UxUUUB Ox2800 UUID of the ce Service 3 Start 0x000C Ox2803 are Value Handle Value Characteristic 3 Start UUID3 0x000D Value Value 1 to 512 bytes Actual data UUID3 Ox000E Ox2902 Value Descriptor 1 CCCD Ox000F Ox2903 Value Descriptor 2 SCCD 0x0010 Ox2904 Value presentation format data Descriptor 3 Ox00111 0x2906 Value valid range Descriptor 4 Range A colour highlighted example of a GATT Server table is shown above which shows there are 3 services at handles Ox0001 0x0008 and OxO000B because there are 3 rows where the Type 0x2803 and all rows up to the next instance of a row with Type 0x2800 or 2801 belong to that service In each group of rows for a service you can see one or more Characteristics where Type 0x2803 For example the service beginning at handle 0x0008 has one characteristic which contains 2 rows identified by handles 0x0009 and OxOO0A and the actual value for the characteristic starting at Ox0009 is in the row identified by OxOO0A Likewise each characteristic starts with a row with Tyoe 0x2803 and all rows following it up to a row with type 0x2800 28
275. xamples AT MAC 008098010203 AT MAC is an extension command AT BLX COMMAND This command is used to stop all radio activity adverts or connections when in interactive mode It is particularly Useful when the virtual serial port is enabled while in interactive mode AT BLX Command Returns nO0O r Arguments None Americas 1 800 492 2320 Option 2 11 Laird Technologies Europe 44 1628 858 940 Hong Kong 852 2923 0610 wireless support lairdtech com www lairdtech com bluetooth smart BASIC User Manual Interactive Command This is an Interactive Mode command and MUST be terminated by a carriage return for it fo be processed Note The module self reboots so that the bonding manager context Is also reset Examples AT BLX AT BLX is an extension command 3 CORE LANGUAGE BUILT IN ROUTINES Core language built in routines are present in every implementation of smarfBASIC These routines provide the basic programming functionality They are augmented with target specific routines for different platforms which are described in the extention manual for each target platform All the core functionality is described in the document smartBASIC Core Functionality However some functions have small behaviour differences and they are listed below Information Routines SYSINFO FUNCTION Returns an informational integer value depending on the value of varld argument SYSINFO varld Returns INTEGER Value
276. y for subsequent pairings and is used to determine if the pairing is authenticated or not This is related to Simple Secure Pairing as described in the following whitepapers httos www bluetooth org docman handlers DownloadDoc ashx doc_id 86174 httos www bluetooth orgq docman handlers DownloadDoc ashx doc _id 86173 In addition the Security Manager Specification in the core 4 0 specification Part H provides a full description You must be registered with the Bluetooth SIG www bluetooth org to get access to all these documents An authenticated pairing is deemed to be one with less than 1 in a million probability that the pairing was compromised by a MITM Man in the middle security attack The valid user I O capabilities are as described below BLESECMNGRIOCAP nloCap INTEGER a result code nem Typical value 0x0000 indicates a successful operation Arguments byVal nloCap AS INTEGER The user I O capability for all subsequent pairings O None also known as Just Works unauthenticated pairing nloCap Display with Yes No input capability authenticated pairing 2 Keyboard Only authenticated pairing 3 Display Only authenticated pairing if other end has input cap 4 Keyboard only authenticated pairing Interactive No Command Example BleSecMngrIoCap sb See in BL600CodeSnippets zip PRINT BleSecMngrIoCap 1 Expected Output BLESECMNGRIOCAP is an extension function BleSecMngrBondReq FUNCT
Download Pdf Manuals
Related Search
Related Contents
LG VX8800 Quick Start Guide (Spanish) - HD 2102.1, HD 2102.2, HD 2302.0 NGS StencilI ACRIBLATEM ANTIGRAFFITI (EXT Westinghouse 6401100 Instructions / Assembly Aiphone LAF-10S User's Manual STIHL MS 150 TC Owners Instruction Manual VGN-SR290JVH/C Copyright © All rights reserved.
Failed to retrieve file