Dependencies:   MQTT

mqtt.cpp

Committer:
MannyK
Date:
2019-12-06
Revision:
4:64c6fc70ddb7
Parent:
2:f10d6fecb345
Child:
5:e0d8e5e922f1

File content as of revision 4:64c6fc70ddb7:

/* mbed Microcontroller Library
 * Copyright (c) 2018 ARM Limited
 * SPDX-License-Identifier: Apache-2.0
 */

#include "mbed.h"
#include "MQTTNetwork.h"
#include "MQTTClient.h"
#include "MQTTmbed.h"
#include "mqtt.h"
#include <assert.h>
#include "AccCar.h"

// topics interested in 
#define POSITION_TOPIC "MQTT_Position0x25"
#define ROAD_TOPIC "MQTT_Road0x25"
#define CONTROL_TOPIC "MQTT_Control0x25"

#define DEBUG_MQTT
 
Serial mqtt_pc (USBTX, USBRX);


// empty constructor
mqtt::mqtt()
{
    
}

/*
    This function sets up the wifi module and connects it to the SSID 
    configured in the configuration file. It also prints out the MAC address 
    of the module, which is needed if you are trying to use campus wifi.
    This function returns NULL if there are any issues.
*/
WiFiInterface* mqtt::setup_wifi() {
    // Get a handle to the WiFi module
    WiFiInterface* wifi = WiFiInterface::get_default_instance();
    
    // Connect the module to the wifi, based on the SSID and password 
    // specified in the mbed_app.json configuration file
    // If you are using AirPennNet-Device, this will not succeed until the MAC
    // address (printed shortly after this) is registered
    mqtt_pc.printf("Connecting to wifi\r\n");
    int rc = wifi->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
    
    // Print out the MAC address of the wifi module. The MAC address is 
    // needed to register the device with AirPennNet-Device, so that you
    // can use the campus wifi
    mqtt_pc.printf("MAC Address: ");
    mqtt_pc.printf(wifi->get_mac_address());
    mqtt_pc.printf("\r\n");
    
    if (rc != 0) {
        mqtt_pc.printf("Problem connecting to wifi\r\n");   
        return NULL;
    } else {
        mqtt_pc.printf("Wifi connected\r\n");  
    }
      
    return wifi;
}

/*
    This function creates the MQTT client and connects it to the MQTT broker
    that we have setup for the course. If there are any errors with the 
    connection, it will return NULL
*/
MQTT::Client<MQTTNetwork, Countdown>* mqtt::setup_mqtt(MQTTNetwork& network) {
    // the hostname and port point to a Google Cloud MQTT server we setup for
    // this project
    const char* hostname = "34.68.206.11";
    int port = 1883;
    
    // Create the underlying network connection to the MQTT server
    mqtt_pc.printf("Connecting to %s:%d\r\n", hostname, port);
    int rc = network.connect(hostname, port);
    if (rc != 0) {
        mqtt_pc.printf("There was an error with the TCP connect: %d\r\n", rc);
        return NULL;
    }
    
    mqtt_pc.printf("Connected to %s:%d\r\n", hostname, port);
        
    // Connect the MQTT client to the server
    MQTT::Client<MQTTNetwork, Countdown>* temp_client = new MQTT::Client<MQTTNetwork, Countdown>(network);
    rc = temp_client->connect();
    if (rc != 0) {
        mqtt_pc.printf("There was an error with the MQTT connect: %d\r\n", rc);
        return NULL;
    }
    
    mqtt_pc.printf("MQTT connect successful!\r\n");
    
    return temp_client;
}

/*
    This function is the callback for when a message is received from the 
    MQTT broker. You register different callback functions with different
    topic subscriptions
*/
void mqtt::control_message_arrived(MQTT::MessageData& md)
{
    MQTT::Message &message = md.message;
    // make message
    control_msg_t* msg = new control_msg_t;
    assert(msg != NULL && message.payloadlen == sizeof(control_msg_t));
    
    // copy to our new pointer for some reason just taking the payload ptr is bad for mbed?
    memcpy(msg,message.payload,message.payloadlen);

#ifdef DEBUG_MQTT  
    //mqtt_pc.printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id);
    mqtt_pc.printf("speed %d id %d \r\n", msg->speed, msg->car_id);
#endif 

    // add our message to the queue no fucking clue what happens internally to
    // the message memory
    mqtt::instance()->add_to_control_queue(msg->car_id,msg);
    
    // free message
    delete msg;
}

