CAN to BLE translator - and back

Dependencies:   BLE_API CANnucleo X_NUCLEO_IDB0XA1 mbed

Revision:
7:b834d20f9aa1
Parent:
6:f85bc6e59111
--- a/main.cpp	Fri Apr 08 14:39:43 2016 +0000
+++ b/main.cpp	Tue Apr 12 06:32:27 2016 +0000
@@ -10,29 +10,37 @@
 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 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;
+
+
+void initMEM(void);
+void dumpMEM(void);
 
-Ticker ticker;
+CANMessage      rxMsg;
+CANMessage      txMsg;
+
+BLE ble;
+
+char shareddata[64][8]= { };
 
 DigitalOut      led(LED_PIN),CAN_show(PC_12);
+DigitalIn button(PC_13);
 
+const uint8_t firstBleRdPointer=1;
+const uint8_t lastBleRdPointer=14;
+const uint8_t firstCanRdPointer=57;
+const uint8_t lastCanRdPointer=63;
 
 const static char     DEVICE_NAME[]        = "STNucleo - RGM - FM";
-static const uint16_t uuid16_list[]        = {0xFFFF};
+const static uint16_t uuid16_list[]        = {0xFFFF};
 
-//const unsigned int RX_ID = 0x10;
-//const unsigned int TX_ID = 0x11;
-
-char shareddata[64][8]= { };
+static volatile bool  triggerSensorPolling = false;
 
 uint8_t canWrPointer= 255;
 uint8_t canRdPointer= 255;
@@ -41,31 +49,19 @@
 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
 
-Timer           timerA; //questo contatoro serve solo per dire: appena è passato un po' di tempo -> esegui
+Ticker ticker;      //synchronous counter - IRQ enabled
+Timer           timerA; //unsynchronous counter  - no IRQ 
 
-//CAN             can(PB_8, PB_9);  // CAN Rx pin name, CAN Tx pin name
-CANMessage      rxMsg;
-CANMessage      txMsg;
-
-BLE ble;
+//CAN             can(PB_8, PB_9);  // alternatives for CAN Rx pin name, CAN Tx pin name
 
 uint16_t customServiceUUID  = 0xA000; // service UUID
 uint16_t readCharUUID       = 0xA001; // read characteristic UUID
 uint16_t writeCharUUID      = 0xA002; // write characteristic UUID
 
 static uint8_t readValue[128] = {0};
-
-
-
 ReadOnlyArrayGattCharacteristic<uint8_t,  sizeof(readValue)> readChar(readCharUUID, readValue, BLE_GATT_CHAR_PROPERTIES_NOTIFY , NULL,0); //aggiunto il BLE_GATT_CHAR_PROPERTIES_NOTIFY => appena arriva lo rimanda
 
 static uint8_t writeValue[128] = {0};
@@ -73,49 +69,53 @@
 
 GattCharacteristic *characteristics[] = {&readChar, &writeChar};
 GattService         customService(customServiceUUID, characteristics,  sizeof(characteristics) / sizeof(GattCharacteristic *));
+
 uint8_t retry=1;
-uint8_t readdata[20]= {};
 char symbol=' ';
+
 volatile bool   CANmsgAvailable = false;
 volatile bool   BLExmit = false;
+bool signal=true;
+
 float stopTimer=2.0;
 
+uint8_t readdata[20]= {}; //BLE data
+char kantMsg[8]= {0};   //CAN data
+
 int main()
 {
-    uint8_t j=0,k=firstBleRdPointer;
-    // printf("\r\nBoard started\r\n");
+    uint8_t j=0,k=0;
+    int mcan=0;
+    initMEM();
+    printf("\r\nBoard started\r\n");
     led = 1;       // turn LED on
-    CAN_show=1;
-
     bleRdLastPointer=lastBleRdPointer;
+    canRdPointer=lastCanRdPointer;
     BLE::Instance().init(bleInitComplete);
     CAN             can(PA_11, PA_12);  // CAN Rx pin name, CAN Tx pin name
-    CAN_show=0;
 
     //canRdLastPointer=lastCanRdPointer;
     can.frequency(500000);                     // set bit rate to 500kbps as S018
-    printf("\r\nCAN started at 500kbps\r\n");
+    printf("CAN started at 500kbps\r\n");
     timerA.start();
     can.attach(&onMsgReceived, CAN::RxIrq);     // attach 'CAN receive-complete' interrupt handler
-
-
     while(true) {
         //  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='!';
+            stopTimer=0.1;
+
         } else {
-            stopTimer=3;
+
+            stopTimer=1;
+            //stopTimer=5;
             //  ble.waitForEvent();
-            symbol='.';
+
         }
 
         if(timerA.read()>=stopTimer) {
@@ -124,8 +124,26 @@
             timerA.stop();
             timerA.reset();
             led=!led.read();
-            printf("%c\r\n",symbol);
             timerA.start();
+            if(!button) dumpMEM();
+            
+            
+            if(++canRdPointer>lastCanRdPointer) {
+                canRdPointer=firstCanRdPointer;
+             }
+            mcan = BLESlot2CANId(canRdPointer);
+             for(int m=0; m<8; m++) {
+                kantMsg[m] = shareddata[canRdPointer][m];
+            }
+            if(can.write(CANMessage(mcan, kantMsg, 8))) {              // transmit message
+            //if(can.write(txMsg)) {              // transmit message
+           //     printf("CAN message sent %x, 0x%.3x",canRdPointer, mcan);
+             //    for(int c=0; c<8; c++) {
+             //        printf(" %.2x",kantMsg[c]);
+             //    }
+             //    printf("\r\n");
+            }
+
 
         }
         if(CANmsgAvailable) {
@@ -133,32 +151,37 @@
             can.read(rxMsg);                    // read message into Rx message storage
             j=CANId2BLESlot(rxMsg.id);
             if(j!=bleRdPointerA && j!=bleRdPointerB) {
-
+                //  printf("CAN message rcvd %.2x, 0x%.3x \r\n",j,rxMsg.id);
                 for(int i = 0; i < rxMsg.len; i++) {
                     shareddata[j][i]=rxMsg.data[i];
-                             // printf(" %x", rxMsg.data[i]);
+                    // printf(" %.2x",rxMsg.data[i]);
                 }
-                //   printf("#");
-
+                //printf("\r\n");
             }
         }
         if(BLExmit) {
             BLExmit=false;
             retry++;
             if(retry==0xff) ble.gap().startAdvertising();
-            printf ("%x  ",retry);
-            printf("@");
+          //  printf ("%#x  ",retry);
             k++;
             if(k>lastBleRdPointer)
                 k=firstBleRdPointer;
             readValue[0]=k;
+          //  printf (" <%.2x ---",readValue[0]);
             for(int i=1; i<8; i++) {
                 readValue[i]=shareddata[k][i];
+          //      printf ("%.2x ",readValue[i]);
             }
-            for(int i=0; i<8; i++) {
-                printf ("%x",readValue[i]);
+            readValue[8]= ++k;;
+          //  printf ("> <%.2x ---",readValue[8]);
+
+            for(int i=9; i<18; i++) {
+                readValue[i]=shareddata[k][i-9];
+           //     printf ("%.2x ",readValue[i]);
             }
-            ble.updateCharacteristicValue(readChar.getValueHandle(), readValue,9);
+           // printf (">\n\r");
+            ble.updateCharacteristicValue(readChar.getValueHandle(), readValue,18);
         }
     }
 }
