Switchbot and Wio Terminal

Hi, I love the Wio Terminal! I´m strugglin with this sketch, adapting, working from 0… no good luck, I am doing something wrong with BLE.
I have several of them so the blue address must be involved.
The manufacturer gave the code for python in: https://github.com/OpenWonderLabs/python-host/blob/master/switchbot_py3.py

It works with iOS-android nRF connect.

I would like to activate de Press Command in the switchbot in a similar way than in this gif.

If anyone could help me I would be really happy.

This is the sketch and some notes:

#include "BLEDevice.h"
#include "Seeed_erpcUnified.h" //not sure if needed

#define SWITCHBOT_MAC "C8:39:2E:90:32:31"
//#define SWITCHBOT_MAC "31:32:90:2E:39:C8" //REVERSE MAC ADRESS

static BLEUUID serviceUUID("CBA20D00-224D-11E6-9FB8-0002A5D5C51B"); //same for all switchbots
static BLEUUID characteristicUUID("CBA20002-224D-11E6-9FB8-0002A5D5C51B"); //same for all switchbots

static BLEAdvertisedDevice* myDevice;

  //commands = {
    //    'press' : '\x57\x01\x00',  
      //  'on'    : '\x57\x01\x01',
        //'off'   : '\x57\x01\x02',
        
static uint8_t cmdPress[3] = {0x57, 0x01, 0x00}; //Command to send. Works in iOs-Android with nRF Connect APP

uint8_t bd_addr[6] = {0x31, 0x32, 0x90, 0x2e, 0x39, 0xc8}; //REVERSE MAC ADRESS HEX
BLEAddress BattServer(bd_addr); //not sure if needed

bool pressSwitchBot() {

  bool result;
  BLEClient*  pClient  = BLEDevice::createClient();
  result = pClient->connect(myDevice);
  Serial.println(myDevice->getAddress().toString().c_str()); //wrong bl address returns here
  
  if (!result) {
    delay(2000);
    return (false);
  }

  BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
  if (pRemoteService == nullptr) {
    pClient->disconnect();

    delay(2000);
    return (false);
  }

  BLERemoteCharacteristic* pCharacteristic = pRemoteService->getCharacteristic(characteristicUUID);
  if (pCharacteristic == nullptr) {
    pClient->disconnect();
    delay(2000);
    return (false);
  }

  pCharacteristic->writeValue(cmdPress, sizeof(cmdPress), false);

  pClient->disconnect();
  delay(2000);
  return (true);
}

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)
          && advertisedDevice.getAddress().equals(BLEAddress(SWITCHBOT_MAC))) {
        Serial.println(advertisedDevice.getAddress().toString().c_str()); // if specified device found, print its MAC address to serial console.
        BLEDevice::getScan()->stop();
        myDevice = new BLEAdvertisedDevice(advertisedDevice);
      }
    }
};

void setup() {
  Serial.begin(115200);
  pinMode(WIO_KEY_A, INPUT); //set button A pin as input
  delay(10);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);

}

static uint32_t count = 0;

void loop() {
  if (digitalRead(WIO_KEY_A) == LOW) { //check whether button A is pressed
    Serial.println("Press Swichtbot");
    pressSwitchBot();
    delay(2000);
  }
}

Hi Sleepin6

Could you provide the correct bl address?

Best regards
fenyi

1 Like

I think this could be a nice -real- example to share. Thank you all!

Hi Sleepin6

Just want to make sure one thing, have you test the Wio terminal to connect your bot via BLE? (coz I have not your other device)

I suggest you check the BLE scan whether can find out your device first and then the client example have the function of check connection, you are able to follow it to confirm you bot whether connecting it.

Best regards
fenyi

1 Like

Thank you! Yes, I did it. Wio sees the devices and exits. Then I can’t send the command to the device. The Wio always returns result=0

The scan gives me: gapCallbackDefault L#58 GAP_MSG_LE_SCAN_INFO:adv_type 0x0, bd_addr c8:39:2e:90:32:30, remote_addr_type 1, rssi -50, data_len 13

