Motion and Environmental sensor reader application connected via BLE to ST BlueMS iOS/Android application.

Dependencies:   HTS221 LIS3MDL LPS22HB LSM303AGR LSM6DSL

Fork of MOTENV_Mbed by ST Expansion SW Team

This application supports three different sets of ST hardware boards:

  • STEVAL-STLKT01V1 (aka SensorTile)
  • X-NUCLEO-IDB05A1 and X-NUCLEO-IKS01A2 expansion boards
  • B-L475E-IOT01A IoT Discovery board

    and runs over four different target configurations:

  • Nucleo F401RE + X-NUCLEO-IDB05A1 + X-NUCLEO-IKS01A2 (set target NUCLEO_F401RE)
  • DISCO_L475VG_IOT01A (set target DISCO_L475VG_IOT01A)
  • Nucleo L476RG + CRADLE + SENSORTILE (set compile target NUCLEO_L476RG)
  • Nucleo L476RG + CRADLE_EXPANSION_BOARD + SENSORTILE (set compile target NUCLEO_L476RG, remove macro MINI_CRADLE from mbed_app.json)

The first 2 configurations do not require any HW modifications (just use the above indicated targets).

Third configuration (CRADLE ) only requires to remove the two ST-LINK jumpers and JP6 from the Nucleo L476RG board in order to allow flashing the SensorTile through the Nucleo Jtag controller. Once flashed, if the battery is properly plugged and charged, the SensorTile could be mounted in the plastic enclosure being able to run as a small stand alone wearable device. Please note that this configuration do not provide a serial console for printf.

To enable last configuration (CRADLE_EXPANSION_BOARD), follow the steps below:

  • On Nucleo L476RG
    • open the two "ST-LINK" jumpers
    • open the MCU power supply jumper JP6
    • close the solder bridges SB63 and SB62 (to enable the serial console)
  • On SensorTile Arduino Cradle close the solder bridges SB21 and SB10 (to enable the serial console) and move the jumper J2 to the 5V position
  • Plug the Sensor Tile on the Arduino Cradle
  • Plug the Cradle on the Nucleo Arduino connector and connect the debug flat cable between Cradle and Nucleo Jtag connector (the cradle pin1 -identified by a dot- must be connected to the Nucleo pin1 (dot) of SWD CN4 jtag connector)
  • Plug the Nucleo USB cable on PC (a new COM port should appear); no need to plug the micro USB cable on the cradle.
  • Open a PC terminal to see the messages
  • Compile from mbed CLI or on-line compiler removing macro MINI_CRADLE from mbed_app.json file and selecting NUCLEO_ L476RG target
  • Flash the board with the binary

For all configurations on an Android or iOS device download and open the ST BlueMS application and connect to "MotEnvMbedOS" BLE device to see the sensor data.

For all configurations is also possible to add a 9 axis MotionFX sensor fusion library, which is part of the X-CUBE-MEMS package at this link.
The library comes in three flavours, choose your preferred according to the toolchain used (IAR, Keil or GC, Keil version should be used for the online compiler) and copy it in the Middlewares\ST\STM32_MotionFX_Library\Lib directory changing the file extension according to the toolchain used (.a for GCC, .ar for Keil).
In the file mbed_app.json add the macro definition "USE_SENSOR_FUSION_LIB" to the chosen target.
If compiling from CLI and using GCC_ARM toolchain option, in the file \mbed-os\tools\toolchains\gcc.py change the compiling option from

        if target.core == "Cortex-M4F":
            self.cpu.append("-mfpu=fpv4-sp-d16")
            self.cpu.append("-mfloat-abi=softfp")

to

        if target.core == "Cortex-M4F":
            self.cpu.append("-mfpu=fpv4-sp-d16")
            self.cpu.append("-mfloat-abi=hard")

and compile.

Revision:
16:b794ff225d9d
Parent:
13:d00147d01d4e
Child:
18:e2360c944484
diff -r df9d639c9d4a -r b794ff225d9d main.cpp
--- a/main.cpp	Thu Jun 08 09:16:48 2017 +0200
+++ b/main.cpp	Thu Jun 08 09:25:00 2017 +0200
@@ -48,13 +48,21 @@
 #include "blecommon.h"
 #include "BLE.h"
 #include "UUID.h"
-#include "Utils.h"
+//#include "Utils.h"
 #include "MotionFX_Manager.h"
 #include "InterruptManager.h"
 #include "DevI2C.h"
 #include "BlueNRGGattServer.h"
 #include "GattCharacteristic.h"
 #include "main.h"   // contains the condt compiling configuration