/*
    This function sends a message to the test topic.
*/
int mqtt::send_position_msg( position_msg_t* msg ) 
{
    assert(msg != NULL && client != NULL);
    
    MQTT::Message message;

    // might be safest to memcopy thius seems to work
    //memcpy(message.payload,msg,sizeof(position_msg_t));
    message.payload = (void*)msg;
    message.payloadlen = sizeof(position_msg_t); 
    message.qos = MQTT::QOS1;

#ifdef DEBUG_MQTT
    mqtt_pc.printf("Sending a message!\r\n");
#endif

    int rc = client->publish(POSITION_TOPIC,message);
    assert(rc == 0);  

    client->yield(1000);
    return 0;
}

int mqtt::send_road_msg( road_msg_t* msg ) 
{
    assert(msg != NULL && client != NULL);
    
    MQTT::Message message;

    // might be safest to memcopy thius seems to work
    //memcpy(message.payload,msg,sizeof(position_msg_t));
    message.payload = (void*)msg;
    message.payloadlen = sizeof(position_msg_t); 
    message.qos = MQTT::QOS1;

#ifdef DEBUG_MQTT
    mqtt_pc.printf("Sending a message!\r\n");
#endif

    int rc = client->publish(ROAD_TOPIC,message);
    assert(rc == 0);  

    client->yield(1000);
    return 0;
}

void mqtt::bringup_network() {
    
    // 
    WiFiInterface* wifi = setup_wifi();
    assert(wifi != NULL);
    
    // Create the network object needed by the MQTT client
    new_network = new MQTTNetwork(wifi);
    
    // get client
    client = setup_mqtt(*new_network);
    assert(client != NULL);

    // Subscribe to a topic / register a callback  
    mqtt_pc.printf("Subscribing to topic %s\r\n", CONTROL_TOPIC);
    int rc = client->subscribe(CONTROL_TOPIC, MQTT::QOS1, control_message_arrived);
    assert(rc == 0);
    
    // make a road based of mqtt id
    mqtt_id = 0;
    if(strcmp(wifi->get_mac_address(),"2c:3a:e8:0b:75:06") == 0){
        mqtt_id = 0;
    }
    else{
        mqtt_id = 1;
    }
    
    mqtt_pc.printf("Subscribed, Setup complete!\r\n");
}


// manage callbacks from mqtt
void mqtt::manage_network()
{
    while(true)
    {
        //
        osEvent evt = position_queue.get();
        assert(evt.status == osEventMessage);
        
        //
        position_msg_t *message = (position_msg_t*)evt.value.p;
        send_position_msg(message);
        
        if (!road_queue.empty()){
            osEvent revt = road_queue.get();
            assert(revt.status == osEventMessage);
        //
            road_msg_t *road_msg = (road_msg_t*)revt.value.p;
            send_road_msg(road_msg);
        }
//      client->yield(100);
    }
}

//
// clean up goes here
void mqtt::shutdown_network()
{    
    //
    mqtt_pc.printf("shutting down mbed\r\n");
    
    //
    client->disconnect();
    delete new_network;
    
    //
    thread->terminate();
    delete thread;
}

// launch network manager thread
// responsible for pub sub 
void mqtt::setup_network()
{
    // bring up network if anything bad happens we will assert and crash
    bringup_network();
    
    // create a new thread thats sole purpose in life is to call client yield
    // what a sad life for a thread
    // calling yield is necessary as we will not get any messages for the mqtt 
    // serverwithout it
    thread = new Thread();
    assert(thread != NULL);
    thread->start( callback(this,&mqtt::manage_network) );
    
}