mbed_wifi_MQTT_PM25

Dependencies:   mbed-os-example-wifi-DISCO_IOTBOARD_MQTT MQTT

main.cpp

Committer:
peng103617
Date:
11 months ago
Revision:
60:5e586131c009
Parent:
59:9bbcc1b368ba

File content as of revision 60:5e586131c009:

//MQTT+WIFI


#define logMessage printf
#define MQTTCLIENT_QOS2 1

#include "MQTTNetwork.h"
#include "MQTTmbed.h"
#include "MQTTClient.h"

int arrivedcount = 0;
//


#include "mbed.h"
#include "TCPSocket.h"

#define WIFI_IDW0XX1    2

#if (defined(TARGET_DISCO_L475VG_IOT01A) || defined(TARGET_DISCO_F413ZH))
#include "ISM43362Interface.h"
ISM43362Interface wifi(MBED_CONF_APP_WIFI_SPI_MOSI, MBED_CONF_APP_WIFI_SPI_MISO, MBED_CONF_APP_WIFI_SPI_SCLK, MBED_CONF_APP_WIFI_SPI_NSS, MBED_CONF_APP_WIFI_RESET, MBED_CONF_APP_WIFI_DATAREADY, MBED_CONF_APP_WIFI_WAKEUP, false);

#else // External WiFi modules

#if MBED_CONF_APP_WIFI_SHIELD == WIFI_IDW0XX1
#include "SpwfSAInterface.h"
SpwfSAInterface wifi(MBED_CONF_APP_WIFI_TX, MBED_CONF_APP_WIFI_RX);
#endif // MBED_CONF_APP_WIFI_SHIELD == WIFI_IDW0XX1

#endif


void messageArrived(MQTT::MessageData& md)
{
    MQTT::Message &message = md.message;
    //logMessage("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id);
    //logMessage("Payload %.*s\r\n", message.payloadlen, (char*)message.payload);
    //++arrivedcount;
}


const char *sec2str(nsapi_security_t sec)
{
    switch (sec) {
        case NSAPI_SECURITY_NONE:
            return "None";
        case NSAPI_SECURITY_WEP:
            return "WEP";
        case NSAPI_SECURITY_WPA:
            return "WPA";
        case NSAPI_SECURITY_WPA2:
            return "WPA2";
        case NSAPI_SECURITY_WPA_WPA2:
            return "WPA/WPA2";
        case NSAPI_SECURITY_UNKNOWN:
        default:
            return "Unknown";
    }
}

int scan_demo(WiFiInterface *wifi)
{
    WiFiAccessPoint *ap;

    printf("Scan:\n");

    int count = wifi->scan(NULL,0);
    printf("%d networks available.\n", count);

    /* Limit number of network arbitrary to 15 */
    count = count < 15 ? count : 15;

    ap = new WiFiAccessPoint[count];
    count = wifi->scan(ap, count);
    for (int i = 0; i < count; i++)
    {
        printf("Network: %s secured: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx RSSI: %hhd Ch: %hhd\n", ap[i].get_ssid(),
               sec2str(ap[i].get_security()), ap[i].get_bssid()[0], ap[i].get_bssid()[1], ap[i].get_bssid()[2],
               ap[i].get_bssid()[3], ap[i].get_bssid()[4], ap[i].get_bssid()[5], ap[i].get_rssi(), ap[i].get_channel());
    }

    delete[] ap;
    return count;
}