I have not the “other” device :rofl: I just saw the gif and try to replicate in my Wio.

OK, I thought that is your device: )

try imitate it, thank you

When…
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
The Wio gets stuck.

I think that something similar happens here: https://github.com/nkolban/esp32-snippets/issues/874

07:10:32.943 -> found SwitchBot
07:10:44.964 -> Press Swichtbot
07:10:44.964 -> start connectAndSendCommand
07:10:47.127 -> connected

Then this happens…

BLERemoteService* pRemoteService = pClient->getService(serviceUUID);

…and total death. No more Serial.print(“hello?”);

Maybe is an issue with the libraries? I am using Seeed_Arduino_rpcUnified-master and Seeed_Arduino_rpcBLE-master

Thank you!

In case anyone can use it this is the sketch. I will upload the final and a video if I can make it work…

#include "BLEDevice.h"
#include "Seeed_erpcUnified.h"

// Address of your SwitchBot reversed
//static String addrSwitchBot = "c8:39:2E:90:32:30";
static String addrSwitchBot = "30:32:90:2e:39:c8";
// SwitchBot user-defined service
static BLEUUID serviceUUID("cba20d00-224d-11e6-9fb8-0002a5d5c51b");
// Target characteristic in the above service
static BLEUUID    charUUID("cba20002-224d-11e6-9fb8-0002a5d5c51b");
// SwitchBot Press command
static uint8_t cmdPress[3] = {0x57, 0x01, 0x00};

static BLEAddress *pGattServerAddress;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEClient*  pClient = NULL;
static boolean doSendCommand = false;

void dbg(const char *format, ...) {
  char b[512];
  va_list va;
  va_start(va, format);
  vsnprintf(b, sizeof(b), format, va);
  va_end(va);
  Serial.print(b);;
}

// Callback when advertisement is detected
class advdCallback: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      dbg("BLE device found: ");
      String addr = advertisedDevice.getAddress().toString().c_str();
      dbg("addr=[%s]\r\n", addr.c_str());
       // Discover SwitchBot
      if (addr.equalsIgnoreCase(addrSwitchBot)) {
        dbg("found SwitchBot\r\n");
        advertisedDevice.getScan()->stop();
        pGattServerAddress = new BLEAddress(advertisedDevice.getAddress());        
        doSendCommand = true;
      }
    }
};

void setup() {
  
  Serial.begin(115200);
  pinMode(WIO_KEY_A, INPUT); //set button A pin as input
  dbg("start");
  // BLE initialization
  BLEDevice::init("");
  // Scan advertisements from devices
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new advdCallback());
  pBLEScan->setActiveScan(true);
  pBLEScan->start(30);
}

void loop() {
    if (digitalRead(WIO_KEY_A) == LOW) { //check whether button A is pressed
    Serial.println("Press Swichtbot"); 
    if (connectAndSendCommand(*pGattServerAddress)) {
    } else {
      dbg("connectAndSendCommand failed");
    }
    doSendCommand = false;
    dbg("done");
  }
  delay(1000);
}

// Connect to SwitchBot's GATT server-Send Press command
static bool connectAndSendCommand(BLEAddress pAddress) {
  dbg("start connectAndSendCommand\r\n");
  pClient  = BLEDevice::createClient();

  pClient->connect(pAddress);
  dbg("connected\r\n");

// Get the target service 
 BLERemoteService* pRemoteService = pClient->getService(serviceUUID);//>>>>>>>>>>>>>>>>>STUCKED HERE 
 dbg("aqui\r\n");
 
  if (pRemoteService == nullptr) {
    dbg("target service not found\r\n");
    return false;
  }
  dbg("found target service\r\n");

  // Get the target characteristic
  pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
  if (pRemoteCharacteristic == nullptr) {
    dbg("target characteristic not found");
    return false;
  }
  dbg("found target characteristic\r\n");
  
  // Write the Press command characteristically
  pRemoteCharacteristic->writeValue(cmdPress, sizeof(cmdPress), false);

  delay(3000);
  if (pClient) {
    pClient->disconnect();
    pClient = NULL;
  }
  return true;
}
1 Like

