CAN to BLE translator - and back

Dependencies:   BLE_API CANnucleo X_NUCLEO_IDB0XA1 mbed

Revision:
5:9f30eba41c77
Parent:
4:8c2cd88d2545
Child:
6:f85bc6e59111
--- a/main.cpp	Fri Apr 08 13:33:35 2016 +0000
+++ b/main.cpp	Fri Apr 08 14:30:50 2016 +0000
@@ -7,17 +7,15 @@
 
 #define BLE_GATT_CHAR_PROPERTIES_NOTIFY 0x10
 
-uint8_t CANId2BLESlot(unsigned int   id);
-unsigned int BLESlot2CANId(uint8_t   id);
-void onMsgReceived(void);
-void initCAN(void);
-
-void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params);
+//void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params);
 void writeCharCallback(const GattWriteCallbackParams  *params);
 void bleInitComplete(BLE::InitializationCompleteCallbackContext *params);
 void onBleInitError(BLE &ble, ble_error_t error);
 void initBLE(void);
 
+void periodicCallback(void);
+static volatile bool  triggerSensorPolling = false;
+
 
 DigitalOut      led(LED_PIN),CAN_show(PC_12);
 
@@ -29,29 +27,10 @@
 //const unsigned int TX_ID = 0x11;
 
 char shareddata[64][8]= { };
-
-uint8_t canWrPointer= 255;
-uint8_t canRdPointer= 255;
-uint8_t bleWrPointerA= 255;
-uint8_t bleRdPointerA= 255;
-uint8_t bleWrPointerB= 255;
-uint8_t bleRdPointerB= 255;
-
-const uint8_t firstBleRdPointer=1;
-const uint8_t lastBleRdPointer=14;
-
-const uint8_t firstCanRdPointer=62;
-const uint8_t lastCanRdPointer=63;
-
-uint8_t canRdLastPointer= 255; // puntatore per sapere che cosa ho mandato per ultimo. a runtime devo andare a modificarlo per sapere al ciclo dopo cosa ho già mandato
-uint8_t bleRdLastPointer= 255; // puntatore per sapere che cosa ho mandato per ultimo. a runtime devo andare a modificarlo per sapere al ciclo dopo cosa ho già mandato
+Ticker ticker;
 
 Timer           timerA; //questo contatoro serve solo per dire: appena è passato un po' di tempo -> esegui
 
-//CAN             can(PB_8, PB_9);  // CAN Rx pin name, CAN Tx pin name
-CANMessage      rxMsg;
-CANMessage      txMsg;
-
 BLE ble;
 
 uint16_t customServiceUUID  = 0xA000; // service UUID
@@ -76,39 +55,55 @@
 volatile bool   CANmsgAvailable = false;
 volatile bool   BLExmit = false;
 float stopTimer=2.0;
