IUT GEII SEM 4 ER

Dependencies:   C12832 EthernetInterface LM75B MFRC522 MMA7660 MQTT mbed-rtos mbed

Fork of GEII4ERS4 by Philippe Bazot

Files at this revision

API Documentation at this revision

Comitter:
syasya
Date:
Thu Feb 22 18:47:12 2018 +0000
Parent:
20:3045570c01ff
Commit message:
IUT GEII SEM4

Changed in this revision

C027.h Show annotated file Show diff for this revision Revisions of this file
K64F.h Show annotated file Show diff for this revision Revisions of this file
LPC1768.h Show annotated file Show diff for this revision Revisions of this file
MFRC522.lib Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/C027.h	Thu Jan 25 11:15:06 2018 +0000
+++ b/C027.h	Thu Feb 22 18:47:12 2018 +0000
@@ -27,8 +27,12 @@
 DigitalIn Up(A2); DigitalIn Down(A3); DigitalIn Left(A4); DigitalIn Right(A5); DigitalIn Click(D4);
 AnalogIn ain1 (A0); AnalogIn ain2 (A1);
 
+#define LED1_OFF 0
+#define LED1_ON 1
 #define LED2_OFF 0
 #define LED2_ON 1
+#define LED3_OFF 0
+#define LED3_ON 1
 
 #define DEFAULT_TYPE_NAME "iotsample-mbed-c027"
 
--- a/K64F.h	Thu Jan 25 11:15:06 2018 +0000
+++ b/K64F.h	Thu Feb 22 18:47:12 2018 +0000
@@ -19,7 +19,9 @@
 #define K64F_H
 
 C12832 lcd(D11, D13, D12, D7, D10);
+BusOut led1 (LED_RED);
 BusOut led2 (LED_BLUE);
+BusOut led3 (LED_GREEN);
 BusOut r (D5);
 BusOut g (D9);
 BusOut b (D8);
@@ -28,9 +30,12 @@
 DigitalIn Up(A2); DigitalIn Down(A3); DigitalIn Right(A4); DigitalIn Left(A5); DigitalIn Click(D4);
 AnalogIn ain1(A0); AnalogIn ain2(A1);
 
-#define LED2_OFF 1
-#define LED2_ON 0
-
+#define LED1_OFF 0
+#define LED1_ON 1
+#define LED2_OFF 0
+#define LED2_ON 1
+#define LED3_OFF 0
+#define LED3_ON 1
 #define DEFAULT_TYPE_NAME "iotsample-mbed-k64f"
 
 //#include "lpc_phy.h"
--- a/LPC1768.h	Thu Jan 25 11:15:06 2018 +0000
+++ b/LPC1768.h	Thu Feb 22 18:47:12 2018 +0000
@@ -19,7 +19,9 @@
 #define LPC1768_H
 
 C12832 lcd(p5, p7, p6, p8, p11);
+DigitalOut led1(LED1);
 DigitalOut led2(LED2);
+DigitalOut led3(LED3);
 PwmOut r(p23);
 PwmOut g(p24);
 PwmOut b(p25);
@@ -33,8 +35,12 @@
 AnalogIn ain1(p19);
 AnalogIn ain2(p20);
 
+#define LED1_OFF 0
+#define LED1_ON 1
 #define LED2_OFF 0
 #define LED2_ON 1
+#define LED3_OFF 0
+#define LED3_ON 1
 
 #define DEFAULT_TYPE_NAME "iotsample-mbed-lpc1768"
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MFRC522.lib	Thu Feb 22 18:47:12 2018 +0000
@@ -0,0 +1,1 @@
+https://mbed.org/users/AtomX/code/MFRC522/#63d729186747
--- a/main.cpp	Thu Jan 25 11:15:06 2018 +0000
+++ b/main.cpp	Thu Feb 22 18:47:12 2018 +0000
@@ -30,6 +30,11 @@
 #include "C12832.h"
 #include "Arial12x12.h"
 #include "rtos.h"
