This is the first stage and sends data (temp, humidity) to mqtt server.

Dependencies:   EthernetInterface MQTT RHT03 mbed-rtos mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "EthernetInterface.h"
00003 #include "PubSubClient.h"
00004 #include "RHT03.h" 
00005 #include <iostream>
00006 #include <sstream>
00007 #include <string>
00008 #include <iomanip>
00009 
00010 Serial pc(USBTX, USBRX);
00011 DigitalOut myled(LED1);
00012 
00013 char* serverIpAddr = "192.168.1.2";  
00014 int port = 1883; 
00015 
00016 
00017 void callback(char* topic, char* payload, unsigned int len);
00018 PubSubClient mqtt(serverIpAddr, port, callback);
00019 EthernetInterface  eth;
00020 
00021 void callback(char* topic, char* payload, unsigned int len)
00022 {
00023     printf("Topic: %s\r\n", topic);
00024     printf("Payload: %s\r\n\r\n", payload);
00025     
00026     //Send incoming payloads back to topic.
00027     //mqtt.publish("mbed/mybehive", payload, len);
00028 }
00029 
00030 int main() {
00031 
00032     float temp,hum;
00033     RHT03 humtemp(p24); 
00034     string var;
00035     
00036     printf("\r\nMQTTClient Tester\r\n");
00037     eth.init(); //Use DHCP
00038     eth.connect();
00039 
00040     printf("IP Address is %s\n\r", eth.getIPAddress());  
00041     
00042     char clientID[] = "charlie";   /*Client nanme show for MQTT server*/
00043     char pub_topic[] = "mbed/mybehive";   /*Publish to topic : "/mbed" */
00044 
00045     
00046     if(!mqtt.connect(clientID)){
00047         pc.printf("\r\nConnect to server failed ..\r\n");
00048         return -1;
00049     }
00050     
00051     printf("\r\nConnect to server sucessed ..\r\n");
00052       
00053     while(1) {
00054         mqtt.loop();
00055         myled = 1;
00056         wait(3);
00057 
00058         pc.printf("Read temperature\n\r");
00059         if(humtemp.readData() == RHT_ERROR_NONE) 
00060         {
00061             //Gets the current temperature in centigrade
00062             temp = humtemp.getTemperatureC();
00063             //Gets the current humidity in percentage 
00064             hum = humtemp.getHumidity(); 
00065             
00066             stringstream oss;
00067             oss << "{" << "\"temperature\":" << std::setprecision(4) << temp << "," << "\"humidity\":" << std::setprecision(4) << hum << "}";
00068             
00069             string data = oss.str();            
00070             pc.printf("temperature is %f\n\r", temp);
00071             pc.printf("humidity is %f\n\r\n\r", hum);
00072             pc.printf("environment is %s\n\r\n\r", data.c_str());
00073             char * value = new char [37];
00074             strcpy(value, data.c_str());
00075             mqtt.publish(pub_topic, value);
00076         }
00077         myled = 0;
00078         wait(3);
00079     }
00080 }