Nucleo F411RE, SR04 and servomotor with Cayenne IoT version 2

Dependencies:   Cayenne-MQTT-mbed mbed Servo X_NUCLEO_IDW01M1v2 NetworkSocketAPI HCSR04

main.cpp

Committer:
stiotchallenge
Date:
2019-07-17
Revision:
12:dd98953c0a6d
Parent:
11:760e0ede36bb

File content as of revision 12:dd98953c0a6d:

/**
* Example app for using the Cayenne MQTT C++ library to send and receive example data. This example uses
* the X-NUCLEO-IDW01M1 WiFi expansion board via the X_NUCLEO_IDW01M1v2 library.
*/

#include "MQTTTimer.h"
#include "CayenneMQTTClient.h"
#include "MQTTNetworkIDW01M1.h"
#include "SpwfInterface.h"
#include "hcsr04.h"
#include "Servo.h"

// WiFi network info.
char* ssid = "iPhone";
char* wifiPassword = "abcd1234";

// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char* username = "4f3fbcb0-3796-11e9-ad96-c15442ccb423";
char* password = "9e099f3d9aaedd7b76ca94044c6bb488c3999e3c";
char* clientID = "4288d2f0-a5a9-11e9-9636-f9904f7b864b";

SpwfSAInterface interface(D8, D2); // TX, RX
MQTTNetwork<SpwfSAInterface> network(interface);
CayenneMQTT::MQTTClient<MQTTNetwork<SpwfSAInterface>, MQTTTimer> mqttClient(network, username, password, clientID);

DigitalIn button1(USER_BUTTON);
DigitalOut led1(LED1);
DigitalOut ledGreen(D11);
DigitalOut ledRed(D12);
HCSR04 sensor(D7, D6);
Servo myservo(D10);

int iotvalue;

//Function prototype new
MQTTTimer publishData(MQTTTimer, int, int);
MQTTTimer myFunction(MQTTTimer);

MQTTTimer myFunction (MQTTTimer timer){
    /**
    * Write your codes here.
    **/
    led1 = 1;
    wait(0.2);
    led1 = 0;
    wait(0.2);

//    ledGreen = iotvalue;
    
//ULTRASONIC + SERVO/////////////////////////////
    int openclose;
    long distance = sensor.distance();   
    printf("distance  %d  \n",distance);
    wait(1.0); // 1 sec
    if (distance > 50) {
        ledGreen = 0;
        ledRed = 1;   
        myservo = 1; //tutup
        wait(0.2);
        openclose = 0;
    }
    if (distance <50) {
        ledGreen = 1;
        ledRed = 0;
        myservo = 0; //buka
        wait(0.2);
        openclose = 1;
    }
    
    timer = publishData(timer, ledGreen, openclose);
    return timer;
}

MQTTTimer publishData(MQTTTimer timer, int data1, int data2){
     // Publish some example data every few seconds. This should be changed to send your actual data to Cayenne.
        if (timer.expired()) {
            int error = 0;
            if ((error = mqttClient.publishData(DATA_TOPIC, 1, TYPE_VOLTAGE, UNIT_DIGITAL, data1)) != CAYENNE_SUCCESS) {
                printf("Publish data failed, error: %d\n", error);
            }
            if ((error = mqttClient.publishData(DATA_TOPIC, 2, TYPE_VOLTAGE, UNIT_DIGITAL, data2)) != CAYENNE_SUCCESS) {
                printf("Publish data failed, error: %d\n", error);
            }
            // Restart the countdown timer for publishing data every 5 seconds. Change the timeout parameter to publish at a different interval.
            timer.countdown_ms(1500);
        }   
        return timer;
}

/**
* 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
            iotvalue = atoi(message.getValue());
            printf("From Cayenne = %d\n",iotvalue);
            // 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)
{
    // Start the countdown timer for publishing data every 5 seconds. Change the timeout parameter to publish at a different interval.
    MQTTTimer timer(1500);

    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");
            }
        }        
        timer = myFunction (timer);
    }
}

/**
* Main function.
*/
int main()
{   
    // Initialize the network interface.
    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;
}