-
+uint8_t j=0,k=1;
+    
 int main()
 {
-    uint8_t j=0,k=firstBleRdPointer;
     // printf("\r\nBoard started\r\n");
     led = 1;       // turn LED on
-    CAN_show=1;
+     BLE::Instance().init(bleInitComplete);
+     /*
+     while (true) {
+        // check for trigger from periodicCallback()
+        if (triggerSensorPolling && ble.getGapState().connected) {
+            triggerSensorPolling = false;
 
-    bleRdLastPointer=lastBleRdPointer;
-    BLE::Instance().init(bleInitComplete);
-    CAN             can(PA_11, PA_12);  // CAN Rx pin name, CAN Tx pin name
-    CAN_show=0;
+            // Do blocking calls or whatever is necessary for sensor polling.
+            // In our case, we simply update the HRM measurement.
 
-    //canRdLastPointer=lastCanRdPointer;
-    can.frequency(500000);                     // set bit rate to 500kbps as S018
-    printf("\r\nCAN started at 500kbps\r\n");
+        } else {
+            ble.waitForEvent(); // low power wait for event
+        }
+    }*/
+     
+  
     timerA.start();
-    can.attach(&onMsgReceived, CAN::RxIrq);     // attach 'CAN receive-complete' interrupt handler
+  //  can.attach(&onMsgReceived, CAN::RxIrq);     // attach 'CAN receive-complete' interrupt handler
 
     while(true) {
-      //  if(ble.getGapState().connected) { 
-       if(ble.gap().getState().connected) {
+        //  if(ble.getGapState().connected) {
+        if(triggerSensorPolling && ble.getGapState().connected)
+        {
+               triggerSensorPolling=false;
+           //    printf("^");
+        }
+        else { 
+         // printf("v");
+           ble.waitForEvent();
+        }
+        
+        if(ble.gap().getState().connected) {
             stopTimer=0.2;
             symbol='!';
         } else {
             stopTimer=3;
-            ble.waitForEvent();
+          //  ble.waitForEvent();
             symbol='.';
         }
 
         if(timerA.read()>=stopTimer) {
-         //   BLExmit=ble.getGapState().connected;
-         BLExmit=ble.gap().getState().connected;
+            //   BLExmit=ble.getGapState().connected;
+            BLExmit=ble.gap().getState().connected;
             timerA.stop();
             timerA.reset();
             led=!led.read();
@@ -116,43 +111,35 @@
             timerA.start();
 
         }
-        if(CANmsgAvailable) {
-            CANmsgAvailable = false;               // reset flag for next use
-            can.read(rxMsg);                    // read message into Rx message storage
-            j=CANId2BLESlot(rxMsg.id);
-            if(j!=bleRdPointerA && j!=bleRdPointerB) {
-                
-                for(int i = 0; i < rxMsg.len; i++) {
-                    shareddata[j][i]=rxMsg.data[i];
-                    //          printf(" %x", rxMsg.data[i]);
-                }
-                //   printf("#");
-              
-            }
-        }
+    
         if(BLExmit) {
             BLExmit=false;
             retry++;
-          if(retry==0xff) ble.gap().startAdvertising();
-           printf ("%x  ",retry);
+            if(retry==0xff) ble.gap().startAdvertising();
+            printf ("%#x  ",retry);
             printf("@");
             k++;
-            if(k>lastBleRdPointer)
-                k=firstBleRdPointer;
+            if(k>1)
+                k=1;
             readValue[0]=k;
             for(int i=1; i<8; i++) {
                 readValue[i]=shareddata[k][i];
             }
-             for(int i=0; i<8; i++) {
-            printf ("%x",readValue[i]);
-         }
+            for(int i=0; i<8; i++) {
+                printf ("%x",readValue[i]);
+            }
             ble.updateCharacteristicValue(readChar.getValueHandle(), readValue,9);
-
-
         }
     }
 }
 
+void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
+{
+    (void)params;
+    printf("\r\nTarget loss... wait for reconnection \r\n");
+
+    BLE::Instance().gap().startAdvertising(); // restart advertising
+}
 void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
 {
     BLE&        ble   = params->ble;
@@ -166,7 +153,7 @@
     if (ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
         return;
     }
-    
+
     ble.gap().onDisconnection(disconnectionCallback);
 
     /* Setup primary service. */
@@ -181,10 +168,11 @@
     ble.gap().startAdvertising();
     ble.onDataWritten(writeCharCallback);
     ble.addService(customService);
+    ticker.detach();
+    ticker.attach(periodicCallback, 1); // blink LED every second
 
     printf("Starting Loop\r\n");
-
-
+  
 }
 void onBleInitError(BLE &ble, ble_error_t error)
 {
@@ -195,91 +183,26 @@
 
     /* Initialization error handling should go here */
 }
-void onMsgReceived(void)
-{
-    CANmsgAvailable = true;
-}
-uint8_t CANId2BLESlot(unsigned int   id)
+void periodicCallback(void)
 {
-    uint8_t retval=0;
-    switch(id) {
-        case 0x313:
-            retval=1;
-            break;
-        case 0x314:
-            retval=2;
-            break;
-        case 0x310:
-            retval=3;
-            break;
-        case 0x315:
-            retval=4;
-            break;
-        case 0x111:
-            retval=5;
-            break;
-        case 0x112:
-            retval=6;
-            break;
-        case 0x400:
-            retval=7;
-            break;
-        case 0x450:
-            retval=8;
-            break;
-        case 0x451:
-            retval=9;
-            break;
-        case 0x452:
-            retval=10;
-            break;
-        case 0x453:
-            retval=11;
-            break;
-        case 0x454:
-            retval=12;
-            break;
-        case 0x455:
-            retval=13;
-            break;
-        default:
-            retval=0;
-            break;
-    }
-    return retval;
+    led = !led; /* Do blinky on LED1 while we're waiting for BLE events */
+    /* Note that the periodicCallback() executes in interrupt context, so it is safer to do
+     * heavy-weight sensor polling from the main thread. */
+    if(!ble.getGapState().connected) {
+        printf("? ");
+        ticker.attach(periodicCallback, 1); // blink LED every 5 second
+    } else
+        ticker.attach(periodicCallback, 0.1); // blink LED every second
+
+    triggerSensorPolling = true;
 }
-unsigned int BLESlot2CANId(uint8_t   id)
-{
-    unsigned int retval=0;
-    switch(id) {
-        case 63:
-            retval=0x303;
-            break;
-        case 62:
-            retval=0x304;
-            break;
-        default:
-            retval=0x0;
-            break;
-    }
-    return retval;
-}
-
-void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
-{
-    (void)params;
-    printf("\r\nTarget loss... wait for reconnection \r\n");
-
-    BLE::Instance().gap().startAdvertising(); // restart advertising
-}
-
 void writeCharCallback(const GattWriteCallbackParams  *params)
 {
 
     uint8_t j=0;
 
     // check to see what characteristic was written, by handle
-    if(params->handle  == writeChar.getValueHandle()) {
+ /*   if(params->handle  == writeChar.getValueHandle()) {
         BLESlot2CANId(params->data[0]);
         printf("\n\r Data received: length = %d, data = ",params->len);
         if(canRdPointer != j && canRdPointer != j+1) {
@@ -296,5 +219,5 @@
             bleWrPointerA=255;
             bleWrPointerB=255;
         }
-    }
+    }*/
 }