After connected Wio says: connection lost cause 0xe
Still clueless…

17:42:05.260 -> connected
17:42:05.330 -> client: DEBUG: getServices L#221 start BLEClient::getServices():
17:42:05.330 ->

17:42:13.248 -> device: DEBUG: ble_handle_gap_msg L#393 ble_handle_gap_msg: subtype 2
17:42:13.248 ->
17:42:13.248 -> device: DEBUG: ble_handle_gap_msg L#407 GAP_MSG_LE_CONN_STATE_CHANGE
17:42:13.248 ->
17:42:13.248 -> device: DEBUG: ble_conn_state_evt_handler L#505 connection lost cause 0xe
17:42:13.248 ->
17:42:13.318 -> device: DEBUG: ble_handle_gap_msg L#393 ble_handle_gap_msg: subtype 1
17:42:13.318 ->
17:42:13.318 -> device: DEBUG: ble_handle_gap_msg L#399 GAP_MSG_LE_DEV_STATE_CHANGE
17:42:13.318 ->
17:42:13.318 -> device: DEBUG: ble_dev_state_evt_handler L#553 ble_dev_state_evt_handler: init state 1, adv state 0, cause 0xe

And the results from nRF Connect after succesfully send the command:

15:15:15,Dispositivo Conectado,verbose,Attempting to connect…
15:15:16,Dispositivo Conectado,debug,[Callback] centralManager(central, didConnect: peripheral)
15:15:16,Dispositivo Conectado,normal,Connected.
15:15:16,Dispositivo Conectado,verbose,Discovering Services…
15:15:16,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didDiscoverServices: nil)
15:15:16,Dispositivo Conectado,normal,Discovered FEE7 y CBA20D00-224D-11E6-9FB8-0002A5D5C51B Services.
15:15:16,Dispositivo Conectado,verbose,Discovering Characteristics for FEE7…
15:15:16,Dispositivo Conectado,debug,peripheral.discoverCharacteristics(nil, for: FEE7)
15:15:16,Dispositivo Conectado,verbose,Discovering Characteristics for CBA20D00-224D-11E6-9FB8-0002A5D5C51B…
15:15:16,Dispositivo Conectado,debug,peripheral.discoverCharacteristics(nil, for: CBA20D00-224D-11E6-9FB8-0002A5D5C51B)
15:15:16,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didDiscoverCharacteristicsFor: FEE7, error: nil)
15:15:16,Dispositivo Conectado,verbose,Discovering Descriptors for Characteristic FEC8…
15:15:16,Dispositivo Conectado,debug,peripheral.discoverDescriptors(for: FEC8)
15:15:16,Dispositivo Conectado,verbose,Discovering Descriptors for Characteristic FEC7…
15:15:16,Dispositivo Conectado,debug,peripheral.discoverDescriptors(for: FEC7)
15:15:16,Dispositivo Conectado,verbose,Discovering Descriptors for Characteristic FEC9…
15:15:16,Dispositivo Conectado,debug,peripheral.discoverDescriptors(for: FEC9)
15:15:16,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didDiscoverCharacteristicsFor: CBA20D00-224D-11E6-9FB8-0002A5D5C51B, error: nil)
15:15:16,Dispositivo Conectado,verbose,Discovering Descriptors for Characteristic CBA20003-224D-11E6-9FB8-0002A5D5C51B…
15:15:16,Dispositivo Conectado,debug,peripheral.discoverDescriptors(for: CBA20003-224D-11E6-9FB8-0002A5D5C51B)
15:15:16,Dispositivo Conectado,verbose,Discovering Descriptors for Characteristic CBA20002-224D-11E6-9FB8-0002A5D5C51B…
15:15:16,Dispositivo Conectado,debug,peripheral.discoverDescriptors(for: CBA20002-224D-11E6-9FB8-0002A5D5C51B)
15:15:16,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didDiscoverDescriptorsFor: FEC8, error: nil)
15:15:16,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didDiscoverDescriptorsFor: FEC7, error: nil)
15:15:16,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didDiscoverDescriptorsFor: FEC9, error: nil)
15:15:16,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didDiscoverDescriptorsFor: CBA20003-224D-11E6-9FB8-0002A5D5C51B, error: nil)
15:15:16,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didDiscoverDescriptorsFor: CBA20002-224D-11E6-9FB8-0002A5D5C51B, error: nil)
15:15:16,Dispositivo Conectado,normal,Discovered Characteristics FEC8, FEC7 y FEC9 for Service FEE7.
15:15:16,Dispositivo Conectado,normal,Discovered Characteristics CBA20003-224D-11E6-9FB8-0002A5D5C51B y CBA20002-224D-11E6-9FB8-0002A5D5C51B for Service CBA20D00-224D-11E6-9FB8-0002A5D5C51B.
15:15:16,Dispositivo Conectado,normal,Discovered Client Characteristic Configuration for Characteristic FEC8
15:15:16,Dispositivo Conectado,normal,Characteristic FEC7 has no Descriptors.
15:15:16,Dispositivo Conectado,normal,Characteristic FEC9 has no Descriptors.
15:15:16,Dispositivo Conectado,normal,Discovered Client Characteristic Configuration for Characteristic CBA20003-224D-11E6-9FB8-0002A5D5C51B
15:15:16,Dispositivo Conectado,normal,Characteristic CBA20002-224D-11E6-9FB8-0002A5D5C51B has no Descriptors.
15:15:27,Dispositivo Conectado,verbose,Writing 0x57-01-00 to Characteristic CBA20002-224D-11E6-9FB8-0002A5D5C51B
15:15:27,Dispositivo Conectado,debug,peripheral.writeValue(0x57-01-00, forCharacteristic: CBA20002-224D-11E6-9FB8-0002A5D5C51B)
15:15:27,Dispositivo Conectado,application,Writing value 0x57-01-00 to Characteristic CBA20002-224D-11E6-9FB8-0002A5D5C51B
15:15:27,Dispositivo Conectado,debug,[Callback] peripheral(peripheral, didWriteValueForCharacteristic: CBA20002-224D-11E6-9FB8-0002A5D5C51B, error: nil)
15:16:06,Escáner,normal,Scanner Off.

