Coordinator code

Dependencies:   EthernetInterface WebSocketClient mbed-rtos mbed

Revision:
0:4cb87eb1f914
diff -r 000000000000 -r 4cb87eb1f914 Xbee.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Xbee.cpp	Thu Feb 18 13:21:58 2016 +0000
@@ -0,0 +1,105 @@
+#include "Xbee.h"
+
+static bool frameStarted = false;
+static char readBuffer[128];
+static int  buffer = 0;
+
+// Fonction d'assignation du PAN ID
+void setPanId(Serial* xbee, unsigned long long panId)
+{
+    // Construction de la trame
+    const int frameLength = 16;
+    char frame[frameLength];
+    frame[0] = 0x7E; // Start delimiter
+    frame[1] = 0x00; // Length (MSB)
+    frame[2] = 0x0C; // Length (LSB)
+    frame[3] = 0x08; // AT Command
+    frame[4] = 0x00; // Frame ID
+    frame[5] = 'I';
+    frame[6] = 'D';
+    frame[7] = (panId >> 56) & 0xFF;
+    frame[8] = (panId >> 48) & 0xFF;
+    frame[9] = (panId >> 40) & 0xFF;
+    frame[10] = (panId >> 32) & 0xFF;
+    frame[11] = (panId >> 24) & 0xFF;
+    frame[12] = (panId >> 16) & 0xFF;
+    frame[13] = (panId >> 8) & 0xFF;
+    frame[14] = (panId >> 0) & 0xFF;
+    frame[15] = checksum(frame, 3, 15);
+    
+    // Envoi sur le UART
+    if (xbee->writeable())
+    {
+        for (int i = 0; i < frameLength; i++)
+        {
+            xbee->putc(frame[i]);
+        }
+    }
+}
+
+// Fonction de calcul du checksum
+char checksum(char* frame, int begin, int end)
+{
+    char sum = 0;
+
+    // Addition des bits
+    for (int i = begin; i < end; i++)
+    {
+        sum += frame[i];
+    }
+    
+    return 0xFF - sum;
+}
+
+// Fonction de lecture des données du Xbee
+bool readPacket(Serial* pc, Serial* xbee, char* output)
+{
+    if(xbee->readable())
+    {
+        int c = xbee->getc();
+        
+        // Début d'une trame
+        if (c == START_BYTE)
+        {
+            frameStarted = true;
+        }
+
+        // Ajout du caractère dans le buffer
+        if (frameStarted)
+        {
+            readBuffer[buffer++] = c;
+        }
+        
+        // Si la longueur de la trame a été lue
+        if (buffer > 3)
+        {
+            int length = (readBuffer[1] << 8 ) | (readBuffer[2] & 0xFF);
+
+            // Vérifier que la trame au complet a été reçue et que le checksum est valide
+            if (buffer == length + 4 &&
+                checksum(readBuffer, 3, buffer) == readBuffer[buffer])
+            {
+                // Fin de la trame
+                frameStarted = false;
+                parse(readBuffer, buffer, output);
+                buffer = 0;
+                return true;
+            }
+        }
+    }
+    
+    return false;
+}
+
+void parse(char* buffer, int size, char* output)
+{
+    if (size >= 17)
+    {
+        // Données utiles
+        int button = buffer[15];
+        short accX = buffer[16] | buffer[17] << 8;
+
+        // Formattage pour le serveur Websockets
+        sprintf(output, "Button = %i, Acceleration X = %i\r\n", button, accX);
+    }
+}