ESP_IOT v2.5
IOT ESP Coding
BLEServerNetworking.cpp
Go to the documentation of this file.
1/**
2* \link BLEServerNetworking
3*/
4//
5// BLENetworking.cpp
6// M5Stick
7//
8// Created by Scott Moody on 1/19/22.
9//! 6.6.26 D-Day, 82 years later
10//! @see https://github.com/h2zero/NimBLE-Arduino/blob/master/docs/Migration_guide.md#general-information
11
12#include "BLEServerNetworking.h"
13#include <NimBLEDevice.h>
14#include "../../Defines.h"
15#ifdef M5UNIFIED
16#define pettutorApproach
17//https://h2zero.github.io/esp-nimble-cpp/class_nim_b_l_e_device.html
18//!the BLE Server
19static NimBLEServer* _pBLEServer;
20NimBLECharacteristic* _pCharacteristic;
21
22//!device name
23//unset... char *_deviceName_BLEServer = NULL;
24
26
27//!need to device way to change these ...
28//#define SERVICE_UUID "B0E6A4BF-CCCC-FFFF-330C-0000000000F0" //Pet Tutor feeder service for feed
29//#define CHARACTERISTIC_UUID "B0E6A4BF-CCCC-FFFF-330C-0000000000F1" //Pet Tutor feeder characteristic
32
33#define MAX_MESSAGE 600
35
36
37//! retrieve the service name (PTFEEDER, PTFeeder:Name, PTClicker:Name, etc)
39{
41}
42
43#ifdef M5UNIFIED //! 7.25.26 trying to work with 2.1 libs..
44
45/** None of these are required as they will be handled by the library with defaults. **
46 ** Remove as you see fit for your needs */
47class BLEServeNetworkingCallbacks : public NimBLEServerCallbacks {
48 void onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo) override {
49 SerialDebug.printf("Client connected:\n%s", connInfo.toString().c_str());
50
51 /**
52 * We can use the connection handle here to ask for different connection parameters.
53 * Args: connection handle, min connection interval, max connection interval
54 * latency, supervision timeout.
55 * Units; Min/Max Intervals: 1.25 millisecond increments.
56 * Latency: number of intervals allowed to skip.
57 * Timeout: 10 millisecond increments.
58 */
59 pServer->updateConnParams(connInfo.getConnHandle(), 24, 48, 0, 180);
60 }
61
62 void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason) override {
63 SerialDebug.printf("Client disconnected - start advertising\n");
64 NimBLEDevice::startAdvertising();
65 }
66
67 void onMTUChange(uint16_t MTU, NimBLEConnInfo& connInfo) override {
68 SerialDebug.printf("MTU updated: %u for connection ID: %u\n", MTU, connInfo.getConnHandle());
69 }
70
71 /********************* Security handled here *********************/
72 uint32_t onPassKeyDisplay() override {
73 SerialDebug.printf("Server Passkey Display\n");
74 /**
75 * This should return a random 6 digit number for security
76 * or make your own static passkey as done here.
77 */
78 return 123456;
79 }
80
81 void onConfirmPassKey(NimBLEConnInfo& connInfo, uint32_t passkey) override {
82 SerialDebug.printf("The passkey YES/NO number: %" PRIu32 "\n", passkey);
83 /** Inject false if passkeys don't match. */
84 NimBLEDevice::injectConfirmPasskey(connInfo, true);
85 }
86
87 void onAuthenticationComplete(NimBLEConnInfo& connInfo) override {
88 /** Check that encryption was successful, if not we disconnect the client */
89 if (!connInfo.isEncrypted())
90 {
91 NimBLEDevice::getServer()->disconnect(connInfo.getConnHandle());
92 SerialDebug.printf("Encrypt connection failed - disconnecting client\n");
93 return;
94 }
95
96 SerialDebug.printf("Secured connection to: %s\n", connInfo.getAddress().toString().c_str());
97 }
99
100#else // not M5Unified
101/** None of these are required as they will be handled by the library with defaults. **
102 ** Remove as you see fit for your needs */
103class BLEServeNetworkingCallbacks : public NimBLEServerCallbacks
104{
105 void onConnect(NimBLEServer* pServer)
106 {
107 SerialInfo.println("Client connected");
108 SerialInfo.println("Multi-connect support: start advertising");
109 NimBLEDevice::startAdvertising();
110 };
111 /** Alternative onConnect() method to extract details of the connection.
112 See: src/ble_gap.h for the details of the ble_gap_conn_desc struct.
113 */
114 void onConnect(NimBLEServer* pServer, ble_gap_conn_desc* desc)
115 {
116 SerialInfo.print("Client address: ");
117 SerialInfo.println(NimBLEAddress(desc->peer_ota_addr).toString().c_str());
118 /** We can use the connection handle here to ask for different connection parameters.
119 Args: connection handle, min connection interval, max connection interval
120 latency, supervision timeout.
121 Units; Min/Max Intervals: 1.25 millisecond increments.
122 Latency: number of intervals allowed to skip.
123 Timeout: 10 millisecond increments, try for 5x interval time for best results.
124 */
125 //GOOD:
126 pServer->updateConnParams(desc->conn_handle, 24, 48, 0, 60);
127
128 //try:
129 //pServer->updateConnParams(desc->conn_handle, 100, 200, 10, 160);
130
131 };
132 void onDisconnect(NimBLEServer* pServer)
133 {
134 SerialInfo.println("Client disconnected - start advertising");
135 NimBLEDevice::startAdvertising();
136 };
137 void onMTUChange(uint16_t MTU, ble_gap_conn_desc* desc)
138 {
139 SerialInfo.printf("MTU updated: %u for connection ID: %u\n", MTU, desc->conn_handle);
140 };
141
142 /********************* Security handled here **********************
143 ****** Note: these are the same return values as defaults ********/
144 uint32_t onPassKeyRequest()
145 {
146 SerialDebug.println("Server Passkey Request");
147 /** This should return a random 6 digit number for security
148 or make your own static passkey as done here.
149 */
150 return 123456;
151 };
152
153 bool onConfirmPIN(uint32_t pass_key)
154 {
155 SerialDebug.print("The passkey YES/NO number: "); SerialDebug.println(pass_key);
156 /** Return false if passkeys don't match. */
157 return true;
158 };
159
160 void onAuthenticationComplete(ble_gap_conn_desc* desc)
161 {
162 /** Check that encryption was successful, if not we disconnect the client */
163 if (!desc->sec_state.encrypted)
164 {
165 NimBLEDevice::getServer()->disconnect(desc->conn_handle);
166 SerialDebug.println("Encrypt connection failed - disconnecting client");
167 return;
168 }
169 SerialDebug.println("Starting BLE work!");
170 };
171} _BLEServeNetworkingCallbacks; //add this.. 7.25,26
172#endif // not M5Unified
173
174#ifdef M5UNIFIED //! 7.25.26 trying to work with 2.1 libs..
175
176/** Handler class for characteristic actions */
177//!Note: the onRead and onWrite are from the perspective of the client. So onRead is the client calling this server, over BLE, and reading a value. The onWrite is the client writing to this server (sending a BLE message). This is where JSON or raw values are used.
178class BLEServerNetworkingCharacteristicCallbacks : public NimBLECharacteristicCallbacks
179{
180 //!called when wanting to "read" from this server
181 void onRead(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo) override
182 {
183 SerialDebug.print(pCharacteristic->getUUID().toString().c_str());
184 SerialDebug.print(": onRead(), value: ");
185 // SerialDebug.print(_fullJSONString);
186 SerialDebug.println(pCharacteristic->getValue().c_str());
187 };
188
189 //!called when writing to the server.
190 void onWrite(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo) override
191 {
192 SerialDebug.print(pCharacteristic->getUUID().toString().c_str());
193 SerialDebug.print(": onWrite(), value: ");
194 /*******************************MQTT*************************************/
195 std::string value = pCharacteristic->getValue();
196 SerialDebug.println(value.c_str());
197
198 if (value.length() > 0) {
199 SerialDebug.println("*********");
200 SerialDebug.printf("New value: %d - \n", value.length());
201
202 //create a string 'ascii' from the values
203 for (int i = 0; i < value.length(); i++)
204 {
205 _asciiMessage[i] = value[i];
206 _asciiMessage[i + 1] = 0;
207 if (i >= value.length())
208 break;
209 }
210 SerialDebug.printf("_asciiMessage = '%s'\n", _asciiMessage);
211 //! try reboot...
212 if (strlen(_asciiMessage)>0 && _asciiMessage[0] == 'r')
213 {
214 //! reboot
215 SerialDebug.println(" **** REBOOT ***");
217 }
218 //reply right away .. see what happens..
219 //sendBLEMessageACKMessage();
220 //pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
221 SerialDebug.println(pCharacteristic->getUUID().toString().c_str());
222
223 //call the callback specified from the caller (eg. NimBLE_PetTutor_Server .. or others)
224 // (*_callbackFunction)(rxValue);
226
227#ifdef ESP_M5
228 SerialDebug.println("*** performing an M5 specific command from BLE trigger");
229 // do something ..
231
232 // M5.Beep.beep();
233
234 //!Increment the screen color 0..n cache for getting the screen color 0..max (max provided by sender)
235 //!This is implemented by incrementScreenColor_mainModule() since it knows the MAX value of colors
237
238
239#endif
240
241 }
242 }
243
244 /**
245 * The value returned in code is the NimBLE host return code.
246 */
247 void onStatus(NimBLECharacteristic* pCharacteristic, int code) override {
248 SerialLots.printf("Notification/Indication return code: %d, %s\n", code, NimBLEUtils::returnCodeToString(code));
249 }
250
251 /** Peer subscribed to notifications/indications */
252 void onSubscribe(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo, uint16_t subValue) override {
253 std::string str = "Client ID: ";
254 str += connInfo.getConnHandle();
255 str += " Address: ";
256 str += connInfo.getAddress().toString();
257 if (subValue == 0) {
258 str += " Unsubscribed to ";
259 } else if (subValue == 1) {
260 str += " Subscribed to notifications for ";
261 } else if (subValue == 2) {
262 str += " Subscribed to indications for ";
263 } else if (subValue == 3) {
264 str += " Subscribed to notifications and indications for ";
265 }
266 str += std::string(pCharacteristic->getUUID());
267
268 SerialDebug.printf("%s\n", str.c_str());
269 }
271#else
272/** Handler class for characteristic actions */
273//!Note: the onRead and onWrite are from the perspective of the client. So onRead is the client calling this server, over BLE, and reading a value. The onWrite is the client writing to this server (sending a BLE message). This is where JSON or raw values are used.
274class BLEServerNetworkingCharacteristicCallbacks : public NimBLECharacteristicCallbacks
275{
276 //!called when wanting to "read" from this server
277 void onRead(NimBLECharacteristic* pCharacteristic)
278 {
279 SerialDebug.print(pCharacteristic->getUUID().toString().c_str());
280 SerialDebug.print(": onRead(), value: ");
281 // SerialDebug.print(_fullJSONString);
282 SerialDebug.println(pCharacteristic->getValue().c_str());
283 };
284
285 //!called when writing to the server.
286 void onWrite(NimBLECharacteristic* pCharacteristic)
287 {
288 SerialDebug.print(pCharacteristic->getUUID().toString().c_str());
289 SerialDebug.print(": onWrite(), value: ");
290 // SerialDebug.println(pCharacteristic->getValue().c_str());
291 // std::string rxValue = pCharacteristic->getValue().c_str();
292 //??
293 // ProcessClientCmd(rxValue[0]); //?? client sent a command now see what it is
294 // pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
295 /*******************************MQTT*************************************/
296 std::string value = pCharacteristic->getValue();
297 SerialDebug.println(value.c_str());
298
299 if (value.length() > 0) {
300 SerialDebug.println("*********");
301 SerialDebug.printf("New value: %d - \n", value.length());
302
303 //create a string 'ascii' from the values
304 for (int i = 0; i < value.length(); i++)
305 {
306 _asciiMessage[i] = value[i];
307 _asciiMessage[i + 1] = 0;
308 if (i >= value.length())
309 break;
310 }
311 SerialDebug.printf("_asciiMessage = '%s'\n", _asciiMessage);
312 //! try reboot...
313 if (strlen(_asciiMessage)>0 && _asciiMessage[0] == 'r')
314 {
315 //! reboot
316 SerialDebug.println(" **** REBOOT ***");
318 }
319 //reply right away .. see what happens..
320 //sendBLEMessageACKMessage();
321 //pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
322 SerialDebug.println(pCharacteristic->getUUID().toString().c_str());
323
324#ifdef TRY_LATER
325 //try .. #85
326 // if (value.compare("_ESP_32"==0))
327 {SerialInfo.println("pChar->setValue(_ESP_32)");
328 //send it back...
329 pCharacteristic->setValue((char*)"_ESP_32");
330 }
331#endif
332 //call the callback specified from the caller (eg. NimBLE_PetTutor_Server .. or others)
333 // (*_callbackFunction)(rxValue);
335
336#ifdef ESP_M5
337 SerialDebug.println("*** performing an M5 specific command from BLE trigger");
338 // do something ..
340
341 // M5.Beep.beep();
342
343 //!Increment the screen color 0..n cache for getting the screen color 0..max (max provided by sender)
344 //!This is implemented by incrementScreenColor_mainModule() since it knows the MAX value of colors
346
347
348#endif
349#ifdef NOT_NOW_MQTT_NETWORKING
350 //This should be a 'register' command..
351
352 // will return true if the message was JSON and was processes, false otherwise.
353 if (processJSONMessage(ascii))
354 {
355 //processed by the MQTTNetworking code..
356 pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
357 }
358 else
359 {
360 //perform feed...
361 SerialInfo.println("Perform FEED");
362
363 //std::string rxValue = pCharacteristic->getValue().c_str(); //??
364 //stepperModule_ProcessClientCmd(rxValue[0]); //?? client sent a command now see what it is
366 pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
367
368#ifdef ESP_M5
369
370 //#ifdef TEST_M5_TO_M5
371 // do something ..
372 showText_displayModule("BLE FEED");
373
374 //!Increment the screen color 0..n cache for getting the screen color 0..max (max provided by sender)
375 //!This is implemented by incrementScreenColor_mainModule() since it knows the MAX value of colors
377
378 //#endif
379#endif
380 }
381 SerialDebug.println("*********");
382
383#endif
384 }
385
386 /*******************************MQTT*************************************/
387
388}// _BLEServerNetworkingCharacteristicCallbacks;
389
390/** Called before notification or indication is sent,
391 the value can be changed here before sending if desired.
392 */
393void onNotify(NimBLECharacteristic * pCharacteristic)
394{
395 SerialDebug.println("Sending notification to clients");
396};
397
398
399/** The status returned in status is defined in NimBLECharacteristic.h.
400 The value returned in code is the NimBLE host return code.
401 */
402void onStatus(NimBLECharacteristic * pCharacteristic, Status status, int code)
403{
404#if (SERIAL_DEBUG_DEBUG)
405 String str = ("Notification/Indication status code: ");
406 str += status;
407 str += ", return code: ";
408 str += code;
409 str += ", ";
410 str += NimBLEUtils::returnCodeToString(code);
411 SerialDebug.println(str);
412#endif //serial_debug_debug
413};
414
415void onSubscribe(NimBLECharacteristic * pCharacteristic, ble_gap_conn_desc * desc, uint16_t subValue)
416{
417#if (SERIAL_DEBUG_DEBUG)
418
419 String str = "Client ID: ";
420 str += desc->conn_handle;
421 str += " Address: ";
422 str += std::string(NimBLEAddress(desc->peer_ota_addr)).c_str();
423 if (subValue == 0) {
424 str += " Unsubscribed to ";
425 }
426 else if (subValue == 1) {
427 str += " Subscribed to notfications for ";
428 }
429 else if (subValue == 2) {
430 str += " Subscribed to indications for ";
431 }
432 else if (subValue == 3) {
433 str += " Subscribed to notifications and indications for ";
434 }
435 str += std::string(pCharacteristic->getUUID()).c_str();
436
437 SerialDebug.println(str);
438#endif //serial_debug_debug
439};
440};
441#endif //not m5 unified
442
443#ifdef M5UNIFIED
444/** Handler class for descriptor actions */
445class BLEServerNetworkingDescriptorCallbacks : public NimBLEDescriptorCallbacks
446{
447 void onWrite(NimBLEDescriptor* pDescriptor, NimBLEConnInfo& connInfo) override {
448 std::string dscVal = pDescriptor->getValue();
449 SerialDebug.printf("Descriptor written value: %s\n", dscVal.c_str());
450 }
451
452 void onRead(NimBLEDescriptor* pDescriptor, NimBLEConnInfo& connInfo) override {
453 SerialDebug.printf("%s Descriptor read\n", pDescriptor->getUUID().toString().c_str());
454 SerialDebug.printf("DeviceName = %s\n", _serviceName_BLEServer?_serviceName_BLEServer:(char*)"nil");
455 }
456
458#else
459/** Handler class for descriptor actions */
460class BLEServerNetworkingDescriptorCallbacks : public NimBLEDescriptorCallbacks
461{
462 void onWrite(NimBLEDescriptor* pDescriptor)
463 {
464#if (SERIAL_DEBUG_DEBUG)
465
466#define VERSION_1_4_1
467#ifdef VERSION_1_4_1
468 SerialDebug.print("Descriptor written value:");
469 SerialDebug.println(pDescriptor->getValue());
470#else
471 std::string dscVal((char*)pDescriptor->getValue(), pDescriptor->getLength());
472 SerialDebug.print("Descriptor written value:");
473 SerialDebug.println(dscVal.c_str());
474#endif
475
476#endif
477 };
478
479 void onRead(NimBLEDescriptor* pDescriptor)
480 {
481 SerialDebug.print(pDescriptor->getUUID().toString().c_str());
482 SerialDebug.println("Descriptor read");
483 SerialDebug.printf(" DeviceName = %s\n", _serviceName_BLEServer?_serviceName_BLEServer:"nil");
484 };
485};
486#endif
487
488#ifdef M5UNIFIED
489#else
490/** Define callback instances globally to use for multiple Charateristics \ Descriptors */
493#endif
494
495//!the 'loop' for this module BLEServerNetworking.
497{
498
499 if (_pBLEServer && _pBLEServer->getConnectedCount() >0 )
500 {
501 NimBLEService* pSvc = _pBLEServer->getServiceByUUID(_SERVICE_UUID);
502 if (pSvc)
503 {
504 NimBLECharacteristic* pChr = pSvc->getCharacteristic(_CHARACTERISTIC_UUID);
505 if (pChr)
506 {
507 pChr->notify(true);
508 }
509 }
510 }
511}
512//!the 'setup' for this module BLEServerNetworking. Here the service name is added (and potentially more later)
513void setup_BLEServerNetworking(char *serviceName, char * deviceName, char *serviceUUID, char *characteristicUUID)
514{
515
516 _SERVICE_UUID = serviceUUID;
517 _CHARACTERISTIC_UUID = characteristicUUID;
518
519 SerialDebug.printf("setup_BLEServerNetworking(%s,%s,%s,%s)\n", serviceName?serviceName:"NULL", deviceName?deviceName:"NULL", serviceUUID?serviceUUID:"NULL", characteristicUUID?characteristicUUID:"NULL");
520 char *storedDeviceName = deviceName_mainModule();
521 SerialTemp.printf("Stored DeviceName = '%s'\n", storedDeviceName);
522
523#pragma mark CALCULATE_BLE_NAME
524 //! 10.13.25 copy here..
525 //! 8.16.25 (use the setting)
527 {
528 sprintf(_serviceName_BLEServer, "%s:%s", serviceName, storedDeviceName);
529 }
530 else
531 {
532 strcpy(_serviceName_BLEServer, serviceName);
533 }
534
535 SerialMin.printf("Setting BLE serviceName: '%s'\n", _serviceName_BLEServer);
536
537 //!! Seems to be a length of 31 too long
538 //! //DEBUG: crashed
539 // assert failed: static void NimBLEDevice::init(const string&) NimBLEDevice.cpp:901 (rc == 0)
540 // void NimBLEDevice::init(const std::string &deviceName) {
541 //!@see https://github.com/espressif/arduino-esp32/issues/7894
542 int len = strlen(_serviceName_BLEServer);
543 if (len > 29)
544 {
546 SerialMin.printf("Name was over 29 characters, so shirking: '%s'\n", _serviceName_BLEServer);
547 }
548#pragma mark START BLE Server
549 NimBLEDevice::init(_serviceName_BLEServer);
550
551 //!create server
552 _pBLEServer = NimBLEDevice::createServer();
553
554 //! set callbacks
555 _pBLEServer->setCallbacks(&_BLEServeNetworkingCallbacks);
556
557#pragma mark DEAD Service
558 //! create the DEAD service so a GEN3 can be ruled out..
559 NimBLEService* pDeadService = _pBLEServer->createService("DEAD");
560 NimBLECharacteristic* pBeefCharacteristic = pDeadService->createCharacteristic("BEEF",NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::NOTIFY);
561
562 pBeefCharacteristic->setValue("Beef");
563 pBeefCharacteristic->setCallbacks(&_BLEServerNetworkingCharacteristicCallbacks);
564
565 /** 2904 descriptors are a special case, when createDescriptor is called with
566 0x2904 a NimBLE2904 class is created with the correct properties and sizes.
567 However we must cast the returned reference to the correct type as the method
568 only returns a pointer to the base NimBLEDescriptor class.
569 */
570 NimBLE2904* pBeef2904 = (NimBLE2904*)pBeefCharacteristic->createDescriptor("2904");
571 pBeef2904->setFormat(NimBLE2904::FORMAT_UTF8);
572 pBeef2904->setCallbacks(&_BLEServerNetworkingDescriptorCallbacks);
573 //! used??
574
575#pragma mark SERVICE_UUID service (main service)
576 //! create our main _SERVICE_UUID service`
577 NimBLEService* pIDogWatchService = _pBLEServer->createService(_SERVICE_UUID);
578 NimBLECharacteristic* pIDogWatchCharacteristic = pIDogWatchService->createCharacteristic(_CHARACTERISTIC_UUID,NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::NOTIFY);
579
580 pIDogWatchCharacteristic->setValue(_serviceName_BLEServer);
581 pIDogWatchCharacteristic->setCallbacks(&_BLEServerNetworkingCharacteristicCallbacks);
582 //pIDogWatchCharacteristic->setValue((const uint8_t*)deviceName, strlen(deviceName));
583
584
585 /** Custom descriptor: Arguments are UUID, Properties, max length in bytes of the value */
586 NimBLEDescriptor* pPetTutordsc = pIDogWatchCharacteristic->createDescriptor("C01D",NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::WRITE_ENC, 20);
587 pPetTutordsc->setValue(_serviceName_BLEServer);
588 pPetTutordsc->setCallbacks(&_BLEServerNetworkingDescriptorCallbacks);
589
590 //! now the advertising..
591 //!
592 _pCharacteristic = pIDogWatchCharacteristic;
593
594 /** Create an advertising instance and add the services to the advertised data */
595 NimBLEAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
596 pAdvertising->setName(_serviceName_BLEServer);
597
598 //! advertise service UUID for DEAD
599 pAdvertising->addServiceUUID(pDeadService->getUUID());
600
601 //! advertise service UUID for iDOGWatch
602 pAdvertising->addServiceUUID(pIDogWatchService->getUUID());
603 /**
604 * If your device is battery powered you may consider setting scan response
605 * to false as it will extend battery life at the expense of less data sent.
606 */
607#ifdef M5UNIFIED
608 pAdvertising->enableScanResponse(true);
609#else
610 pAdvertising->setScanResponse(true);
611#endif
612 pAdvertising->start();
613
614 SerialInfo.println("Advertising Started");
615}
616
617
618//!send ACK over bluetooth, this right now is 0x01
620{
621 SerialTemp.printf("%d sendBLEMessageACKMessage._pCharacteristic\n", _pCharacteristic);
622 _pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
623}
624
625#else
626#pragma mark START_OF_OLD_CODE
627//! try code straight from old ble server...
628/**
629 * \link BLEServerNetworking
630 */
631//
632// BLENetworking.cpp
633// M5Stick
634//
635// Created by Scott Moody on 1/19/22.
636//
637
638//#include "BLEServerNetworking.h"
639//#include <NimBLEDevice.h>
640//#include "../../Defines.h"
641#define pettutorApproach
642//https://h2zero.github.io/esp-nimble-cpp/class_nim_b_l_e_device.html
643//!the BLE Server
644static NimBLEServer* _pBLEServer;
645NimBLECharacteristic* _pCharacteristic;
646
647//!device name
648char *_deviceName_BLEServer = NULL;
649
650char _serviceName_BLEServer[100];
651
652//!need to device way to change these ...
653//#define SERVICE_UUID "B0E6A4BF-CCCC-FFFF-330C-0000000000F0" //Pet Tutor feeder service for feed
654//#define CHARACTERISTIC_UUID "B0E6A4BF-CCCC-FFFF-330C-0000000000F1" //Pet Tutor feeder characteristic
655char *_SERVICE_UUID;
657
658#define MAX_MESSAGE 600
660
661
662//! retrieve the service name (PTFEEDER, PTFeeder:Name, PTClicker:Name, etc)
664{
666}
667
668#ifdef NOT_HERE_USE_MAIN
669//! 10.13.25 Nice day. Snow in Hills. Mt out, Tom and Marjarie
670//! call this now.. from main
671//!NOT CALLED...
672//!sets the device name in the advertising
673void setBLEServerDeviceName(char *deviceName)
674{
675 _pCharacteristic->setValue(deviceName);
676
677 //save the deviceName
678 _deviceName_BLEServer = deviceName;
679}
680#endif
681
682/** None of these are required as they will be handled by the library with defaults. **
683 ** Remove as you see fit for your needs */
684class BLEServeNetworkingCallbacks : public NimBLEServerCallbacks
685{
686 void onConnect(NimBLEServer* pServer)
687 {
688 SerialInfo.println("Client connected");
689 SerialInfo.println("Multi-connect support: start advertising");
690 NimBLEDevice::startAdvertising();
691 };
692 /** Alternative onConnect() method to extract details of the connection.
693 See: src/ble_gap.h for the details of the ble_gap_conn_desc struct.
694 */
695 void onConnect(NimBLEServer* pServer, ble_gap_conn_desc* desc)
696 {
697 SerialInfo.print("Client address: ");
698 SerialInfo.println(NimBLEAddress(desc->peer_ota_addr).toString().c_str());
699 /** We can use the connection handle here to ask for different connection parameters.
700 Args: connection handle, min connection interval, max connection interval
701 latency, supervision timeout.
702 Units; Min/Max Intervals: 1.25 millisecond increments.
703 Latency: number of intervals allowed to skip.
704 Timeout: 10 millisecond increments, try for 5x interval time for best results.
705 */
706 //GOOD:
707 pServer->updateConnParams(desc->conn_handle, 24, 48, 0, 60);
708
709 //try:
710 //pServer->updateConnParams(desc->conn_handle, 100, 200, 10, 160);
711
712 };
713 void onDisconnect(NimBLEServer* pServer)
714 {
715 SerialInfo.println("Client disconnected - start advertising");
716 NimBLEDevice::startAdvertising();
717 };
718 void onMTUChange(uint16_t MTU, ble_gap_conn_desc* desc)
719 {
720 SerialInfo.printf("MTU updated: %u for connection ID: %u\n", MTU, desc->conn_handle);
721 };
722
723 /********************* Security handled here **********************
724 ****** Note: these are the same return values as defaults ********/
725 uint32_t onPassKeyRequest()
726 {
727 SerialDebug.println("Server Passkey Request");
728 /** This should return a random 6 digit number for security
729 or make your own static passkey as done here.
730 */
731 return 123456;
732 };
733
734 bool onConfirmPIN(uint32_t pass_key)
735 {
736 SerialDebug.print("The passkey YES/NO number: "); SerialDebug.println(pass_key);
737 /** Return false if passkeys don't match. */
738 return true;
739 };
740
741 void onAuthenticationComplete(ble_gap_conn_desc* desc)
742 {
743 /** Check that encryption was successful, if not we disconnect the client */
744 if (!desc->sec_state.encrypted)
745 {
746 NimBLEDevice::getServer()->disconnect(desc->conn_handle);
747 SerialDebug.println("Encrypt connection failed - disconnecting client");
748 return;
749 }
750 SerialDebug.println("Starting BLE work!");
751 };
752};
753
754/** Handler class for characteristic actions */
755//!Note: the onRead and onWrite are from the perspective of the client. So onRead is the client calling this server, over BLE, and reading a value. The onWrite is the client writing to this server (sending a BLE message). This is where JSON or raw values are used.
756class BLEServerNetworkingCharacteristicCallbacks : public NimBLECharacteristicCallbacks
757{
758 //!called when wanting to "read" from this server
759 void onRead(NimBLECharacteristic* pCharacteristic)
760 {
761 SerialDebug.print(pCharacteristic->getUUID().toString().c_str());
762 SerialDebug.print(": onRead(), value: ");
763 // SerialDebug.print(_fullJSONString);
764 SerialDebug.println(pCharacteristic->getValue().c_str());
765 };
766
767 //!called when writing to the server.
768 void onWrite(NimBLECharacteristic* pCharacteristic)
769 {
770 SerialDebug.print(pCharacteristic->getUUID().toString().c_str());
771 SerialDebug.print(": onWrite(), value: ");
772 // SerialDebug.println(pCharacteristic->getValue().c_str());
773 // std::string rxValue = pCharacteristic->getValue().c_str();
774 //??
775 // ProcessClientCmd(rxValue[0]); //?? client sent a command now see what it is
776 // pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
777 /*******************************MQTT*************************************/
778 std::string value = pCharacteristic->getValue();
779 SerialDebug.println(value.c_str());
780
781 if (value.length() > 0) {
782 SerialDebug.println("*********");
783 SerialDebug.printf("New value: LEN = %d => \n", value.length());
784
785 //create a string 'ascii' from the values
786 for (int i = 0; i < value.length(); i++)
787 {
788 _asciiMessage[i] = value[i];
789 _asciiMessage[i + 1] = 0;
790 if (i >= value.length())
791 break;
792 }
793 SerialDebug.printf("_asciiMessage = '%s' = %0x\n", _asciiMessage, value[0]);
794
795 //! try reboot...
796 if (strlen(_asciiMessage)>0 && _asciiMessage[0] == 'r')
797 {
798 //! reboot
799 SerialDebug.println(" **** REBOOT ***");
801 }
802 //reply right away .. see what happens..
803 //sendBLEMessageACKMessage();
804 //pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
805 SerialDebug.println(pCharacteristic->getUUID().toString().c_str());
806
807#ifdef TRY_LATER
808 //try .. #85
809 // if (value.compare("_ESP_32"==0))
810 {SerialInfo.println("pChar->setValue(_ESP_32)");
811 //send it back...
812 pCharacteristic->setValue((char*)"_ESP_32");
813 }
814#endif
815 //call the callback specified from the caller (eg. NimBLE_PetTutor_Server .. or others)
816 // (*_callbackFunction)(rxValue);
818
819//#ifdef ESP_M5
820#ifdef M5UNIFIED
821 SerialDebug.println("*** performing an M5 specific command from BLE trigger");
822 // do something ..
824
825 // M5.Beep.beep();
826
827 //!Increment the screen color 0..n cache for getting the screen color 0..max (max provided by sender)
828 //!This is implemented by incrementScreenColor_mainModule() since it knows the MAX value of colors
830
831
832#endif
833#ifdef NOT_NOW_MQTT_NETWORKING
834 //This should be a 'register' command..
835
836 // will return true if the message was JSON and was processes, false otherwise.
837 if (processJSONMessage(ascii))
838 {
839 //processed by the MQTTNetworking code..
840 pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
841 }
842 else
843 {
844 //perform feed...
845 SerialInfo.println("Perform FEED");
846
847 //std::string rxValue = pCharacteristic->getValue().c_str(); //??
848 //stepperModule_ProcessClientCmd(rxValue[0]); //?? client sent a command now see what it is
850 pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
851
852#ifdef ESP_M5
853
854 //#ifdef TEST_M5_TO_M5
855 // do something ..
856 showText_displayModule("BLE FEED");
857
858 //!Increment the screen color 0..n cache for getting the screen color 0..max (max provided by sender)
859 //!This is implemented by incrementScreenColor_mainModule() since it knows the MAX value of colors
861
862 //#endif
863#endif
864 }
865 SerialDebug.println("*********");
866
867#endif
868 }
869
870 /*******************************MQTT*************************************/
871
872};
873
874/** Called before notification or indication is sent,
875 the value can be changed here before sending if desired.
876 */
877void onNotify(NimBLECharacteristic * pCharacteristic)
878{
879 SerialDebug.println("Sending notification to clients");
880};
881
882
883/** The status returned in status is defined in NimBLECharacteristic.h.
884 The value returned in code is the NimBLE host return code.
885 */
886void onStatus(NimBLECharacteristic * pCharacteristic, Status status, int code)
887{
888#if (SERIAL_DEBUG_DEBUG)
889 String str = ("Notification/Indication status code: ");
890 str += status;
891 str += ", return code: ";
892 str += code;
893 str += ", ";
894 str += NimBLEUtils::returnCodeToString(code);
895 SerialDebug.println(str);
896#endif //serial_debug_debug
897};
898
899void onSubscribe(NimBLECharacteristic * pCharacteristic, ble_gap_conn_desc * desc, uint16_t subValue)
900{
901#if (SERIAL_DEBUG_DEBUG)
902
903 String str = "Client ID: ";
904 str += desc->conn_handle;
905 str += " Address: ";
906 str += std::string(NimBLEAddress(desc->peer_ota_addr)).c_str();
907 if (subValue == 0) {
908 str += " Unsubscribed to ";
909 }
910 else if (subValue == 1) {
911 str += " Subscribed to notfications for ";
912 }
913 else if (subValue == 2) {
914 str += " Subscribed to indications for ";
915 }
916 else if (subValue == 3) {
917 str += " Subscribed to notifications and indications for ";
918 }
919 str += std::string(pCharacteristic->getUUID()).c_str();
920
921 SerialDebug.println(str);
922#endif //serial_debug_debug
923};
924};
925
926/** Handler class for descriptor actions */
927class BLEServerNetworkingDescriptorCallbacks : public NimBLEDescriptorCallbacks
928{
929 void onWrite(NimBLEDescriptor* pDescriptor)
930 {
931#if (SERIAL_DEBUG_DEBUG)
932
933#define VERSION_1_4_1
934#ifdef VERSION_1_4_1
935 SerialDebug.print("Descriptor written value:");
936 SerialDebug.println(pDescriptor->getValue());
937#else
938 std::string dscVal((char*)pDescriptor->getValue(), pDescriptor->getLength());
939 SerialDebug.print("Descriptor written value:");
940 SerialDebug.println(dscVal.c_str());
941#endif
942
943#endif
944 };
945
946 void onRead(NimBLEDescriptor* pDescriptor)
947 {
948 SerialDebug.print(pDescriptor->getUUID().toString().c_str());
949 SerialDebug.println("Descriptor read");
950 SerialDebug.printf(" DeviceName = %s\n", _deviceName_BLEServer?_deviceName_BLEServer:"nil");
951 };
952};
953
954
955/** Define callback instances globally to use for multiple Charateristics \ Descriptors */
956//static DescriptorCallbacks dscCallbacks;
957//static CharacteristicCallbacks chrCallbacks;
958
959
960/** Define callback instances globally to use for multiple Charateristics \ Descriptors */
961static BLEServerNetworkingDescriptorCallbacks _descriptorBLEServerCallbacks;
962static BLEServerNetworkingCharacteristicCallbacks _characteristicBLEServerCallbacks;
963
964//!the 'loop' for this module BLEServerNetworking.
966{
967
968 // SerialDebug.printf("# Clients: %d \n\r", pServer->getConnectedCount()); // nimconfig.h can change the max clients allowed(up to 9). default is 3 wha
969#ifdef originalApproach
970 if (_pBLEServer->getConnectedCount()) {
971 NimBLEService* pSvc = pServer->getServiceByUUID("BAAD");
972 if (pSvc) {
973 NimBLECharacteristic* pChr = pSvc->getCharacteristic("F00D");
974 if (pChr) {
975 pChr->notify(true);
976 }
977 }
978 }
979#endif
980#ifdef pettutorApproach
981 if (_pBLEServer->getConnectedCount()) {
982 NimBLEService* pSvc = _pBLEServer->getServiceByUUID(_SERVICE_UUID);
983 if (pSvc) {
984 NimBLECharacteristic* pChr = pSvc->getCharacteristic(_CHARACTERISTIC_UUID);
985 if (pChr) {
986 pChr->notify(true);
987 }
988 }
989 }
990#endif
991}
992//!the 'setup' for this module BLEServerNetworking. Here the service name is added (and potentially more later)
993void setup_BLEServerNetworking(char *serviceName, char * deviceName, char *serviceUUID, char *characteristicUUID)
994{
995
996 _SERVICE_UUID = serviceUUID;
997 _CHARACTERISTIC_UUID = characteristicUUID;
998
999 SerialMin.printf("setup_BLEServerNetworking(%s,%s,%s,%s)\n", serviceName?serviceName:"NULL", deviceName?deviceName:"NULL", serviceUUID?serviceUUID:"NULL", characteristicUUID?characteristicUUID:"NULL");
1000
1001 char *storedDeviceName = deviceName_mainModule();
1002 SerialTemp.printf("Stored DeviceName = '%s'\n", storedDeviceName);
1003#define CALCULATE_BLE_NAME
1004#ifdef CALCULATE_BLE_NAME
1005 //! 10.13.25 copy here..
1006 //! 8.16.25 (use the setting)
1008 {
1009 sprintf(_serviceName_BLEServer, "%s:%s", serviceName, storedDeviceName);
1010 }
1011 else
1012 {
1013 strcpy(_serviceName_BLEServer, serviceName);
1014 }
1015#else
1016
1017 if (strcmp(serviceName, "PTClicker")==0)
1018 {
1019 //! currently not using the option, just doing it...
1020 sprintf(_serviceName_BLEServer, "%s:%s", serviceName, storedDeviceName);
1021 }
1022 else
1023 {
1024 //! 10.13.25 the service name was calaulated in MAIN already..
1025 strcpy(_serviceName_BLEServer, serviceName);
1026
1027 //! 8.16.25 (use the setting)
1029 {
1030 sprintf(_serviceName_BLEServer, "%s:%s", serviceName, storedDeviceName);
1031 }
1032 else
1033 {
1034 strcpy(_serviceName_BLEServer, serviceName);
1035 }
1036 }
1037#endif
1038
1039
1040 SerialMin.printf("Setting BLE serviceName: '%s'\n", _serviceName_BLEServer);
1041 // SerialMin.printf("LEN = %d\n", strlen(_serviceName_BLEServer));
1042
1043
1044 //!! Seems to be a length of 31 too long
1045 //! //DEBUG: crashed
1046 // assert failed: static void NimBLEDevice::init(const string&) NimBLEDevice.cpp:901 (rc == 0)
1047 // void NimBLEDevice::init(const std::string &deviceName) {
1048 //!@see https://github.com/espressif/arduino-esp32/issues/7894
1049 int len = strlen(_serviceName_BLEServer);
1050 if (len > 29)
1051 {
1052 _serviceName_BLEServer[28] = 0;
1053 SerialMin.printf("Name was over 29 characters, so shirking: '%s'\n", _serviceName_BLEServer);
1054 }
1055
1056
1057 /** sets device name */
1058 //??original NimBLEDevice::init("NimBLE-Arduino");
1059 // NimBLEDevice::init("PTFeeder");
1060 //NimBLEDevice::init(serviceName);
1061 NimBLEDevice::init(_serviceName_BLEServer);
1062
1063 /** Optional: set the transmit power, default is 3db */
1064 NimBLEDevice::setPower(ESP_PWR_LVL_P9); /** +9db */
1065
1066 /** Set the IO capabilities of the device, each option will trigger a different pairing method.
1067 BLE_HS_IO_DISPLAY_ONLY - Pass
1068 \ng
1069 */
1070 //NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_ONLY); // use passkey
1071 //NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_YESNO); //use numeric comparison
1072
1073 /** 2 different ways to set security - both calls achieve the same result.
1074 no bonding, no man in the middle protection, secure connections.
1075
1076 These are the default values, only shown here for demonstration.
1077 */
1078 //NimBLEDevice::setSecurityAuth(false, false, true);
1079 NimBLEDevice::setSecurityAuth(/*BLE_SM_PAIR_AUTHREQ_BOND | BLE_SM_PAIR_AUTHREQ_MITM |*/ BLE_SM_PAIR_AUTHREQ_SC);
1080 //** NOTE: DEAD is a hex string .. and BEEF is too, so they are not really strings but UUID's in HEX.
1081
1082 _pBLEServer = NimBLEDevice::createServer();
1083 _pBLEServer->setCallbacks(new BLEServerCallbacks());
1084 /****************** DEAD service BEEF characteristic 2904notify,R/W/W_ENC(pairing REQUIRED!) ********************/
1085 NimBLEService* pDeadService = _pBLEServer->createService("DEAD");
1086 //?? NimBLEService* pDeadService = pServer->createService(SERVICE_UUID);
1087 NimBLECharacteristic* pBeefCharacteristic = pDeadService->createCharacteristic(
1088 "BEEF",
1089 //?? NimBLECharacteristic * pBeefCharacteristic = pDeadService->createCharacteristic(
1090 //?? CHARACTERISTIC_UUID,
1091 NIMBLE_PROPERTY::READ |
1092 NIMBLE_PROPERTY::WRITE |
1093 /** Require a secure connection for read and write access */
1094 NIMBLE_PROPERTY::READ_ENC | // only allow reading if paired / encrypted
1095 NIMBLE_PROPERTY::WRITE_ENC // only allow writing if paired / encrypted
1096 );
1097 //NOTE: IS THIS RIGHT? vs the other characteristic?? 5.19.22
1098 //assign to global: It's the Food charactestic..
1099#ifdef OLD_BLE_NO_ACK_APPROACH
1100 _pCharacteristic = pBeefCharacteristic;
1101#endif
1102
1103
1104
1105 /*******************************MQTT*************************************/
1106 //#ifdef MQTT_NETWORKING
1107 pBeefCharacteristic->setValue(deviceName);
1108
1109 //#else
1110 // pBeefCharacteristic->setValue("Burger");
1111 //#endif
1112 /*******************************MQTT*************************************/
1113
1114 pBeefCharacteristic->setCallbacks(&_characteristicBLEServerCallbacks);
1115
1116 /** 2904 descriptors are a special case, when createDescriptor is called with
1117 0x2904 a NimBLE2904 class is created with the correct properties and sizes.
1118 However we must cast the returned reference to the correct type as the method
1119 only returns a pointer to the base NimBLEDescriptor class.
1120 */
1121 NimBLE2904* pBeef2904 = (NimBLE2904*)pBeefCharacteristic->createDescriptor("2904");
1122 pBeef2904->setFormat(NimBLE2904::FORMAT_UTF8);
1123 pBeef2904->setCallbacks(&_descriptorBLEServerCallbacks);
1124
1125 /******** BAAD service F00D characteristic R/W/N C01D Descriptor ********************************/
1126#ifdef originalApproach
1127 NimBLEService* pBaadService = pServer->createService("BAAD");
1128 NimBLECharacteristic* pFoodCharacteristic = pBaadService->createCharacteristic(
1129 "F00D",
1130 NIMBLE_PROPERTY::READ |
1131 NIMBLE_PROPERTY::WRITE |
1132 NIMBLE_PROPERTY::NOTIFY
1133 );
1134#endif
1135#ifdef pettutorApproach
1136 NimBLEService* pBaadService = _pBLEServer->createService(_SERVICE_UUID);
1137 NimBLECharacteristic* pFoodCharacteristic = pBaadService->createCharacteristic(
1139 NIMBLE_PROPERTY::READ |
1140 NIMBLE_PROPERTY::WRITE // |
1141 // NIMBLE_PROPERTY::NOTIFY
1142 );
1143#endif
1144
1145#ifdef originalApproach
1146 pFoodCharacteristic->setValue("Fries");
1147#endif
1148
1149 pFoodCharacteristic->setCallbacks(&_characteristicBLEServerCallbacks);
1150
1151 /** Note a 0x2902 descriptor MUST NOT be created as NimBLE will create one automatically
1152 if notification or indication properties are assigned to a characteristic.
1153 */
1154
1155#ifdef originalApproach
1156 /** Custom descriptor: Arguments are UUID, Properties, max length in bytes of the value */
1157 NimBLEDescriptor* pC01Ddsc = pFoodCharacteristic->createDescriptor(
1158 "C01D",
1159 NIMBLE_PROPERTY::READ |
1160 NIMBLE_PROPERTY::WRITE |
1161 NIMBLE_PROPERTY::WRITE_ENC, // only allow writing if paired / encrypted
1162 20
1163 );
1164 pC01Ddsc->setValue("Send it back!");
1165 pC01Ddsc->setCallbacks(&dscCallbacks);
1166#endif
1167#ifdef pettutorApproach
1168 /** Custom descriptor: Arguments are UUID, Properties, max length in bytes of the value */
1169 NimBLEDescriptor* pPetTutordsc = pFoodCharacteristic->createDescriptor(
1170 "C01D", //the UUID is 0xC01D
1171 NIMBLE_PROPERTY::READ |
1172 NIMBLE_PROPERTY::WRITE |
1173 20
1174 );
1175 pPetTutordsc->setValue("feed s/a/j type u/m ");
1176 pPetTutordsc->setCallbacks(&_descriptorBLEServerCallbacks);
1177#endif
1178
1179#ifdef CURRENT_BLE_ACK_APPROACH
1180 //THIS IS RIGHT characteristic
1181 _pCharacteristic = pFoodCharacteristic;
1182 // end setup of services and characteristics
1183#endif
1184
1185 //#define TRY_THIRD_SERVICE_WITH_NAME
1186#ifdef TRY_THIRD_SERVICE_WITH_NAME
1187#define DEVICE_NAME_UUID "53636F74-7479426F79" //ScottyBoy
1188#define DEVICE_NAME_SERVICE "6E616D65" //name
1189 /****************** DEAD service BEEF characteristic 2904notify,R/W/W_ENC(pairing REQUIRED!) ********************/
1190 NimBLEService* pNameService = _pBLEServer->createService(DEVICE_NAME_SERVICE);
1191 //?? NimBLEService* pDeadService = pServer->createService(SERVICE_UUID);
1192 NimBLECharacteristic* pNameCharacteristic = pNameService->createCharacteristic(
1193 DEVICE_NAME_UUID,
1194 //?? NimBLECharacteristic * pBeefCharacteristic = pDeadService->createCharacteristic(
1195 //?? CHARACTERISTIC_UUID,
1196 NIMBLE_PROPERTY::READ |
1197 NIMBLE_PROPERTY::WRITE |
1198 /** Require a secure connection for read and write access */
1199 NIMBLE_PROPERTY::READ_ENC | // only allow reading if paired / encrypted
1200 NIMBLE_PROPERTY::WRITE_ENC // only allow writing if paired / encrypted
1201 );
1202
1203
1204 /*******************************MQTT*************************************/
1205 //#ifdef MQTT_NETWORKING
1206 pNameCharacteristic->setValue(deviceName);
1207
1208 //#else
1209 // pBeefCharacteristic->setValue("Burger");
1210 //#endif
1211 /*******************************MQTT*************************************/
1212
1213 pNameCharacteristic->setCallbacks(&_characteristicBLEServerCallbacks);
1214
1215 /** 2904 descriptors are a special case, when createDescriptor is called with
1216 0x2904 a NimBLE2904 class is created with the correct properties and sizes.
1217 However we must cast the returned reference to the correct type as the method
1218 only returns a pointer to the base NimBLEDescriptor class.
1219 */
1220 NimBLE2904* pName2904 = (NimBLE2904*)pNameCharacteristic->createDescriptor("2904");
1221 pName2904->setFormat(NimBLE2904::FORMAT_UTF8);
1222 pName2904->setCallbacks(&_descriptorBLEServerCallbacks);
1223 pNameService->start();
1224
1225#endif
1226
1227 /** Start the services when finished creating all Characteristics and Descriptors */
1228 pDeadService->start();
1229 pBaadService->start();
1230
1231 NimBLEAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
1232 /** Add the services to the advertisment data **/
1233 pAdvertising->addServiceUUID(pDeadService->getUUID());
1234 pAdvertising->addServiceUUID(pBaadService->getUUID());
1235 /** If your device is battery powered you may consider setting scan response
1236 to false as it will extend battery life at the expense of less data sent.
1237 */
1238#ifdef TRY_THIRD_SERVICE_WITH_NAME
1239 pAdvertising->addServiceUUID(pNameService->getUUID());
1240
1241#endif
1242 pAdvertising->setScanResponse(true);
1243 pAdvertising->start();
1244 //try the user supplied local name: Local Name == ScottyBoy in Advertisment
1245 // char *storedDeviceName = deviceName_mainModule();
1246 // SerialTemp.print("Stored DeviceName = ");
1247 // SerialTemp.println(storedDeviceName);
1248 //!setName shows up ad LocalName in Punchthrough Scanner, but
1249 // pAdvertising->setName(storedDeviceName);
1250
1251
1252 SerialInfo.println("Advertising Started");
1253}
1254
1255
1256//!send ACK over bluetooth, this right now is 0x01
1258{
1259 SerialTemp.printf("%d sendBLEMessageACKMessage._pCharacteristic\n", _pCharacteristic);
1260 _pCharacteristic->setValue(0x01); //?? This is the acknowlege(ACK) back to client. Later this should be contigent on a feed completed
1261}
1262
1263
1264
1265#endif
BLEServerNetworkingCharacteristicCallbacks _BLEServerNetworkingCharacteristicCallbacks
BLEServerNetworkingDescriptorCallbacks _BLEServerNetworkingDescriptorCallbacks
void loop_BLEServerNetworking()
the 'loop' for this module BLEServerNetworking.
#define MAX_MESSAGE
void sendBLEMessageACKMessage()
send ACK over bluetooth, this right now is 0x01
char _asciiMessage[MAX_MESSAGE]
char * getServiceName_BLEServerNetworking()
retrieve the service name (PTFEEDER, PTFeeder:Name, PTClicker:Name, etc)
char * _CHARACTERISTIC_UUID
NimBLECharacteristic * _pCharacteristic
BLEServeNetworkingCallbacks _BLEServeNetworkingCallbacks
char * _SERVICE_UUID
need to device way to change these ...
void setup_BLEServerNetworking(char *serviceName, char *deviceName, char *serviceUUID, char *characteristicUUID)
the 'setup' for this module BLEServerNetworking. Here the service name is added (and potentially more...
char _serviceName_BLEServer[100]
device name
#define BLE_SERVER_CALLBACK_ONWRITE
void addToTextMessages_displayModule(String text)
void incrementScreenColor_displayModule()
void showText_displayModule(String text)
char * deviceName_mainModule()
gets the device name
#define CALLBACKS_BLE_SERVER
Definition: MainModule.cpp:792
void processClientCommandChar_mainModule(char cmd)
single character version of processClientCommand (since many used that already)
void rebootDevice_mainModule()
void callCallbackMain(int callbacksModuleId, int callbackType, char *message)
performs the indirect callback based on the callbackType
Definition: MainModule.cpp:900
boolean getPreferenceBoolean_mainModule(int preferenceID)
called to set a preference (which will be an identifier and a string, which can be converted to a num...
#define PREFERENCE_BLE_SERVER_USE_DEVICE_NAME_SETTING
if set, the BLE Server (like PTFeeder) will tack on the device name (or none if not defined).
7.25.26 trying to work with 2.1 libs..
7.25.26 trying to work with 2.1 libs..