Snippet Tag: Losant Temperature Humidity Sensor

MQTT Publish and Subscribe

void reconnectMQTT(){ Serial.println("setting up mqtt"); while(!mqttCli.connected()){ if(mqttCli.connect("ESP8266Client123456789")==true){ Serial.println("connected"); String subTopic = String("channels/"+ String(channelID) + "/subscribe/json/" + String(readAPIKey)); int subTopicLength = subTopic.length()+1; char subTopicBuffer[subTopicLength]; subTopic.toCharArray(subTopicBuffer,subTopicLength); String pubMessage = "status=MQTTPUBLISH"; String pubTopic =String("channels/"+String(channelID)+"/publish/"+String(writeAPIKey)); int pubTopicLength = pubTopic.length()+1; char pubTopicBuffer[pubTopicLength]; pubTopic.toCharArray(pubTopicBuffer,pubTopicLength); //Publish to MQTT Broker Serial.println(mqttCli.publish(pubTopicBuffer, pubMessage.c_str()) ? "Published" : "NotPublished"); //Subscribe to MQTT Broker Serial.println(mqttCli.subscribe(subTopicBuffer) ? "Subscribed" : "Unsbscribed"); }else{ Serial.print("failed, rc="); Serial.println(mqttCli.state()); delay(1000); } } } //———-WiFiCallback———–// void taskWiFiCallback(){ Serial.println("taskWiFiCallbackStarted"); Serial.print("timeout for this task: t"); Serial.println(tWiFi.getTimeout()); if(!mqttCli.connected()){ Serial.println("Client not connected"); reconnectMQTT(); } String topicString ="channels/"+String(channelID)+"/publish/"+String(writeAPIKey); int topicLength = topicString.length()+1; char topicBuffer[topicLength]; topicString.toCharArray(topicBuffer,topicLength+1); Serial.println(topicBuffer); String dataString = String("field1="+ String(tempC,1) + "&field2=" +

Read More »