+#include "MFRC522.h"
+
+Serial pc(USBTX,USBRX);
+
+#define IP_BROKER "10.23.14.3" //IP address PC
 
 // Update this to the next number *before* a commit
 #define __APP_SW_REVISION__ "18"
@@ -42,12 +47,27 @@
 #define DEVICE_NAME ""     // Replace with your own name
 // End Of Configuration values needed to connect to IBM IoT Cloud
 
+/***********Configuration RFID***********/
+
+//KL25Z Pins for MFRC522 SPI interface
+#define SPI_MOSI   p5
+#define SPI_MISO   p6
+#define SPI_SCLK   p7
+#define SPI_CS     p21
+// KL25Z Pin for MFRC522 reset
+#define MF_RESET    p8
+// KL25Z Pins for Debug UART port
+#define UART_RX    p10
+#define UART_TX    p9
+// End Of Configuration RFID
+
 #define MQTT_PORT 1883
 #define MQTT_TLS_PORT 8883
 #define IBM_IOT_PORT MQTT_PORT
 
 #define MQTT_MAX_PACKET_SIZE 250
 
+
 #if defined(TARGET_UBLOX_C027)
 #warning "Compiling for mbed C027"
 #include "C027.h"
@@ -59,12 +79,12 @@
 #include "K64F.h"
 #endif
 
-
 bool quickstartMode = false;
-char org[11] = ORG;  
+char org[11] = ORG;
 char type[30] = TYPE;
 char id[30] = ID;                 // mac without colons
 char auth_token[30] = AUTH_TOKEN; // Auth_token is only used in non-quickstart mode
+char machaine [21]; // for transfer id to convert into string
 
 bool connected = false;
 bool mqttConnecting = false;
@@ -76,32 +96,35 @@
 int menuItem = 0;
 
 char* joystickPos = "CENTRE";
-int blink_interval = 0;
+int blink_interval;
 
 char* ip_addr = "";
 char* gateway_addr = "";
 char* host_addr = "";
 int connectTimeout = 1000;
 
+Serial     DebugUART(UART_TX, UART_RX);
+MFRC522    RfChip   (SPI_MOSI, SPI_MISO, SPI_SCLK, SPI_CS, MF_RESET);
+
 // If we wanted to manually set the MAC address,
 // this is how to do it. In this example, we take
 // the original Mbed Set MAC address and combine it
 // with a prefix of our choosing.
- /*
+/*
 extern "C" void $Super$$mbed_mac_address(char *s);
-extern "C" void $Sub$$mbed_mac_address(char *s) 
+extern "C" void $Sub$$mbed_mac_address(char *s)
 {
-    char originalMAC[6] = "";
-    $Super$$mbed_mac_address(originalMAC);
-    
-    char mac[6];
-    mac[0] = 0x00;
-    mac[1] = 0x08;
-    mac[2] = 0xdc;
-    mac[3] = originalMAC[3];
-    mac[4] = originalMAC[4];
-    mac[5] = originalMAC[5];
-    memcpy(s, mac, 6);
+   char originalMAC[6] = "";
+   $Super$$mbed_mac_address(originalMAC);
+
+   char mac[6];
+   mac[0] = 0x00;
+   mac[1] = 0x08;
+   mac[2] = 0xdc;
+   mac[3] = originalMAC[3];
+   mac[4] = originalMAC[4];
+   mac[5] = originalMAC[5];
+   memcpy(s, mac, 6);
 }
 */
 
@@ -113,40 +136,87 @@
 
 void red()
 {
-    r = 0.7; g = 1.0; b = 1.0;    // 1 is off, 0 is full brightness
+    r = 0.7;
+    g = 1.0;
+    b = 1.0;    // 1 is off, 0 is full brightness
 }
 
 void yellow()
 {
-    r = 0.7; g = 0.7; b = 1.0;    // 1 is off, 0 is full brightness
+    r = 0.7;
+    g = 0.7;
+    b = 1.0;    // 1 is off, 0 is full brightness
 }
 
 void green()
 {
-    r = 1.0; g = 0.7; b = 1.0;    // 1 is off, 0 is full brightness
+    r = 1.0;
+    g = 0.7;
+    b = 1.0;    // 1 is off, 0 is full brightness
 }
 
