temperature_conversion.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <cstdio>
  2. #include <cstring>
  3. #include "temperature_conversion.h"
  4. #include <mosquittopp.h>
  5. mqtt_tempconv::mqtt_tempconv(const char *id, const char *host, int port) : mosquittopp(id)
  6. {
  7. int keepalive = 60;
  8. /* Connect immediately. This could also be done by calling
  9. * mqtt_tempconv->connect(). */
  10. connect(host, port, keepalive);
  11. };
  12. mqtt_tempconv::~mqtt_tempconv()
  13. {
  14. }
  15. void mqtt_tempconv::on_connect(int rc)
  16. {
  17. printf("Connected with code %d.\n", rc);
  18. if(rc == 0){
  19. /* Only attempt to subscribe on a successful connect. */
  20. subscribe(NULL, "temperature/celsius");
  21. }
  22. }
  23. void mqtt_tempconv::on_message(const struct mosquitto_message *message)
  24. {
  25. double temp_celsius, temp_fahrenheit;
  26. char buf[51];
  27. if(!strcmp(message->topic, "temperature/celsius")){
  28. memset(buf, 0, 51*sizeof(char));
  29. /* Copy N-1 bytes to ensure always 0 terminated. */
  30. memcpy(buf, message->payload, 50*sizeof(char));
  31. temp_celsius = atof(buf);
  32. temp_fahrenheit = temp_celsius*9.0/5.0 + 32.0;
  33. snprintf(buf, 50, "%f", temp_fahrenheit);
  34. publish(NULL, "temperature/fahrenheit", strlen(buf), buf);
  35. }
  36. }
  37. void mqtt_tempconv::on_subscribe(int mid, int qos_count, const int *granted_qos)
  38. {
  39. printf("Subscription succeeded.\n");
  40. }