+#include "ble_utils.h"
+
+#ifdef DEBUG
+#include <stdio.h>
+#define PRINTF(...) printf(__VA_ARGS__)
+#else
+#define PRINTF(...)
+#endif
 
 typedef struct {
     int32_t AXIS_X;
@@ -71,7 +79,7 @@
 #endif
 
 #ifdef CUST_SENS_SERV
-#include "x_nucleo_iks01a1.h"
+#include "XNucleoIKS01A2.h"
 #include "CustomSensorsService.h"
 #endif
 
@@ -85,7 +93,7 @@
 
 static bool             isBlueButtonSequence = false;
 static                  Ticker BlueButtonTimer;
-static DigitalOut       greenled(LED1);
+//static DigitalOut       greenled(LED1);
 //static int8_t           txPower=-3;
 static unsigned char    isCal = 0;
 static uint16_t         TimeStamp=0;
@@ -97,14 +105,35 @@
 static uint32_t         timeoutMems  =0;
 static BLE              * p_BLEdev = NULL;
 static int32_t          CounterAGM  =0;
+static bool SensorFusionOK = false;
+
+static EventQueue eventQueue(/* event count */ 16 * /* event size */ 32);
+static Queue <char, 5>QueueMainActivity;
+
+#define TMO_MEMS  1
+#define TMO_CALIB 2
+#define TMO_SENSOR_FUSION 3
+#define TMO_ENV   4
+
     
 #ifdef CUST_CONS_SERV
 static CustomConsoleService    * p_customconsoleservice = NULL;
 #endif
 
 #ifdef CUST_SENS_SERV
+#define IMU_6AXES_OK   0 
+#define MAGNETO_OK     0
+#define HUM_TEMP_OK    0
+#define PRESSURE_OK    0
 static CustomSensorService     * p_customsensorservice   = NULL;
-static X_NUCLEO_IKS01A1        * p_mems_expansion_board = NULL;
+//static X_NUCLEO_IKS01A1        * p_mems_expansion_board = NULL;
+SPI3W sens_intf(PB_15, NC, PB_13); // 3W mosi, sclk on Nucleo L476 same as BTLE
+	
+LPS22HBSensor press_temp(&sens_intf, PA_3);	 // on SensorTile L476JG
+LSM6DSLSensor acc_gyro(&sens_intf, PB_12, NC, PA_2 );	 // on SensorTile L476JG  
+LSM303AGRMagSensor mag(&sens_intf, PB_1 ); //on SensorTile L476JG				  
+LSM303AGRAccSensor acc(&sens_intf, PC_4 ); //on SensorTile L476JG		
+
 #endif
 
 #ifdef CUST_SW_SERV
@@ -378,6 +407,7 @@
 static void onUpdatesEnabledCallback(GattAttribute::Handle_t handle)
 {
     PRINTF("onUpdatesEnabledCallback! handle: %x\n\r", handle);
+	printf("onUpdatesEnabledCallback! handle: %x\n\r", handle);
 #ifdef CUST_SENS_SERV
     if (p_customsensorservice)
         p_customsensorservice->enNotify (handle);
@@ -490,33 +520,38 @@
 
 #ifdef CUST_SENS_SERV
     if (p_customsensorservice->isTempHandle(handle)) {
-        p_mems_expansion_board->ht_sensor->GetTemperature(&temp);
+//        p_mems_expansion_board->ht_sensor->GetTemperature(&temp);
+        press_temp.get_temperature(&temp);
         floatToInt(temp, &intPart, &decPart, 1);
         TempToSend = intPart*10+decPart;
         p_customsensorservice->sendEnvTemperature(TempToSend, TimeStamp);
 
     } else if (p_customsensorservice->isHumHandle(handle)) {
-        p_mems_expansion_board->ht_sensor->GetHumidity(&hum);
+//        p_mems_expansion_board->ht_sensor->GetHumidity(&hum);  /** FIXME Hum not present */
         floatToInt(hum, &intPart, &decPart, 1);
         HumToSend = intPart*10+decPart;
         p_customsensorservice->sendEnvHumidity(HumToSend, TimeStamp);
 
     } else if (p_customsensorservice->isPresHandle(handle)) {
-        p_mems_expansion_board->pt_sensor->GetPressure(&pres);
+//        p_mems_expansion_board->pt_sensor->GetPressure(&pres);
+        press_temp.get_pressure(&pres);
         floatToInt(pres, &intPart, &decPart, 1);
         PresToSend = intPart*100+decPart;
         p_customsensorservice->sendEnvPressure(PresToSend, TimeStamp);
 
     } else if (p_customsensorservice->isGyroHandle(handle)) {
-        p_mems_expansion_board->GetGyroscope()->Get_G_Axes((int32_t *)&Gyro);
+//        p_mems_expansion_board->GetGyroscope()->Get_G_Axes((int32_t *)&Gyro);
+        acc_gyro.get_g_axes((int32_t *)&Gyro);
         p_customsensorservice->sendEnvGyroscope (&Gyro, TimeStamp);
 
     } else if (p_customsensorservice->isAccHandle(handle)) {
-        p_mems_expansion_board->GetAccelerometer()->Get_X_Axes((int32_t *)&Acc);
+//        p_mems_expansion_board->GetAccelerometer()->Get_X_Axes((int32_t *)&Acc);
+        acc_gyro.get_x_axes((int32_t *)&Acc);
         p_customsensorservice->sendEnvAccelerometer (&Acc, TimeStamp);
 
     } else if (p_customsensorservice->isMagHandle(handle)) {
-        p_mems_expansion_board->magnetometer->Get_M_Axes((int32_t *)&Magn);
+//        p_mems_expansion_board->magnetometer->Get_M_Axes((int32_t *)&Magn);
+        mag.get_m_axes((int32_t *)&Magn);
         p_customsensorservice->sendEnvMagnetometer(&Magn, TimeStamp, magOffset);
 
     } else if (p_customsensorservice->isAccGyroMagHandle(handle)) {
@@ -651,203 +686,183 @@
  */
 static void Ticker_Env(void)
 {
-    timeoutEnv = 1;
+	char msg;
+	  msg = TMO_ENV;
+		QueueMainActivity.put((char*)msg);		
 }
 
 static void Ticker_Calib(void)
 {
+	char msg;	
     timeoutCalib = 1;
 }
 
 static void Ticker_Mems(void)
 {
+	char msg;	
     TimeStamp++;
     CounterAGM++;
-    timeoutMems = 1;
+	  msg = TMO_MEMS;
+		QueueMainActivity.put((char*)msg);		
+}
+
+static int ble_started=0;
+
+void onBleInitError(BLE &ble, ble_error_t error)
+{
+    (void)ble;
+    (void)error;
+	printf ("--->> onBleInitError\n\r");
+   /* Initialization error handling should go here */
+}
+
+void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
+{
+    BLE&        ble   = params->ble;
+    ble_error_t error = params->error;
+    if (error != BLE_ERROR_NONE) {
+        onBleInitError(ble, error);
+        printf ("--->> bleInitComplete ERROR\n\r");			
+        return;
+    }
+    if (ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
+        return;
+    }
+	ble_started=1;
+#if 0
+    ble.gap().onDisconnection(disconnectionCallback);
+
+    /* Setup primary service. */
+    hrServicePtr = new HeartRateService(ble, hrmCounter, HeartRateService::LOCATION_FINGER);
+  
+    /* Setup advertising. */
+    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
+    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
+    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_HEART_RATE_SENSOR);
+    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
+    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
+//    ble.gap().setAdvertisingInterval(1000); /* 1000ms */
+    ble.gap().setAdvertisingInterval(500); /* 1000ms */
+    ble.gap().startAdvertising();
+#endif
+}
+
+void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) {
+    BLE &ble = BLE::Instance();
+    eventQueue.call(Callback<void()>(&ble, &BLE::processEvents));
+}
+
+/* Helper function for printing floats & doubles */
+static char *print_double(char* str, double v, int decimalDigits=2)
+{
+  int i = 1;
+  int intPart, fractPart;
+  int len;
+  char *ptr;
+
+  /* prepare decimal digits multiplicator */
+  for (;decimalDigits!=0; i*=10, decimalDigits--);
+
+  /* calculate integer & fractinal parts */
+  intPart = (int)v;
+  fractPart = (int)((v-(double)(int)v)*i);
+
+  /* fill in integer part */
+  sprintf(str, "%i.", intPart);
+
+  /* prepare fill in of fractional part */
+  len = strlen(str);
+  ptr = &str[len];
+
+  /* fill in leading fractional zeros */
+  for (i/=10;i>1; i/=10, ptr++) {
+    if (fractPart >= i) {
+      break;
+    }
+    *ptr = '0';
+  }
+
+  /* fill in (rest of) fractional part */
+  sprintf(ptr, "%i", fractPart);
+
+  return str;
 }
 
 
-int main()
-{
-    Ticker EnvTimer;
-    Ticker CalibTimer;
-    Ticker MemsTimer;
-    int32_t decPart, intPart;
-    int16_t TempToSend,HumToSend;
-    uint32_t PresToSend;
-    float temp,hum,pres;
-    AxesRaw_TypeDef Magn;
-    AxesRaw_TypeDef Acc;
-    AxesRaw_TypeDef Gyro;
-    bool isgyro_lsm6ds0Present=false;
-    bool isgyro_lsm6ds3Present=false;    
-#ifdef CUST_CONS_SERV   
-//    static uint8_t          BufferToWrite[256];
-//    static uint8_t          BytesToWrite;           
-#endif    
-    static bool SensorFusionOK = false;
-
-    DevI2C *i2c = new DevI2C(I2C_SDA, I2C_SCL);
-    i2c->frequency(NUCLEO_I2C_SHIELDS_SPEED);
+void updateSensorValue() {
+    // Do blocking calls or whatever is necessary for sensor polling.
+    // In our case, we simply update the HRM measurement.
+	
+  float value1, value2;
+  char buffer1[32], buffer2[32];
+  int32_t axes[3];	
+#ifdef CUST_SENS_SERV      
+    press_temp.get_temperature(&value1);
+    press_temp.get_pressure(&value2);
+    printf("LPS22HB: [temp] %7s C, [press] %s mbar\r\n", print_double(buffer1, value1), print_double(buffer2, value2));
 
-#ifdef CUST_SENS_SERV
-    p_mems_expansion_board = X_NUCLEO_IKS01A1::Instance(i2c);
-    if (p_mems_expansion_board->gyro_lsm6ds0) isgyro_lsm6ds0Present=true;
-    if (p_mems_expansion_board->gyro_lsm6ds3) isgyro_lsm6ds3Present=true;    
-#endif
-//#ifdef CUST_CONFIG_SERV    
-    InterruptIn BlueButton(USER_BUTTON);    
-    BlueButton.fall(&BlueButtonPressed);
-//#endif
-    printf("\r\nSTMicroelectronics BlueMicrosystem1 W2ST:\r\n"
-#ifdef CUST_SENS_SERV
-           "\tGyro lsmds0 present: %d, lsmds3 present: %d\n\r"
-           "\tSend Every %dmS Temperature/Humidity/Pressure\r\n"
-           "\tSend Every %dmS Acc/Gyro/Magneto\r\n\n"   
-#endif  
-#ifdef CUST_SW_SERV
-           ,"\tSend Every %dmS %d Quaternions\r\n"
-           "\tSend Every %dmS Float precision Quaternion\r\n"
-#endif
-#ifdef CUST_SENS_SERV
-           ,isgyro_lsm6ds0Present,
-           isgyro_lsm6ds3Present,
-           ENV_TIMER/1000,
-           MEMS_TIMER/1000*ACC_GYRO_MAG_UPDATE_MUL_10MS
-#endif
-#ifdef CUST_SW_SERV
-           ,MEMS_TIMER/1000*SEND_N_QUATERNIONS,SEND_N_QUATERNIONS,
-           MEMS_TIMER/1000*QUAT_FLOAT_UPDATE_MUL_10MS
-#endif
-          );
-                    
-                    
-    if (NUCLEO_I2C_SHIELDS_SPEED < MAX_I2C_SPEED) 
-        printf ("Warning I2C speed set to: %d (max: %d)\n\r", NUCLEO_I2C_SHIELDS_SPEED, MAX_I2C_SPEED);
- 
-    p_BLEdev = new BLE;
-    if (!p_BLEdev) {
-        printf("\r\nBLE Device creation failed\r\n");
-        return 0;
-    }        
-    p_BLEdev->init();         
-    
-    greenled = 0;//Switch OFF LED1
-    
-    /* set the BLE CB functions */
-    p_BLEdev->gattServer().onUpdatesEnabled(onUpdatesEnabledCallback);
-    p_BLEdev->gattServer().onUpdatesDisabled(onUpdatesDisabledCallback);
-    p_BLEdev->gattServer().onConfirmationReceived(onConfirmationReceivedCallback);    
-    p_BLEdev->gattServer().onDataSent(onDataSentCallback);
-    p_BLEdev->gattServer().onDataRead(onDataReadCallback);
-    p_BLEdev->gattServer().onDataWritten(onDataWriteCallback);
-    p_BLEdev->gap().onConnection(onConnectionCallback);
-    p_BLEdev->gap().onDisconnection(onDisconnectionCallback);
-    p_BLEdev->gap().onTimeout(onTimeoutCallback);
-
+    mag.get_m_axes(axes);
+    printf("LSM303AGR [mag/mgauss]:  %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
     
-    /* Initialize MotionFX library */
-#ifdef USE_SENSOR_FUSION_LIB       
-    bool DS3_OnBoard = DS3_ONBOARD;    
-    if (MotionFX_manager_init(DS3_OnBoard, magOffset)) {
-        MotionFX_manager_start_9X();
-        SensorFusionOK = true;
-        printf("SW      Service sensor fusion library added successfully\r\n");
-    } else {    /* sensor fusion lib init failed: likely because of wrong license */
-            printf("sensor fusion lib init failed: likely because of wrong license \n\r");
-        SensorFusionOK = false;     
-    }   
-#else 
-    printf("sensor fusion lib disabled \n\r");    
-    SensorFusionOK = false;     
-#endif
-         
-#ifdef CUST_CONFIG_SERV
-    p_customconfigservice = new CustomConfigService(*p_BLEdev);
-    if (!p_customconfigservice) {
-        printf("SW      Service W2ST calibration add FAILED!\n\r");
-        return 0;  
-    }
-    printf("SW      Service W2ST calibration added successfully\r\n");
-#endif
-#ifdef CUST_CONS_SERV
-    p_customconsoleservice = new CustomConsoleService(*p_BLEdev);
-    if (!p_customconsoleservice) {
-        printf("\n\rHW      Service W2ST console add FAILED!\n\r");
-        return 0;
-    }
-    printf("\rHW      Service W2ST console added successfully\r\n");
-#endif
-#ifdef CUST_SENS_SERV
-    p_customsensorservice = new CustomSensorService(*p_BLEdev);
-    if (!p_customsensorservice) {
-        printf("\n\rHW      Service W2ST sensors add FAILED!\n\r");
-        return 0;
+    acc.get_x_axes(axes);
+    printf("LSM303AGR [acc/mg]:  %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
+
+    acc_gyro.get_x_axes(axes);
+    printf("LSM6DSL [acc/mg]:      %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
+
+    acc_gyro.get_g_axes(axes);
+    printf("LSM6DSL [gyro/mdps]:   %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
+#endif    
+}
+
+
+void periodicCallback(void)
+{
+//    led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */
+    if (BLE::Instance().getGapState().connected) {
+ //       eventQueue.call(updateSensorValue);
     }
-    printf("\rHW      Service W2ST sensors added successfully\r\n");
-#endif       
-#ifdef CUST_SW_SERV
-        AxesRaw_TypeDef quat_axes[SEND_N_QUATERNIONS];
-        float QuatFloat[SEND_N_QUATERNIONS];        
-        if (SensorFusionOK) {
-            p_customsoftwareservice = new CustomSoftwareService(*p_BLEdev);
-            if (!p_customsoftwareservice) {
-                    printf("SW      Service W2ST quaternions add FAILED!\n\r");
-                    return 0;
-            }
-            printf("SW      Service W2ST quaternions added successfully\r\n");
-        }
-#endif      
-        
-        const static char     DEVICE_NAME[]        = BLE_DEV_NAME;
-    /* Setup advertising. */
-    p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
-//    p_BLEdev->gap().accumulateAdvertisingPayloadTxPower(txPower); 
-#ifdef USE_SENSOR_FUSION_LIB        
-    uint8_t dat[]= {0x01,0x80,0x00,0xFC,0x01,0x80};
-#else
-    uint8_t dat[]= {0x01,0x80,0x00,0xFC,0x00,0x00};
-#endif      
-    p_BLEdev->gap().accumulateScanResponse(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA,dat,6);    
-    p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::UNKNOWN);
-    p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
-    p_BLEdev->gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
-    p_BLEdev->gap().setAdvertisingInterval(BLE_ADVERTISING_INTERVAL);
-    
-    printf("SERVER: BLE Stack Initialized\r\n");
-    printf("Starting Advertising...\n\r");
-    p_BLEdev->gap().startAdvertising();
-    
-    TimeStamp =0;
-    EnvTimer.attach_us(&Ticker_Env, ENV_TIMER);
-    CalibTimer.attach_us(&Ticker_Calib, CALIB_TIMER );
-    MemsTimer.attach_us(&Ticker_Mems, MEMS_TIMER);
+}
+
 
-    /* Control if the calibration is already available in memory */
-        if (SensorFusionOK) {
-            ReCallCalibrationFromMemory();
-
-            /* Switch on/off the LED according to calibration */
-            if(isCal) {
-                    greenled =1;
-            } else {
-                    greenled =0;
-            }
-        }
-#ifdef CUST_SW_SERV        
-    uint32_t QuaternionNumber =0;
-    uint32_t CounterFloat =0;
-#endif
-        
+void ThreadMainActivity (void) { 
+    float temp, hum, pres;	
+    AxesRaw_TypeDef Magn, Acc, Gyro;
+    int32_t decPart, intPart;
+    int16_t TempToSend, HumToSend;
+    uint32_t    PresToSend;
+    osEvent RxEvt;
+	
     while(1) {
 
+        RxEvt = QueueMainActivity.get();	
+			  switch (RxEvt.value.v) {
+					
+					case TMO_MEMS:
+						 timeoutMems =1;
+					   break;
+					
+          case TMO_CALIB:
+					   break;
+
+          case TMO_SENSOR_FUSION:
+             break;				
+
+          case TMO_ENV:
+						timeoutEnv =1;
+					  break;
+					
+					default:
+						printf ("ERROR unrecognized event\n\r");
+				}
+			
         if (BLEConnectionStatus) {
             if ((isBlueButtonSequence || ForceReCalibration) && SensorFusionOK ) {
                 printf("ForceReCalibration\r\n");
                 /* Reset the Compass Calibration */
                 isCal=0;
                 ForceReCalibration =0;
-                                isBlueButtonSequence = false;                           
+                isBlueButtonSequence = false;                           
                 /* Notifications of Compass Calibration */
 #ifdef CUST_CONFIG_SERV
                 p_customconfigservice->sendConfigState(MASK_CALIB_SENSORFUSION_SHORT, W2ST_COMMAND_CAL_STATUS, isCal, TimeStamp);
@@ -861,7 +876,7 @@
 
                 /* Reset Calibration offset */
                 magOffset.magOffX = magOffset.magOffY= magOffset.magOffZ=0;
-                greenled =0;
+//                greenled =0;
             }
         }
         // Update MEMS @ 100Hz and calculate quaternions
@@ -869,21 +884,23 @@
             timeoutMems =0;
 
 #ifdef CUST_SENS_SERV
-            int32_t err;
-            err = p_mems_expansion_board->GetAccelerometer()->Get_X_Axes((int32_t *)&Acc);
+            int32_t err=IMU_6AXES_OK; 
+            err=acc_gyro.get_x_axes((int32_t *)&Acc);
             if (err != IMU_6AXES_OK) {
                 printf ("= * ERROR %d GetAccelerometer\n\r", err);                          
             }
-            err = p_mems_expansion_board->GetGyroscope()->Get_G_Axes((int32_t *)&Gyro);
+
+            err=acc_gyro.get_g_axes((int32_t *)&Gyro);
             if (err != IMU_6AXES_OK) {
                 printf ("= * ERROR %d GetGyroscope\n\r", err);                          
             }
-            err = p_mems_expansion_board->magnetometer->Get_M_Axes((int32_t *)&Magn);
+            err=mag.get_m_axes((int32_t *)&Magn);
             if (err != MAGNETO_OK) {
                 printf ("= * ERROR %d Get_M_Axes\n\r", err);                            
             }    
+						
             if(CounterAGM >= ACC_GYRO_MAG_UPDATE_MUL_10MS) {
-                CounterAGM=0;
+                CounterAGM=0;		
                 p_customsensorservice->updateEnvAccelerometer (&Acc, TimeStamp);
                 p_customsensorservice->updateEnvGyroscope(&Gyro, TimeStamp);
                 p_customsensorservice->updateEnvMagnetometer(&Magn, TimeStamp, magOffset);
@@ -961,7 +978,7 @@
                 SaveCalibrationToMemory();
 
                 /* Switch on the Led */
-                greenled = 1;
+//                greenled = 1;
 
                 /* Notifications of Compass Calibration */
 #ifdef CUST_CONFIG_SERV
@@ -974,21 +991,21 @@
         // Update environmental sensors @ 2Hz
         if (timeoutEnv && BLEConnectionStatus) {
             timeoutEnv =0;
-                        int32_t err;                                            
+            int32_t err;                                            
 #ifdef CUST_SENS_SERV
                     if (p_customsensorservice->isTempNotificationEn()) {
-                        err = p_mems_expansion_board->ht_sensor->GetTemperature(&temp);
+                        err=press_temp.get_temperature(&temp);
                         if ( err != HUM_TEMP_OK) {
                             printf ("= * ERROR %d GetTemperature\n\r", err);
                         } else {
-                            floatToInt(temp, &intPart, &decPart, 1);
+                            floatToInt(temp, &intPart, &decPart, 1);													
                             TempToSend = intPart*10+decPart;
                             p_customsensorservice->updateEnvTemperature(TempToSend, TimeStamp);
                         }
                     }
-
+#if 0   // Hum sensor not present on SensorTile
                     if (p_customsensorservice->isHumNotificationEn()) {
-                        err = p_mems_expansion_board->ht_sensor->GetHumidity(&hum);
+//                        err = p_mems_expansion_board->ht_sensor->GetHumidity(&hum);  /** FIXME no hum sens on Tile */
                         if ( err != HUM_TEMP_OK) {
                             printf ("= * ERROR %d GetHumidity\n\r", err);                           
                         } else {
@@ -997,9 +1014,9 @@
                             p_customsensorservice->updateEnvHumidity(HumToSend, TimeStamp);       
                         }
                     }
-
+#endif
                     if (p_customsensorservice->isPresNotificationEn()) {
-                        err = p_mems_expansion_board->pt_sensor->GetPressure(&pres);
+                          err=press_temp.get_pressure(&pres);
                         if ( err != PRESSURE_OK) {
                             printf ("= * ERROR GetPressure\n\r");                           
                         } else {
@@ -1010,6 +1027,203 @@
                     }
 #endif
                 }
-        p_BLEdev->waitForEvent();
     }
+}		
+
+	
+int main()
+{
+    Ticker EnvTimer;
+    Ticker CalibTimer;
+    Ticker MemsTimer;
+    bool isgyro_lsm6ds0Present=false;
+    bool isgyro_lsm6ds3Present=false;    
+#ifdef CUST_CONS_SERV   
+//    static uint8_t          BufferToWrite[256];
+//    static uint8_t          BytesToWrite;           
+#endif    
+
+//    DevI2C *i2c = new DevI2C(I2C_SDA, I2C_SCL);
+//    i2c->frequency(NUCLEO_I2C_SHIELDS_SPEED);
+
+#ifdef CUST_SENS_SERV
+//    p_mems_expansion_board = X_NUCLEO_IKS01A1::Instance(i2c);
+//    if (p_mems_expansion_board->gyro_lsm6ds0) isgyro_lsm6ds0Present=true;
+//    if (p_mems_expansion_board->gyro_lsm6ds3) isgyro_lsm6ds3Present=true;    
+#endif
+//#ifdef CUST_CONFIG_SERV    
+//    InterruptIn BlueButton(USER_BUTTON);    
+//    BlueButton.fall(&BlueButtonPressed);
+//#endif
+
+    printf("\r\nSTMicroelectronics BlueMicrosystem1 W2ST:\r\n"
+#ifdef CUST_SENS_SERV
+           "\tGyro lsmds0 present: %d, lsmds3 present: %d\n\r"
+           "\tSend Every %dmS Temperature/Humidity/Pressure\r\n"
+           "\tSend Every %dmS Acc/Gyro/Magneto\r\n\n"   
+#endif  
+#ifdef CUST_SW_SERV
+           ,"\tSend Every %dmS %d Quaternions\r\n"
+           "\tSend Every %dmS Float precision Quaternion\r\n"
+#endif
+#ifdef CUST_SENS_SERV
+           ,isgyro_lsm6ds0Present,
+           isgyro_lsm6ds3Present,
+           ENV_TIMER/1000,
+           MEMS_TIMER/1000*ACC_GYRO_MAG_UPDATE_MUL_10MS
+#endif
+#ifdef CUST_SW_SERV
+           ,MEMS_TIMER/1000*SEND_N_QUATERNIONS,SEND_N_QUATERNIONS,
+           MEMS_TIMER/1000*QUAT_FLOAT_UPDATE_MUL_10MS
+#endif
+          );
+                    
+ /*
+    p_BLEdev = new BLE;
+    if (!p_BLEdev) {
+        printf("\r\nBLE Device creation failed\r\n");
+        return 0;
+    }        
+    p_BLEdev->init(bleInitComplete);         
+ */
+//    eventQueue.call_every(500, periodicCallback); 
+    BLE &ble = BLE::Instance();
+		p_BLEdev = &ble;
+    p_BLEdev->onEventsToProcess(scheduleBleEventsProcessing);
+    p_BLEdev->init(bleInitComplete);
+ 
+ for (; !ble_started; wait_ms(10));
+//    greenled = 0;//Switch OFF LED1
+    
+    /* set the BLE CB functions */
+    p_BLEdev->gattServer().onUpdatesEnabled(onUpdatesEnabledCallback);
+    p_BLEdev->gattServer().onUpdatesDisabled(onUpdatesDisabledCallback);
+/*    p_BLEdev->gattServer().onConfirmationReceived(onConfirmationReceivedCallback);    
+    p_BLEdev->gattServer().onDataSent(onDataSentCallback);
+    p_BLEdev->gattServer().onDataRead(onDataReadCallback);
+    p_BLEdev->gattServer().onDataWritten(onDataWriteCallback);
+*/		
+    p_BLEdev->gap().onConnection(onConnectionCallback);
+    p_BLEdev->gap().onDisconnection(onDisconnectionCallback);
+/*    p_BLEdev->gap().onTimeout(onTimeoutCallback);
+*/	
+    /* Initialize MotionFX library */
+#ifdef USE_SENSOR_FUSION_LIB       
+    bool DS3_OnBoard = DS3_ONBOARD;    
+    if (MotionFX_manager_init(DS3_OnBoard, magOffset)) {
+        MotionFX_manager_start_9X();
+        SensorFusionOK = true;
+        printf("SW      Service sensor fusion library added successfully\r\n");
+    } else {    /* sensor fusion lib init failed: likely because of wrong license */
+            printf("sensor fusion lib init failed: likely because of wrong license \n\r");
+        SensorFusionOK = false;     
+    }   
+#else 
+    printf("sensor fusion lib disabled \n\r");    
+    SensorFusionOK = false;     
+#endif
+         
+#ifdef CUST_CONFIG_SERV
+    p_customconfigservice = new CustomConfigService(*p_BLEdev);
+    if (!p_customconfigservice) {
+        printf("SW      Service W2ST calibration add FAILED!\n\r");
+        return 0;  
+    }
+    printf("SW      Service W2ST calibration added successfully\r\n");
+#endif
+#ifdef CUST_SENS_SERV
+		press_temp.enable();
+    acc_gyro.enable_x();
+    acc_gyro.enable_g();	
+    mag.enable();	
+    acc.enable();
+		
+    uint8_t id22=0, idLSM6=0, id303mag=0, id303acc=0;
+    press_temp.read_id(&id22);
+    acc_gyro.read_id(&idLSM6);				
+    mag.read_id(&id303mag);
+    acc.read_id(&id303acc);
+
+    printf("LS303acc ID %x LS303mag ID %x LSM6DSL ID %x LPS22HB ID %x \r\n", id303acc, id303mag, idLSM6, id22);	  
+    printf("\r\n");  	
+		
+    p_customsensorservice = new CustomSensorService(*p_BLEdev);
+    if (!p_customsensorservice) {
+        printf("\n\rHW      Service W2ST sensors add FAILED!\n\r");
+        return 0;
+    }
+    printf("\rHW      Service W2ST sensors added successfully\r\n");
+#endif       		
+#ifdef CUST_CONS_SERV
+    p_customconsoleservice = new CustomConsoleService(*p_BLEdev);
+    if (!p_customconsoleservice) {
+        printf("\n\rHW      Service W2ST console add FAILED!\n\r");
+        return 0;
+    }
+    printf("\rHW      Service W2ST console added successfully\r\n");
+#endif
+#ifdef CUST_SW_SERV
+        AxesRaw_TypeDef quat_axes[SEND_N_QUATERNIONS];
+        float QuatFloat[SEND_N_QUATERNIONS];        
+        if (SensorFusionOK) {
+            p_customsoftwareservice = new CustomSoftwareService(*p_BLEdev);
+            if (!p_customsoftwareservice) {
+                    printf("SW      Service W2ST quaternions add FAILED!\n\r");
+                    return 0;
+            }
+            printf("SW      Service W2ST quaternions added successfully\r\n");
+        }
+#endif      
+        
+        const static char     DEVICE_NAME[]        = BLE_DEV_NAME;
+    /* Setup advertising. */
+    p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
+//    p_BLEdev->gap().accumulateAdvertisingPayloadTxPower(txPower); 
+#ifdef USE_SENSOR_FUSION_LIB        
+    uint8_t dat[]= {0x01,0x80,0x00,0xFC,0x01,0x80};
+#else
+    uint8_t dat[]= {0x01,0x80,0x00,0xFC,0x00,0x00};
+#endif      
+    p_BLEdev->gap().accumulateScanResponse(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA,dat,6);    
+    p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::UNKNOWN);
+    p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
+
+ //   p_BLEdev->gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, SENS_SERVICE_UUID_128, sizeof(SENS_SERVICE_UUID_128));
+	
+    p_BLEdev->gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
+    p_BLEdev->gap().setAdvertisingInterval(BLE_ADVERTISING_INTERVAL);
+ 
+ 
+    printf("SERVER: BLE Stack Initialized\r\n");
+    printf("Starting Advertising...\n\r");
+    p_BLEdev->gap().startAdvertising();
+	
+    TimeStamp =0;
+    EnvTimer.attach_us(&Ticker_Env, ENV_TIMER);
+//    CalibTimer.attach_us(&Ticker_Calib, CALIB_TIMER );
+    MemsTimer.attach_us(&Ticker_Mems, MEMS_TIMER);
+
+    /* Control if the calibration is already available in memory */
+        if (SensorFusionOK) {
+            ReCallCalibrationFromMemory();
+
+            /* Switch on/off the LED according to calibration */
+            if(isCal) {
+//                    greenled =1;
+            } else {
+ //                   greenled =0;
+            }
+        }
+#ifdef CUST_SW_SERV        
+    uint32_t QuaternionNumber =0;
+    uint32_t CounterFloat =0;
+#endif
+		
+    Thread ThObjMainActivity;
+	  ThObjMainActivity.start(Callback<void()>(ThreadMainActivity));				
+				
+    eventQueue.dispatch_forever();
 }
+
+
+