HI sleepin6
I will test it and check out the library on Monday. Apology for the later reply.

1 Like

Hi Sleepin6
Have u update your library to clean the debug message since you give the same question last time.

If you does not konw how to update just delete the “Seeed_Arduino_rpcBLE” library (the library in here: C:\Users\you_device_name\Documents\Arduino\libraries\Seeed_Arduino_rpcBLE)
then go to this LINK: https://github.com/Seeed-Studio/Seeed_Arduino_rpcBLE, reinstall it.

then try you code again.

Thank you

Yes I did it. Same result. Then I uncommented that line again to see if I could get more info from the debug. No luck.

I see, actually, I was used the phone sent the command to Wio terminal, it work very well, you may have a look at this link as a reference: https://www.hackster.io/fenyi/the-smartphone-communicates-with-the-wio-terminal-via-ble-faf90a
wish it can help you, and I sorry for the later reply, I am busy with other projects, but keep in touch, I will help.

1 Like

Hi Fenyi,
Thank you for your time!
I did you project. It works. But the Wio Terminal can only receive orders not give them.

-I have the bl adress from the bot.
-The serviceUUID.
-The charUUID.
-The writeValue.

This can not be that hard… :tired_face:

I have used the Wio Terminal as RTL8720DN Dev Board and the BLEClientScan works and see the bots.

