This is the first stage and sends data (temp, humidity) to mqtt server.
Dependencies: EthernetInterface MQTT RHT03 mbed-rtos mbed
main.cpp
- Committer:
- charliebsimms
- Date:
- 2014-05-22
- Revision:
- 0:7c734e5f2c45
File content as of revision 0:7c734e5f2c45:
#include "mbed.h" #include "EthernetInterface.h" #include "PubSubClient.h" #include "RHT03.h" #include <iostream> #include <sstream> #include <string> #include <iomanip> Serial pc(USBTX, USBRX); DigitalOut myled(LED1); char* serverIpAddr = "192.168.1.2"; int port = 1883; void callback(char* topic, char* payload, unsigned int len); PubSubClient mqtt(serverIpAddr, port, callback); EthernetInterface eth; void callback(char* topic, char* payload, unsigned int len) { printf("Topic: %s\r\n", topic); printf("Payload: %s\r\n\r\n", payload); //Send incoming payloads back to topic. //mqtt.publish("mbed/mybehive", payload, len); } int main() { float temp,hum; RHT03 humtemp(p24); string var; printf("\r\nMQTTClient Tester\r\n"); eth.init(); //Use DHCP eth.connect(); printf("IP Address is %s\n\r", eth.getIPAddress()); char clientID[] = "charlie"; /*Client nanme show for MQTT server*/ char pub_topic[] = "mbed/mybehive"; /*Publish to topic : "/mbed" */ if(!mqtt.connect(clientID)){ pc.printf("\r\nConnect to server failed ..\r\n"); return -1; } printf("\r\nConnect to server sucessed ..\r\n"); while(1) { mqtt.loop(); myled = 1; wait(3); pc.printf("Read temperature\n\r"); if(humtemp.readData() == RHT_ERROR_NONE) { //Gets the current temperature in centigrade temp = humtemp.getTemperatureC(); //Gets the current humidity in percentage hum = humtemp.getHumidity(); stringstream oss; oss << "{" << "\"temperature\":" << std::setprecision(4) << temp << "," << "\"humidity\":" << std::setprecision(4) << hum << "}"; string data = oss.str(); pc.printf("temperature is %f\n\r", temp); pc.printf("humidity is %f\n\r\n\r", hum); pc.printf("environment is %s\n\r\n\r", data.c_str()); char * value = new char [37]; strcpy(value, data.c_str()); mqtt.publish(pub_topic, value); } myled = 0; wait(3); } }