+void tag_rfid(void)
+{
+
+    // Look for new cards
+    /* if ( RfChip.PICC_IsNewCardPresent()) {
+
+         // Select one of the cards
+         if ( RfChip.PICC_ReadCardSerial()) {
+
+             // Print Card UID
+             pc.printf("Card UID: ");
+             for (uint8_t i = 0; i < RfChip.uid.size; i++) {
+                 pc.printf(" %02X", RfChip.uid.uidByte[i]);
+                 sprintf(machaine[2*i],"%02X",RfChip.uid.uidByte[i]);
+             }
+             pc.printf("\n\r");
+
+             // Print Card type
+             uint8_t piccType = RfChip.PICC_GetType(RfChip.uid.sak);
+             pc.printf("PICC Type: %s \n\r", RfChip.PICC_GetTypeName(piccType));
+         }*
+    bool on = false;
+    while (!connected) {
+        wait(2.0);
+    }*/
+}
 
 void flashing_yellow(void const *args)
 {
     bool on = false;
-    while (!connected && connack_rc != MQTT_NOT_AUTHORIZED && connack_rc != MQTT_BAD_USERNAME_OR_PASSWORD)    // flashing yellow only while connecting 
-    {
-        on = !on; 
-        if (on)
-            yellow();
-        else
-            off();   
+    while (1) {
+        if( RfChip.PICC_IsNewCardPresent()) {
+
+            // Select one of the cards
+            if ( RfChip.PICC_ReadCardSerial()) {
+
+                // Print Card UID
+                pc.printf("Card UID: ");
+                for (uint8_t i = 0; i < RfChip.uid.size; i++) {
+                    pc.printf(" %02X", RfChip.uid.uidByte[i]);
+                    sprintf(machaine+2*i,"%02X",RfChip.uid.uidByte[i]);
+                }
+                pc.printf("\n\r");
+
+                // Print Card type
+                uint8_t piccType = RfChip.PICC_GetType(RfChip.uid.sak);
+                pc.printf("PICC Type: %s \n\r",machaine);
+            }
+        }
         wait(0.5);
     }
+    
+    
 }
 
 
 void flashing_red(void const *args)  // to be used when the connection is lost
 {
+
+
     bool on = false;
-    while (!connected)
-    {
+    while (!connected) {
         on = !on;
         if (on)
             red();
@@ -157,13 +227,12 @@
 }
 
 
-void printMenu(int menuItem) 
+void printMenu(int menuItem)
 {
     static char last_line1[30] = "", last_line2[30] = "";
     char line1[30] = "", line2[30] = "";
-        
-    switch (menuItem)
-    {
+
+    switch (menuItem) {
         case 0:
             sprintf(line1, "IBM IoT Cloud");
             sprintf(line2, "Scroll with joystick");
@@ -180,14 +249,11 @@
             sprintf(line1, "MQTT Status:");
             if (mqttConnecting)
                 sprintf(line2, "Connecting... %d/5", retryAttempt);
-            else
-            {
+            else {
                 if (connected)
                     sprintf(line2, "Connected");
-                else
-                {
-                    switch (connack_rc)
-                    {
+                else {
+                    switch (connack_rc) {
                         case MQTT_CLIENTID_REJECTED:
                             sprintf(line2, "Clientid rejected");
                             break;
@@ -231,10 +297,9 @@
             sprintf(line2, "%d ms", connectTimeout);
             break;
     }
-    
-    if (strcmp(line1, last_line1) != 0 || strcmp(line2, last_line2) != 0)
-    {
-        lcd.cls(); 
+
+    if (strcmp(line1, last_line1) != 0 || strcmp(line2, last_line2) != 0) {
+        lcd.cls();
         lcd.locate(0, 0);
         lcd.printf(line1);
         strncpy(last_line1, line1, sizeof(last_line1));
@@ -248,24 +313,20 @@
 
 void setMenu()
 {
-    
-    if (Down)
-    {
+
+    if (Down) {
         joystickPos = "DOWN";
         if (menuItem >= 0 && menuItem < 9)
             printMenu(++menuItem);
-    } 
-    else if (Left)
+    } else if (Left)
         joystickPos = "LEFT";
     else if (Click)
         joystickPos = "CLICK";
-    else if (Up)
-    {
+    else if (Up) {
         joystickPos = "UP";
         if (menuItem <= 9 && menuItem > 0)
             printMenu(--menuItem);
-    }
-    else if (Right)
+    } else if (Right)
         joystickPos = "RIGHT";
     else
         joystickPos = "CENTRE";
@@ -274,8 +335,7 @@
 void menu_loop(void const *args)
 {
     int count = 0;
-    while(true)
-    {
+    while(true) {
         setMenu();
         if (++count % 10 == 0)
             printMenu(menuItem);
@@ -290,7 +350,7 @@
 void displayMessage(char* message)
 {
     lcd.cls();
-    lcd.locate(0,0);        
+    lcd.locate(0,0);
     lcd.printf("IBM IoT Cloud");
     lcd.locate(0,16);
     lcd.printf(message);
@@ -298,27 +358,27 @@
 
 
 int connect(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack)
-{  
+{
 
-    // The following 3 lines of code are ONLY used when connected to IBM Cloud !  
+    // The following 3 lines of code are ONLY used when connected to IBM Cloud !
     // const char* iot_ibm = ".messaging.internetofthings.ibmcloud.com";
     // char hostname[strlen(org) + strlen(iot_ibm) + 1];
     // sprintf(hostname, "%s%s", org, iot_ibm);
-    
+
     //Instead, for a connection to a local PC, specify HERE BELOW the IP @ of the local PC!!!
-    char hostname[]="192.168.0.6";
-    
-    
-    
+    char hostname[]=IP_BROKER;
+
+
+
     EthernetInterface& eth = ipstack->getEth();
     ip_addr = eth.getIPAddress();
     gateway_addr = eth.getGateway();
-    
+
     // Construct clientId - d:org:type:id
     char clientId[strlen(org) + strlen(type) + strlen(id) + 5];
     sprintf(clientId, "d:%s:%s:%s", org, type, id);
-    
-    // Network debug statements 
+
+    // Network debug statements
     LOG("=====================================\n");
     LOG("Connecting Ethernet.\n");
     LOG("IP ADDRESS: %s\n", eth.getIPAddress());
@@ -328,12 +388,11 @@
     LOG("Server Hostname: %s\n", hostname);
     LOG("Client ID: %s\n", clientId);
     LOG("=====================================\n");
-    
+
     netConnecting = true;
     int rc = ipstack->connect(hostname, IBM_IOT_PORT, connectTimeout);
-    if (rc != 0)
-    {
-        WARN("IP Stack connect returned: %d\n", rc);    
+    if (rc != 0) {
+        WARN("IP Stack connect returned: %d\n", rc);
         return rc;
     }
     netConnected = true;
@@ -344,22 +403,19 @@
     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
     data.MQTTVersion = 3;
     data.clientID.cstring = clientId;
-    
-    if (!quickstartMode) 
-    {        
+
+    if (!quickstartMode) {
         data.username.cstring = "use-token-auth";
         data.password.cstring = auth_token;
     }
-    
-    if ((rc = client->connect(data)) == 0) 
-    {       
+
+    if ((rc = client->connect(data)) == 0) {
         connected = true;
-        green();    
+        green();
         displayMessage("Connected");
         wait(1);
         displayMessage("Scroll with joystick");
-    }
-    else
+    } else
         WARN("MQTT connect returned %d\n", rc);
     if (rc >= 0)
         connack_rc = rc;
@@ -369,8 +425,9 @@
 
 
 int getConnTimeout(int attemptNumber)
-{  // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute
-   // after 20 attempts, retry every 10 minutes
+{
+    // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute
+    // after 20 attempts, retry every 10 minutes
     return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600;
 }
 
@@ -378,27 +435,25 @@
 void attemptConnect(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack)
 {
     connected = false;
-   
+
     // make sure a cable is connected before starting to connect
-    while (!linkStatus()) 
-    {
+    while (!linkStatus()) {
         wait(1.0f);
         WARN("Ethernet link not present. Check cable connection\n");
     }
-        
-    while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) 
-    {    
+
+    while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) {
         if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD)
             return; // don't reattempt to connect if credentials are wrong
-            
+
         Thread red_thread(flashing_red);
 
         int timeout = getConnTimeout(++retryAttempt);
         WARN("Retry attempt number %d waiting %d\n", retryAttempt, timeout);
-        
+
         // if ipstack and client were on the heap we could deconstruct and goto a label where they are constructed
         //  or maybe just add the proper members to do this disconnect and call attemptConnect(...)
-        
+
         // this works - reset the system when the retry count gets to a threshold
         if (retryAttempt == 5)
             NVIC_SystemReset();
@@ -412,25 +467,25 @@
 {
     MQTT::Message message;
     char* pubTopic = "iot-2/evt/status/fmt/json";
-            
+
     char buf[250];
     //sprintf(buf, "%0.4f \",\"%0.4f \",\"%0.4f", sensor.temp(),ain1.read(),ain2.read());
     sprintf(buf,
-     "{\"d\":{\"name\":\"IoT mbed\",\"accelX\":%0.4f,\"accelY\":%0.4f,\"accelZ\":%0.4f,\"temp\":%0.4f,\"joystick\":\"%s\",\"potentiometer1\":%0.4f,\"potentiometer2\":%0.4f,\"lat\":43.9,\"long\":7.25,\"Rfid\":12345}}",
-            MMA.x(), MMA.y(), MMA.z(), sensor.temp(), joystickPos, ain1.read(), ain2.read());
+            "{\"d\":{\"name\":\"IoT mbed\",\"accelX\":%0.4f,\"accelY\":%0.4f,\"accelZ\":%0.4f,\"temp\":%0.4f,\"joystick\":\"%s\",\"potentiometer1\":%0.4f,\"potentiometer2\":%0.4f,\"lat\":43.9,\"long\":7.25,\"Rfid\":\"%s\"}}",
+            MMA.x(), MMA.y(), MMA.z(), sensor.temp(), joystickPos, ain1.read(), ain2.read(),machaine);
     message.qos = MQTT::QOS0;
     message.retained = false;
     message.dup = false;
     message.payload = (void*)buf;
     message.payloadlen = strlen(buf);
-    
+
     LOG("Publishing %s\n", buf);
     return client->publish(pubTopic, message);
 }
 
 
 char* getMac(EthernetInterface& eth, char* buf, int buflen)    // Obtain MAC address
-{   
+{
     strncpy(buf, eth.getMACAddress(), buflen);
 
     char* pos;                                                 // Remove colons from mac address
@@ -444,88 +499,101 @@
 {
     MQTT::Message &message = md.message;
     char topic[md.topicName.lenstring.len + 1];
-    
+
     sprintf(topic, "%.*s", md.topicName.lenstring.len, md.topicName.lenstring.data);
-    
+
     LOG("Message arrived on topic %s: %.*s\n",  topic, message.payloadlen, message.payload);
-          
+
     // Command topic: iot-2/cmd/blink/fmt/json - cmd is the string between cmd/ and /fmt/
     char* start = strstr(topic, "/cmd/") + 5;
     int len = strstr(topic, "/fmt/") - start;
-    
-    if (memcmp(start, "blink", len) == 0)
-    {
+
+    if (memcmp(start, "blink", len) == 0) {
         char payload[message.payloadlen + 1];
         sprintf(payload, "%.*s", message.payloadlen, (char*)message.payload);
-    
+
         char* pos = strchr(payload, '}');
-        if (pos != NULL)
-        {
+        if (pos != NULL) {
             *pos = '\0';
-            if ((pos = strchr(payload, ':')) != NULL)
-            {
-                int blink_rate = atoi(pos + 1);       
-                blink_interval = (blink_rate <= 0) ? 0 : (blink_rate > 50 ? 1 : 50/blink_rate);
+            if ((pos = strchr(payload, ':')) != NULL) {
+                int blink_rate = atoi(pos + 1);
+                blink_interval = blink_rate+1;
+                //blink_interval = (blink_rate <= 0) ? 0 : (blink_rate > 50 ? 1 : 50/blink_rate);
             }
         }
-    }
-    else
+    } else
         WARN("Unsupported command: %.*s\n", len, start);
 }
 
 
 int main()
-{    
+{
+    // Set debug UART speed
+    DebugUART.baud(115200);
+
+    // Init. RC522 Chip
+    RfChip.PCD_Init();
+
+
     quickstartMode = (strcmp(org, "quickstart") == 0);
 
     lcd.set_font((unsigned char*) Arial12x12);  // Set a nice font for the LCD screen
-    
-    led2 = LED2_OFF; // K64F: turn off the main board LED 
-    
+
+    led1 = LED1_OFF; // K64F: turn off the main board LED
+    led2 = LED2_OFF; // K64F: turn off the main board LED
+    led3 = LED3_OFF; // K64F: turn off the main board LED
+
     displayMessage("Connecting");
     Thread yellow_thread(flashing_yellow);
-    Thread menu_thread(menu_loop);  
-    
+    Thread menu_thread(menu_loop);
+    //Thread rfid_thread(tag_rfid);//RFID reading
+
     LOG("***** IBM IoT Client Ethernet Example *****\n");
     MQTTEthernet ipstack;
     ethernetInitialising = false;
     MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack);
-    LOG("Ethernet Initialized\n"); 
-    
+    LOG("Ethernet Initialized\n");
+
     if (quickstartMode)
         getMac(ipstack.getEth(), id, sizeof(id));
-        
+
     attemptConnect(&client, &ipstack);
-    
-    if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD)    
-    {
+
+    if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) {
         red();
         while (true)
             wait(1.0); // Permanent failures - don't retry
     }
-    
-    if (!quickstartMode) 
-    {
+
+    if (!quickstartMode) {
         int rc = 0;
         if ((rc = client.subscribe("iot-2/cmd/+/fmt/json", MQTT::QOS1, messageArrived)) != 0)
-            WARN("rc from MQTT subscribe is %d\n", rc); 
+            WARN("rc from MQTT subscribe is %d\n", rc);
     }
-    
-    blink_interval = 0;
+
+    //blink_interval = 0;
     int count = 0;
-    while (true)
-    {
-        if (++count == 2500)  // Here is the count to change the number of publish/second
-        {               // Publish a message every second
-            if (publish(&client, &ipstack) != 0) 
+    while (true) {
+        if (++count == 250) { // Here is the count to change the number of publish/second 2.5s
+            // Publish a message every second
+            if (publish(&client, &ipstack) != 0)
                 attemptConnect(&client, &ipstack);   // if we have lost the connection
             count = 0;
         }
-        
-        if (blink_interval == 0)
+
+        if (blink_interval == 1) {//KO
+            led1 = LED1_ON;
             led2 = LED2_OFF;
-        else if (count % blink_interval == 0)
-            led2 = !led2;
+            led3 = LED3_OFF;
+        } else if (blink_interval == 2) {//OK
+            led1 = LED1_OFF;
+            led2 = LED2_ON;
+            led3 = LED3_OFF;
+        } else if (blink_interval == 3)  {//UNKNOWN
+            led1 = LED1_OFF;
+            led2 = LED2_OFF;
+            led3 = LED3_ON;
+        }
         client.yield(10);  // allow the MQTT client to receive messages
     }
 }