0
Dependencies: Cayenne-MQTT-mbed Servo nfc X_NUCLEO_IDW01M1v2 NetworkSocketAPI 13
main.cpp
- Committer:
- kapitaninternet
- Date:
- 2019-09-01
- Revision:
- 11:60c50eae8b81
- Parent:
- 10:8892a1436342
- Child:
- 12:32dbf8ff8d80
File content as of revision 11:60c50eae8b81:
#include "MQTTTimer.h" #include "CayenneMQTTClient.h" #include "MQTTNetworkIDW01M1.h" #include "SpwfInterface.h" #include "mbed.h" #include "XNucleoIKS01A2.h" // czujniki ruchu i otoczenia #include "XNucleoNFC01A1.h" // modul nfc #include "NDefLib/NDefNfcTag.h" #include "NDefLib/RecordType/RecordURI.h" AnalogIn ain(A0); DigitalOut led1(LED1); DigitalOut wifiLed(LED3); /* Instantiate the expansion board */ static XNucleoIKS01A2 *mems_expansion_board = XNucleoIKS01A2::instance(D14, D15, D4, D5); /* Retrieve the composing elements of the expansion board */ static HTS221Sensor *hum_temp = mems_expansion_board->ht_sensor; static LPS22HBSensor *press_temp = mems_expansion_board->pt_sensor; // Cayenne authentication info. This should be obtained from the Cayenne Dashboard. char* username = "68880f30-7425-11e9-beb3-736c9e4bf7d0"; char* password = "19f07b4d8806fe42bdda724980634f39d8e639ba"; char* clientID = "bb8e7cc0-74b9-11e9-94e9-493d67fd755e"; // WiFi network info. char* ssid = "Interneto"; char* wifiPassword = "matu1234"; /* Helper function for printing floats & doubles */ static char *print_double(char* str, double v, int decimalDigits=2) { int i = 1; int intPart, fractPart; int len; char *ptr; /* prepare decimal digits multiplicator */ for (;decimalDigits!=0; i*=10, decimalDigits--); /* calculate integer & fractinal parts */ intPart = (int)v; fractPart = (int)((v-(double)(int)v)*i); /* fill in integer part */ sprintf(str, "%i.", intPart); /* prepare fill in of fractional part */ len = strlen(str); ptr = &str[len]; /* fill in leading fractional zeros */ for (i/=10;i>1; i/=10, ptr++) { if (fractPart >= i) { break; } *ptr = '0'; } /* fill in (rest of) fractional part */ sprintf(ptr, "%i", fractPart); return str; } /** * Write a Ndef URI message linking to st.com site. * Write an NDef message with a Uri record linking the st.com site * @param nfcNucleo expansion board where write the NDef message */ SpwfSAInterface interface(D8, D2); // TX, RX MQTTNetwork<SpwfSAInterface> network(interface); CayenneMQTT::MQTTClient<MQTTNetwork<SpwfSAInterface>, MQTTTimer> mqttClient(network, username, password, clientID); /** * Print the message info. * @param[in] message The message received from the Cayenne server. */ void outputMessage(CayenneMQTT::MessageData& message) { switch (message.topic) { case COMMAND_TOPIC: printf("topic=Command"); break; case CONFIG_TOPIC: printf("topic=Config"); break; default: printf("topic=%d", message.topic); break; } printf(" channel=%d", message.channel); if (message.clientID) { printf(" clientID=%s", message.clientID); } if (message.type) { printf(" type=%s", message.type); } for (size_t i = 0; i < message.valueCount; ++i) { if (message.getValue(i)) { printf(" value=%s", message.getValue(i)); } if (message.getUnit(i)) { printf(" unit=%s", message.getUnit(i)); } } if (message.id) { printf(" id=%s", message.id); } printf("\n"); } /** * Handle messages received from the Cayenne server. * @param[in] message The message received from the Cayenne server. */ void messageArrived(CayenneMQTT::MessageData& message) { int error = 0; // Add code to process the message. Here we just ouput the message data. outputMessage(message); if (message.topic == COMMAND_TOPIC) { switch(message.channel) { case 0: // Set the onboard LED state led1 = atoi(message.getValue()); // Publish the updated LED state if ((error = mqttClient.publishData(DATA_TOPIC, message.channel, NULL, NULL, message.getValue())) != CAYENNE_SUCCESS) { printf("Publish LED state failure, error: %d\n", error); } break; } // If this is a command message we publish a response. Here we are just sending a default 'OK' response. // An error response should be sent if there are issues processing the message. if ((error = mqttClient.publishResponse(message.id, NULL, message.clientID)) != CAYENNE_SUCCESS) { printf("Response failure, error: %d\n", error); } } } /** * Connect to the Cayenne server. * @return Returns CAYENNE_SUCCESS if the connection succeeds, or an error code otherwise. */ int connectClient(void) { int error = 0; // Connect to the server. printf("Connecting to %s:%d\n", CAYENNE_DOMAIN, CAYENNE_PORT); while ((error = network.connect(CAYENNE_DOMAIN, CAYENNE_PORT)) != 0) { printf("TCP connect failed, error: %d\n", error); wait(2); } if ((error = mqttClient.connect()) != MQTT::SUCCESS) { printf("MQTT connect failed, error: %d\n", error); return error; } printf("Connected\n"); // Subscribe to required topics. if ((error = mqttClient.subscribe(COMMAND_TOPIC, CAYENNE_ALL_CHANNELS)) != CAYENNE_SUCCESS) { printf("Subscription to Command topic failed, error: %d\n", error); } if ((error = mqttClient.subscribe(CONFIG_TOPIC, CAYENNE_ALL_CHANNELS)) != CAYENNE_SUCCESS) { printf("Subscription to Config topic failed, error:%d\n", error); } // 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. mqttClient.publishData(SYS_VERSION_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, CAYENNE_VERSION); mqttClient.publishData(SYS_MODEL_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, "mbedDevice"); //mqttClient.publishData(SYS_CPU_MODEL_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, "CPU Model"); //mqttClient.publishData(SYS_CPU_SPEED_TOPIC, CAYENNE_NO_CHANNEL, NULL, NULL, "1000000000"); return CAYENNE_SUCCESS; } /** * Main loop where MQTT code is run. */ void loop(void) { if(network.connected()) { wifiLed = 1; } else { wifiLed = 0; } // Start the countdown timer for publishing data every 5 seconds. Change the timeout parameter to publish at a different interval. MQTTTimer timer(2500); while (true) { // Yield to allow MQTT message processing. mqttClient.yield(1000); // Check that we are still connected, if not, reconnect. if (!network.connected() || !mqttClient.connected()) { network.disconnect(); mqttClient.disconnect(); printf("Reconnecting\n"); while (connectClient() != CAYENNE_SUCCESS) { wait(2); printf("Reconnect failed, retrying\n"); } } // Publish some example data every few seconds. This should be changed to send your actual data to Cayenne. if (timer.expired()) { int error = 0; uint8_t id; float value1, value2; char buffer1[32], buffer2[32]; /* Enable all sensors */ hum_temp->enable(); press_temp->enable(); hum_temp->read_id(&id); printf("HTS221 humidity & temperature = 0x%X\r\n", id); press_temp->read_id(&id); printf("LPS22HB pressure & temperature = 0x%X\r\n", id); printf("\r\n"); hum_temp->get_temperature(&value1); hum_temp->get_humidity(&value2); printf("HTS221: [temp] %7s C, [hum] %s%%\r\n", print_double(buffer1, value1), print_double(buffer2, value2)); press_temp->get_temperature(&value1); press_temp->get_pressure(&value2); printf("LPS22HB: [temp] %7s C, [press] %s mbar\r\n", print_double(buffer1, value1), print_double(buffer2, value2)); float voltage_read = ain.read(); printf("---\r\n"); if ((error = mqttClient.publishData(DATA_TOPIC, 1, TYPE_TEMPERATURE, UNIT_CELSIUS, value1)) != CAYENNE_SUCCESS) { printf("Publish temperature failed, error: %d\n", error); } if ((error = mqttClient.publishData(DATA_TOPIC, 3, TYPE_VOLTAGE, UNIT_VOLTS, voltage_read)) != CAYENNE_SUCCESS) { printf("Publish voltage failed, error: %d\n", error); } if ((error = mqttClient.publishData(DATA_TOPIC, 2, TYPE_BAROMETRIC_PRESSURE, UNIT_HECTOPASCAL, value2)) != CAYENNE_SUCCESS) { printf("Publish barometric pressure failed, error: %d\n", error); } // Restart the countdown timer for publishing data every 2 seconds. Change the timeout parameter to publish at a different interval. timer.countdown_ms(2000); } } } /** * Main function. */ int main() { printf("Initializing interface\n"); interface.connect(ssid, wifiPassword, NSAPI_SECURITY_WPA2); // Set the default function that receives Cayenne messages. mqttClient.setDefaultMessageHandler(messageArrived); // Connect to Cayenne. if (connectClient() == CAYENNE_SUCCESS) { // Run main loop. loop(); } else { printf("Connection failed, exiting\n"); } if (mqttClient.connected()) mqttClient.disconnect(); if (network.connected()) network.disconnect(); return 0; }