Jan Kowalski / Program_KPG_2019

Dependencies:   Cayenne-MQTT-mbed Servo nfc X_NUCLEO_IDW01M1v2 NetworkSocketAPI 13

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "MQTTTimer.h"
00002 #include "CayenneMQTTClient.h"
00003 #include "MQTTNetworkIDW01M1.h"
00004 #include "SpwfInterface.h"
00005 #include "mbed.h"
00006 #include "XNucleoIKS01A2.h" // czujniki ruchu i otoczenia
00007 #include "XNucleoNFC01A1.h" // modul nfc
00008 #include "NDefLib/NDefNfcTag.h"
00009 #include "NDefLib/RecordType/RecordURI.h"
00010 #include "Servo.h"                                                                                           //biblioteka z funkcjami mbed
00011 #include "XNucleoIKS01A2.h"                                                                                     //biblioteka ze sterownikiem plytki wykonującej pomiary (IKS)
00012 #include "XNucleoNFC01A1.h"                                                                                     //biblioteka ze sterownikiem plytki NFC
00013 #include "NDefLib/NDefNfcTag.h"                                                                                 //biblioteka z funkcjami plytki NFC - nadawanie tagu NFC
00014 #include "NDefLib/RecordType/RecordText.h"
00015 
00016 /* Instantiate the expansion board */
00017 static XNucleoIKS01A2 *mems_expansion_board = XNucleoIKS01A2::instance(D14, D15, D4, D5);
00018     //instance the board with the default paramiters
00019 I2C i2cChannel(XNucleoNFC01A1::DEFAULT_SDA_PIN,XNucleoNFC01A1::DEFAULT_SDL_PIN);                            
00020 XNucleoNFC01A1 *nfcNucleo = XNucleoNFC01A1::instance(i2cChannel);
00021 
00022 /* Retrieve the composing elements of the expansion board */
00023 static HTS221Sensor *hum_temp = mems_expansion_board->ht_sensor;
00024 static LPS22HBSensor *press_temp = mems_expansion_board->pt_sensor;
00025 
00026 NDefLib::Message msg;
00027 
00028 // Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
00029 char* username = "68880f30-7425-11e9-beb3-736c9e4bf7d0";
00030 char* password = "19f07b4d8806fe42bdda724980634f39d8e639ba";
00031 char* clientID = "bb8e7cc0-74b9-11e9-94e9-493d67fd755e";
00032 
00033 AnalogIn ain(A0); //pin do pomiaru napiecia
00034 DigitalOut myLed(LED2);
00035 Servo myservo(PA_6); // pin do sterowania serwo
00036 bool manualControl = false; // reczne sterowanie
00037 // DigitalOut actuatorPin2(PA_7); 
00038 float voltageMultiplier = 1.0; // mnoznik do wyskalowania odczytu napiecia z pinu A0
00039 int publishInterval = 1000; // co ile publikowac dane na cayenne
00040 float voltageChangeLevel = 1.5; // napiecie powyzej ktorego ma poruszyc serwo
00041 
00042 // dane do WiFi.
00043 char* ssid = "Interneto";
00044 char* wifiPassword = "matu1234";
00045 
00046 SpwfSAInterface interface(D8, D2); // TX, RX
00047 MQTTNetwork<SpwfSAInterface> network(interface);
00048 CayenneMQTT::MQTTClient<MQTTNetwork<SpwfSAInterface>, MQTTTimer> mqttClient(network, username, password, clientID);
00049 
00050 void messageArrived(CayenneMQTT::MessageData& message)
00051 {
00052     int error = 0;
00053     if (message.topic == COMMAND_TOPIC) {
00054         switch(message.channel) {
00055         case 4:
00056             // Set the onboard LED state & actuator PIN
00057             myLed = atoi(message.getValue());
00058             wait(0.1);
00059             myservo = myservo <= 0 ? 0.5 : -0.1;
00060             // actuatorPin2 = atoi(message.getValue());
00061             // Publish the updated LED state
00062             if ((error = mqttClient.publishData(DATA_TOPIC, message.channel, NULL, NULL, message.getValue())) != CAYENNE_SUCCESS) {
00063                 printf("Publish LED state failure, error: %d\n", error);
00064             }
00065             break;
00066         case 6:
00067             // ustaw prog napiecia do wywolaniaobrotu serwa
00068             voltageChangeLevel = atof(message.getValue());
00069             
00070             // Publish the updated LED state
00071             if ((error = mqttClient.publishData(DATA_TOPIC, message.channel, NULL, NULL, message.getValue())) != CAYENNE_SUCCESS) {
00072                 printf("Publish LED state failure, error: %d\n", error);
00073             }
00074             break;
00075         case 7:
00076             // przelacz manualne sterowanie
00077             manualControl = manualControl ? false : true;
00078             
00079             // Publish the updated LED state
00080             if ((error = mqttClient.publishData(DATA_TOPIC, message.channel, NULL, NULL, manualControl ? 1 : 0)) != CAYENNE_SUCCESS) {
00081                 printf("Take manual control: %d\n", error);
00082             }
00083             break;
00084           }
00085         }
00086         
00087         // If this is a command message we publish a response. Here we are just sending a default 'OK' response.
00088         // An error response should be sent if there are issues processing the message.
00089         if ((error = mqttClient.publishResponse(message.id, NULL, message.clientID)) != CAYENNE_SUCCESS) {
00090             printf("Response failure, error: %d\n", error);
00091         }
00092 }
00093 
00094 
00095 /**
00096 * Connect to the Cayenne server.
00097 * @return Returns CAYENNE_SUCCESS if the connection succeeds, or an error code otherwise.
00098 */
00099 int connectClient(void)
00100 {
00101     int error = 0;
00102     // Connect to the server.
00103     printf("Connecting to %s:%d\n", CAYENNE_DOMAIN, CAYENNE_PORT);
00104     while ((error = network.connect(CAYENNE_DOMAIN, CAYENNE_PORT)) != 0) {
00105         printf("TCP connect failed, error: %d\n", error);
00106         wait(2);
00107     }
00108 
00109     if ((error = mqttClient.connect()) != MQTT::SUCCESS) {
00110         printf("MQTT connect failed, error: %d\n", error);
00111         return error;
00112     }
00113     printf("Connected\n");
00114 
00115     // Subscribe to required topics.
00116     if ((error = mqttClient.subscribe(COMMAND_TOPIC, CAYENNE_ALL_CHANNELS)) != CAYENNE_SUCCESS) {
00117         printf("Subscription to Command topic failed, error: %d\n", error);
00118     }
00119     if ((error = mqttClient.subscribe(CONFIG_TOPIC, CAYENNE_ALL_CHANNELS)) != CAYENNE_SUCCESS) {
00120         printf("Subscription to Config topic failed, error:%d\n", error);
00121     }
00122 
00123     // Send device info. Here we just send some example values for the system info. These should be changed to use actual system data, or removed if not needed.
00124     mqttClient.publishData(SYS_VERSION_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, CAYENNE_VERSION);
00125     mqttClient.publishData(SYS_MODEL_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, "mbedDevice");
00126 
00127     return CAYENNE_SUCCESS;
00128 }
00129 
00130 static void write_message(XNucleoNFC01A1 *nfcNucleo,NDefLib::Message &msg){                                     //funkcja uruchamiajaca proces tworzenia tagu NFC                    
00131     NDefLib::NDefNfcTag& tag = nfcNucleo->get_M24SR().get_NDef_tag();
00132     //open the i2c session with the nfc chip
00133     if(tag.open_session()){
00134         printf("Session opened\r\n");
00135 
00136         nfcNucleo->get_led1()=! nfcNucleo->get_led1();                                                          //zapala led1 przy przesylaniu danych przez I2C
00137         
00138         //write the tag
00139         if(tag.write(msg)){
00140             printf("message wrote\r\n");
00141             nfcNucleo->get_led2()=!nfcNucleo->get_led2();                                                       //zapala led2 przy tworzeniu tagu NFC
00142         }//if
00143 
00144         //close the i2c session
00145         if(tag.close_session()){
00146             printf("Session closed\r\n");
00147             nfcNucleo->get_led3()=!nfcNucleo->get_led3();                                                       //zapala led2 przy zakonczeniu przesylu danych przez I2C
00148         }
00149     }//if open session
00150 }
00151 
00152 void loop(void)
00153 {
00154     float voltage_read = 0;
00155     NDefLib::RecordURI rUri(NDefLib::RecordURI::HTTPS,"cayenne.mydevices.com/shared/5d7376a3a4b14e4ee5849b49");
00156     msg.add_record(&rUri);
00157     
00158 
00159     // timer do publikacji wiadomosci mqtt
00160     MQTTTimer timer(publishInterval);
00161 
00162     while (true) {
00163         // wyslij wiadomosc z adresem panelu sterowania przez NFC
00164         write_message(nfcNucleo,msg);
00165         mqttClient.yield(1000);
00166 
00167         // sprawdz polaczenie z siecia i klientem mqtt, jesli brak sprobuj polaczyc ponownie
00168         if (!network.connected() || !mqttClient.connected()) {
00169             //network.disconnect();
00170             mqttClient.disconnect();
00171             while (connectClient() != CAYENNE_SUCCESS) {
00172                 wait(2);
00173             }
00174         }
00175 
00176         // Publish data every few seconds. This should be changed to send your actual data to Cayenne.
00177         if (timer.expired()) {
00178             int error = 0;
00179             
00180             uint8_t id;
00181             float value1, value2, value3;
00182             // char buffer1[32], buffer2[32];
00183   
00184             /* Enable all sensors */
00185             hum_temp->enable();
00186             press_temp->enable();
00187             hum_temp->read_id(&id);
00188             press_temp->read_id(&id);
00189             hum_temp->get_temperature(&value1);
00190             hum_temp->get_humidity(&value3);
00191             // press_temp->get_temperature(&value1);
00192             press_temp->get_pressure(&value2);
00193             // printf("LPS22HB: [temp] %7s C, [press] %s mbar\r\n", print_double(buffer1, value1), print_double(buffer2, value2));
00194 
00195             voltage_read = ain.read() * voltageMultiplier;
00196 
00197             if ((error = mqttClient.publishData(DATA_TOPIC, 1, TYPE_TEMPERATURE, UNIT_CELSIUS, value1 - 3)) != CAYENNE_SUCCESS) {
00198                 printf("Publish temperature failed, error: %d\n", error);
00199             }
00200             
00201             if ((error = mqttClient.publishData(DATA_TOPIC, 5, TYPE_RELATIVE_HUMIDITY, UNIT_PERCENT, value3)) != CAYENNE_SUCCESS) {
00202                 printf("Publish humidity failed, error: %d\n", error);
00203             }
00204 
00205             if ((error = mqttClient.publishData(DATA_TOPIC, 3, TYPE_VOLTAGE, UNIT_VOLTS, voltage_read)) != CAYENNE_SUCCESS) {
00206                 printf("Publish voltage failed, error: %d\n", error);
00207             }
00208 
00209             if ((error = mqttClient.publishData(DATA_TOPIC, 6, TYPE_VOLTAGE, UNIT_VOLTS, voltageChangeLevel)) != CAYENNE_SUCCESS) {
00210                 printf("Publish voltage change level failed, error: %d\n", error);
00211             }
00212             
00213             if ((error = mqttClient.publishData(DATA_TOPIC, 2, TYPE_BAROMETRIC_PRESSURE, UNIT_HECTOPASCAL, value2)) != CAYENNE_SUCCESS) {
00214                 printf("Publish barometric pressure failed, error: %d\n", error);
00215             }
00216             // Restart the countdown timer for publishing data every 2 seconds. Change the timeout parameter to publish at a different interval.
00217             timer.countdown_ms(publishInterval);
00218         }
00219 
00220       // jesli przekroczono ustawione napiecie o 5%, to zmien stan serwa
00221       if(!manualControl & voltage_read > voltageChangeLevel*1.05f)
00222       {
00223           // zmien pozycję serwa na pozycje otwartą
00224           myservo = 0.5;
00225       } else if(!manualControl & voltage_read < voltageChangeLevel*0.95f) // jesli napiecie spadlo ponizej 95% ustalonego napiecia, zmien stan serwa
00226       {
00227           myservo = -0.1;
00228         }
00229     }
00230 }
00231 
00232 int main()
00233 {   
00234     myLed = 0;
00235     myservo = -0.1;
00236     
00237     interface.connect(ssid, wifiPassword, NSAPI_SECURITY_WPA2);
00238     mqttClient.setDefaultMessageHandler(messageArrived);
00239 
00240     // Connect to Cayenne.
00241     if (connectClient() == CAYENNE_SUCCESS) {
00242         // Run main loop.
00243         loop();
00244     }
00245         
00246     if (mqttClient.connected())
00247         mqttClient.disconnect();
00248     if (network.connected())
00249         network.disconnect();
00250     return 0;
00251 }