void http_demo(NetworkInterface *net)
{
    TCPSocket socket;
    nsapi_error_t response;

    printf("Sending HTTP request to www.arm.com...\n");

    // Open a socket on the network interface, and create a TCP connection to www.arm.com
    socket.open(net);
    response = socket.connect("www.arm.com", 80);
    if(0 != response) {
        printf("Error connecting: %d\n", response);
        socket.close();
        return;
    }

    // Send a simple http request
    char sbuffer[] = "GET / HTTP/1.1\r\nHost: www.arm.com\r\n\r\n";
    nsapi_size_t size = strlen(sbuffer);
    response = 0;
    while(size)
    {
        response = socket.send(sbuffer+response, size);
        if (response < 0) {
            printf("Error sending data: %d\n", response);
            socket.close();
            return;
        } else {
            size -= response;
            // Check if entire message was sent or not
            printf("sent %d [%.*s]\n", response, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
        
        }
    }

    // Recieve a simple http response and print out the response line
    char rbuffer[64];
    response = socket.recv(rbuffer, sizeof rbuffer);
    if (response < 0) {
        printf("Error receiving data: %d\n", response);
    } else {
        printf("recv %d [%.*s]\n", response, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
    }

    // Close the socket to return its memory and bring down the network interface
    socket.close();
}


Serial particle_sensor(PA_0,PA_1);//TX,RX
Serial pc(USBTX,USBRX);

float SDS018 ()
{
    uint8_t oneByte =0, myData[10],mCheck =0;
    uint32_t samples_par = 1000;
    int aux=0, t_init =0,i=0;
    float PM2_5_A = 0, PM10_A = 0, PM2_5_sum = 0, PM10_sum = 0,PM2_5_avg = 0, PM10_avg = 0,PM2_5,PM10;
    Timer t;
    
    time_t seconds = time(NULL);  
    //printf("Unix Epoch time = %d\r\n", seconds);
    //while(true){
       // t.start();
       // int time_start=t.read_ms();
        //pc.printf("\nPARTICLE\n\r");
        while (aux < samples_par) //while(t.read_ms()-t_init < time_avg)
        {
            if (aux==0)           
            t_init = t.read_ms();
            while (particle_sensor.readable()) { // whenever sensor transmits packet (every 1 s)
                oneByte = particle_sensor.getc();   
                if(oneByte == 0xAA) { 
                    myData[0] =  oneByte;
                    oneByte = particle_sensor.getc();
                if(oneByte == 0xC0) { 
                    myData[1] =  oneByte;
                    mCheck = 0;
                    for(i=0; i < 6; i++) { // DATA 1-6 received and crc calc
                        myData[i+2] = particle_sensor.getc();
                        //wait_ms(2);
                        mCheck += myData[i+2];
                        if(myData[6]==0x91)
                       {
                        //pc.printf("91\n\r");
                        }
                       if(myData[7]==0xA1)
                       {
                           //pc.printf("A1\n\r");
                        }
                    }
                    myData[8] = particle_sensor.getc();
                    myData[9] = particle_sensor.getc(); // tail (AB)
                    if(mCheck == myData[8]) { // if checksum OK
                        PM2_5 = ((uint16_t)myData[2] | (uint16_t)(myData[3]<<8));
                        PM10 = ((uint16_t)myData[4] | (uint16_t)(myData[5]<<8));        
                        PM2_5_A = (float) PM2_5/10;
                        PM10_A = (float) PM10/10;       
                        if(PM2_5_A*10 > 9999)
                            PM2_5_A = 999.9;
                        if(PM10_A*10 > 9999)
                            PM10_A = 999.9;                     
                        aux++;
                        PM2_5_sum+=PM2_5_A;  // sum samples for future averaging
                        
                        PM10_sum+=PM10_A;  // sum samples for future averaging
                        //printf("%3.2f,\t%3.2f\n\r", PM2_5_A, PM10_A); // CSV print:  PM2.5,  PM10
                        //printf("PM2_5_A = %3.2f", PM2_5_A); //PM2.5
                        return PM2_5_A;                   
                        } 
                    } // head2
                } // head1 
                                
            } // while readable()
           
          } 
}






int main()

{    



    pc.baud (115200) ;                       
                     
    int count = 0;

    printf("WiFi example\n\n");

    count = scan_demo(&wifi);
    if (count == 0) {
        printf("No WIFI APNs found - can't continue further.\n");
        return -1;
    }

    printf("\nConnecting to %s...\n", MBED_CONF_APP_WIFI_SSID);
    int ret = wifi.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
    //int ret = wifi.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA);
    if (ret != 0) {
        printf("\nConnection error\n");
        return -1;
    }

    printf("Success\n\n");
    printf("MAC: %s\n", wifi.get_mac_address());
    printf("IP: %s\n", wifi.get_ip_address());
    printf("Netmask: %s\n", wifi.get_netmask());
    printf("Gateway: %s\n", wifi.get_gateway());
    printf("RSSI: %d\n\n", wifi.get_rssi());

    http_demo(&wifi);

    //wifi.disconnect();

    printf("\Wifi Example Done,MQTT Example Start\n");
    
    // MQTT Example Start
    float version = 0.6;
    char* topic = "test";

    //logMessage("HelloMQTT: version is %.2f\r\n", version);

    NetworkInterface* network = &wifi;
    if (!network) {
        return -1;
    }

    MQTTNetwork mqttNetwork(network);

    MQTT::Client<MQTTNetwork, Countdown> client(mqttNetwork);

    const char* hostname = "172.20.10.3";
    int port = 1883;
    logMessage("Connecting to %s:%d\r\n", hostname, port);
    
    
    
    int rc = mqttNetwork.connect(hostname, port);
    
    if (rc != 0)
        logMessage("rc from TCP connect is %d\r\n", rc);

    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.MQTTVersion = 3;
    data.clientID.cstring = "mbed-sample";
    data.username.cstring = "testuser";
    data.password.cstring = "testpassword";
    if ((rc = client.connect(data)) != 0)
        logMessage("rc from MQTT connect is %d\r\n", rc);

    if ((rc = client.subscribe(topic, MQTT::QOS2, messageArrived)) != 0)
        logMessage("rc from MQTT subscribe is %d\r\n", rc);






  while(1)
  {
   
    MQTT::Message message;
    // QoS 0
    
    
    char buf[100];       
    printf("PM2.5 = %3.2f\r\n",SDS018 ());
    sprintf(buf, "PM2.5 = %3.2f\r\n",SDS018 ());
    
       
    message.qos = MQTT::QOS1;
    message.retained = false;
    message.dup = false;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf)+1;
    rc = client.publish(topic, message);
    client.yield(100);
     
    
   }
     
      
        
}