Maybe my problem is that I have been re-using sketchs made for the ESP32 instead of RTL8720DN (but both use #include “BLEDevice.h” (¿?).

Can you send us this code? This can help us locate problems quickly. Then update the code. @Sleepin6

Sure, thank you!

It gives me this:

Scan Data 26
06:57:48.511 -> ADVType | AddrType | BT_Addr | rssi
06:57:48.511 ->

CON_UNDIRECT | random | c8:39:2e:90:32:30 | -42
06:57:48.511 ->

GAP_ADTYPE_FLAGS: 0x6
06:57:48.511 ->

GAP_ADTYPE_MANUFACTURER_SPECIFIC: company_id 0x59, len 6


#include "BLEDevice.h"
#include "BLEScan.h"

int dataCount = 0;
BLEAdvertData foundDevice;

void scanFunction(T_LE_CB_DATA* p_data) {
    Serial.print("Scan Data ");
    Serial.println(++dataCount);
    BLE.configScan()->printScanInfo(p_data);

    foundDevice.parseScanInfo(p_data);
    if (foundDevice.hasName()) {
        if (foundDevice.getName() == String("WoHand")) {
            Serial.print("Found BOT Device at address ");
            Serial.println(foundDevice.getAddr().str());
        }
    }
    uint8_t serviceCount = foundDevice.getServiceCount();
    if (serviceCount > 0) {
    BLEUUID* serviceList = foundDevice.getServiceList();
        for (uint8_t i = 0; i < serviceCount; i++) {
            if (serviceList[i] == BLEUUID("CBA20002-224D-11E6-9FB8-0002A5D5C51B")) {
            Serial.print("Found BOT2 ");
            Serial.println(foundDevice.getAddr().str());
            }
        }
    }
}

void setup() {
    Serial.begin(115200);
    BLE.init();
    BLE.configScan()->setScanMode(GAP_SCAN_MODE_ACTIVE);    // Active mode requests for scan response packets
    BLE.configScan()->setScanInterval(500);   // Start a scan every 500ms
    BLE.configScan()->setScanWindow(250);     // Each scan lasts for 250ms
    BLE.configScan()->updateScanParams();
    // Provide a callback function to process scan data.
    // If no function is provided, default BLEScan::printScanInfo is used
    BLE.setScanCallback(scanFunction);
    BLE.beginCentral(0);

    BLE.configScan()->startScan(5000);    // Repeat scans for 5 seconds, then stop
}

void loop() {
    delay(1000);
}

And from the original BLE_client i get this:

07:13:54.074 -> BLE Advertised Device found: Name: , Address: 30:32:90:2e:39:c8
07:13:54.074 -> BATT Device found: Name: , Address: 30:32:90:2e:39:c8
07:13:54.144 -> new BLEAdvertisedDevice
07:13:54.144 -> new BLEAdvertisedDevice done
07:13:54.144 -> Forming a connection to 30:32:90:2e:39:c8
07:13:54.144 -> - Created client
07:13:54.179 -> BLE Advertised Device found: Name: , Address: 2f:fb:ad:af:cb:79
07:13:54.247 -> BLE Advertised Device found: Name: , Address: fc:f9:35:d8:ea:44, serviceUUID: , serviceUUID:
07:13:56.452 -> - Connected to server
07:13:59.696 -> ScanCallback: GAP_MSG_LE_CONN_UPDATE_IND: conn_id 0, conn_interval_max 0x18, conn_interval_min 0x6, conn_latency 0x0,supervision_timeout 0x190
07:13:59.696 ->
cba20d00-224d-11e6-9fb8-0002a5d5c51b
07:14:11.509 -> Failed to find our service UUID: cba20d00-224d-11e6-9fb8-0002a5d5c51b
07:14:11.544 -> We have failed to connect to the server; there is nothin more we will do.
07:14:11.544 -> …


From the examples Seeed Adruino BLE BLE_client

/**
   A BLE client example that is rich in capabilities.
   There is a lot new capabilities implemented.
   author unknown
   updated by chegewara
*/

#include "BLEDevice.h"
#include "Seeed_erpcUnified.h"
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>

// The remote service we wish to connect to.
static BLEUUID serviceUUID("CBA20D00-224D-11E6-9FB8-0002A5D5C51B");
// The characteristic of the remote service we are interested in.
static BLEUUID    charUUID("CBA20002-224D-11E6-9FB8-0002A5D5C51B");

static boolean doConnect = true;
static boolean connected = true;
static boolean doScan = true;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;
uint8_t bd_addr[6] = {0x30, 0x32, 0x90, 0x2e, 0x39, 0xc8}; //reversed
//uint8_t bd_addr[6] = {0xc8, 0x39, 0x2e, 0x90, 0x32, 0x30};
BLEAddress BattServer(bd_addr);

static uint8_t cmdPress[3] = {0x57, 0x01, 0x00};

static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {
  Serial.print("Notify callback for characteristic ");
  Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
  Serial.print(" of data length ");
  Serial.println(length);
  Serial.print("data: ");
  Serial.print(*(uint8_t *)pData);
}

class MyClientCallback : public BLEClientCallbacks {
    void onConnect(BLEClient* pclient) {
    }
    void onDisconnect(BLEClient* pclient) {
      connected = false;
      Serial.println("onDisconnect");
    }
};

bool connectToServer() {
  Serial.print("Forming a connection to ");
  Serial.println(myDevice->getAddress().toString().c_str());

  BLEClient*  pClient  = BLEDevice::createClient();
  Serial.println(" - Created client");

  pClient->setClientCallbacks(new MyClientCallback());


  // Connect to the remove BLE Server.
  pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
  Serial.println(" - Connected to server");

  // Obtain a reference to the service we are after in the remote BLE server.
  BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
  Serial.println(serviceUUID.toString().c_str());
  if (pRemoteService == nullptr) {
    Serial.print("Failed to find our service UUID: ");
    Serial.println(serviceUUID.toString().c_str());
    pClient->disconnect();
    return false;
  }
  Serial.println(" - Found our service");

  // Obtain a reference to the characteristic in the service of the remote BLE server.
  pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
  if (pRemoteCharacteristic == nullptr) {
    Serial.print("Failed to find our characteristic UUID: ");
    Serial.println(charUUID.toString().c_str());
    pClient->disconnect();
    return false;
  }
  Serial.println(" - Found our characteristic");

  // Read the value of the characteristic.
  if (pRemoteCharacteristic->canRead()) {
    Serial.println(" -  can  read  start");
    std::string value = pRemoteCharacteristic->readValue();
    Serial.print("The characteristic value was: ");
    Serial.println(value.c_str());
  }

  if (pRemoteCharacteristic->canNotify())
    //            cmd to send ------->>>>>>>>>          pRemoteCharacteristic->writeValue(cmdPress, sizeof(cmdPress), false);
    pRemoteCharacteristic->registerForNotify(notifyCallback);

  connected = true;
  return true;
}
/**
   Scan for BLE servers and find the first one that advertises the service we are looking for.
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    /**
        Called for each advertising BLE server.
    */
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      Serial.print("BLE Advertised Device found: ");
      Serial.println(advertisedDevice.toString().c_str());

      // We have found a device, let us now see if it contains the service we are looking for.
      if (memcmp(advertisedDevice.getAddress().getNative(), BattServer.getNative(), 6) == 0) {
        Serial.print("BATT Device found: ");
        Serial.println(advertisedDevice.toString().c_str());
        BLEDevice::getScan()->stop();
        Serial.println("new BLEAdvertisedDevice");
        myDevice = new BLEAdvertisedDevice(advertisedDevice);
        Serial.println("new BLEAdvertisedDevice done");
        doConnect = true;
        doScan = true;
      } // onResult
    }
}; // MyAdvertisedDeviceCallbacks


void setup() {
  Serial.begin(115200);
  while (!Serial) {};
  delay(2000);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");

  // Retrieve a Scanner and set the callback we want to use to be informed when we
  // have detected a new device.  Specify that we want active scanning and start the
  // scan to run for 5 seconds.
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
} // End of setup.


// This is the Arduino main loop function.
void loop() {

  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are
  // connected we set the connected flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
      
    }
    doConnect = false;
  }
  Serial.printf(".");
  delay(1000);
} // End of loop