@@ -182,7 +205,7 @@
     /* Setup primary service. */
 
     /* Setup advertising. */
-    printf("Setup of Advertising\r\n");
+    printf("Setup of BLE Advertising\r\n");
     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::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
@@ -211,6 +234,52 @@
 {
     CANmsgAvailable = true;
 }
+
+void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
+{
+    (void)params;
+    printf("\r\nTarget loss... wait for reconnection \r\n");
+
+    BLE::Instance().gap().startAdvertising(); // restart advertising
+    dumpMEM();
+}
+
+void writeCharCallback(const GattWriteCallbackParams  *params)
+{
+
+    uint8_t j=0;
+
+    // check to see what characteristic was written, by handle
+    if(params->handle  == writeChar.getValueHandle()) {
+        j= BLESlot2CANId(params->data[0]);
+        printf("\n\r Data received: length = %d, data = ",params->len);
+        if(canRdPointer != j && canRdPointer != j+1) {
+            bleWrPointerA=j;
+            bleWrPointerB=j+1;
+            for(int x=0; x < 9; x++) {
+                printf("%c",params->data[x]);
+                shareddata[j][x]=params->data[x];
+            }
+            for(int x=9; x < 18; x++) {
+                printf("%c",params->data[x]);
+                shareddata[j+1][x-9]=params->data[x];
+            }
+            bleWrPointerA=255;
+            bleWrPointerB=255;
+        }
+    }
+}
+void periodicCallback(void)
+{
+    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;
+}
+
 uint8_t CANId2BLESlot(unsigned int   id)
 {
     uint8_t retval=0;
@@ -265,58 +334,52 @@
     unsigned int retval=0;
     switch(id) {
         case 63:
+            retval=0x301;
+            break;
+        case 62:
+            retval=0x302;
+            break;
+        case 61:
             retval=0x303;
             break;
-        case 62:
+        case 60:
             retval=0x304;
             break;
+        case 59:
+            retval=0x101;
+            break;
+        case 58:
+            retval=0x102
+            ;
+            break;
+        case 57:
+            retval=0x040;
+            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)
+void initMEM(void)
 {
-
-    uint8_t j=0;
-
-    // check to see what characteristic was written, by handle
-    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) {
-            bleWrPointerA=j;
-            bleWrPointerB=j+1;
-            for(int x=0; x < 9; x++) {
-                printf("%c",params->data[x]);
-                shareddata[j][x]=params->data[x];
-            }
-            for(int x=9; x < 18; x++) {
-                printf("%c",params->data[x]);
-                shareddata[j+1][x-9]=params->data[x];
-            }
-            bleWrPointerA=255;
-            bleWrPointerB=255;
+    for(int im = 0; im<64; im++) {
+        for (int jm=0; jm<8; jm++) {
+            shareddata[im][jm]=0x00;
         }
     }
+    for (int jm=0; jm<8; jm++) {
+        kantMsg[jm]=0;
+    }
 }
-void periodicCallback(void)
+void dumpMEM(void)
 {
-     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;
+    printf("\r\n --- Memory Dump ---");
+    for(int im = 0; im<64; im++) {
+        printf("\r\n%.2x", im);
+        for (int jm=0; jm<8; jm++) {
+            printf(" %.2x", shareddata[im][jm]);
+        }
+    }
+    printf("\r\n --- End of Dump ---\r\n");
 }