Hi,
I cannot seem to convert my integer value to the function pubsubClient with MQTT when I try to post it.
The function expects a (const char* , const char*) parameter. The first part is easy, that’s the topic. (“wemos/sleep/timing”) but in the second part I want to let it post a number of seconds it is going to sleep, stored in the sensorValue variable, coming from a potmeter value, multiplied by 4 so I stay within the 71 minute limit.
I have no other way of knowing how long it will sleep.
How do I get a const char* from an integer?
Hello,
If you use this sample code, it will convert an int to a const char*:
int your_int_value = 1; String(your_int_value).c_str()
For example, it will look something like this:
mqttClient.publish("esp", 2, true, String(your_int_value).c_str());
I hope that solves your problem and let me know your results. Regards,
Rui
invalid conversion from ‘int’ to ‘const uint8_t* {aka const unsigned char*}’ [-fpermissive]
(1st try)
and after making the int also unsigned:
invalid conversion from ‘int’ to ‘const uint8_t* {aka const unsigned char*}’ [-fpermissive]
// client.publish(“wemos/sleep/set”, String(sensorValue).c_str())
worked
client.publish(“wemos/sleep/set”, String(sensorValue).c_str());
worked. I realized I was using a different client. function call.
turning potmeter all the way to the left gave a MQTT message: wemos/sleep/set 40
and after 40 seconds it did not restart. …. hmmm
Of course it is not working. I am running this off the breadboard with the batteryshield and the sensors, and the RST to D0 shortcut for the sleeping!
Tried getting a value to the esp32 by MQTT worked. Now trying to get a parameter to a sleeping wemos by using the MQTT Retained option.
Well, I got a message there, but I could not get it to do anything with it due to conversion issues and the hated pointers. Finally I have something working.. The easy way by defining an array of numbers in a char. Because I cannot compare char to integer.. or a pointer.
********
#include
#include WiFi.h>
#include AsyncMqttClient.h>
#include OneWire.h>
#include DallasTemperature.h>
// Change the credentials below, so your ESP32 connects to your router
#define WIFI_SSID ""
#define WIFI_PASSWORD ""
// Change the MQTT_HOST variable to your Raspberry Pi IP address,
// so it connects to your Mosquitto MQTT broker
#define MQTT_HOST IPAddress(192)
#define MQTT_PORT 18
// Create objects to handle MQTT client
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
String temperatureString = ""; // Variable to hold the temperature reading
unsigned long previousMillis = 0; // Stores last time temperature was published
long interval = 600000; // interval at which to publish sensor readings in 1000/s
char minutes[] = {'0', '1','2', '3','4', '5','6', '7','8', '9'}; //array to payload
int ontvangentijd = 1; // variabele to contain payload
const int ledPin = 25; // GPIO where the LED is connected to
int ledState = LOW; // the current state of the output pin
int lstatus = 0; // feedback ledstatus via mqqt
long timer = 20000; // std timer in Ms.
int stemp = 0;
// GPIO where the DS18B20 is connected to
const int oneWireBus = 32;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch(event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
}
}
// Add more topics that want your ESP32 to be subscribed to
void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);
// ESP32 subscribed to esp32/led topic
uint16_t packetIdSub = mqttClient.subscribe("esp32/led", 0);
Serial.print("Subscribing at QoS 0, packetId: ");
Serial.println(packetIdSub);
// subscribe to sleeptimer topic
uint16_t packetIdSub2 = mqttClient.subscribe("esp32/timer", 0);
Serial.print("Subscribing at QoS 0, packetId: ");
Serial.println(packetIdSub2);
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println("Disconnected from MQTT.");
if (WiFi.isConnected()) {
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttPublish(uint16_t packetId) {
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
// You can modify this function to handle what happens when you receive a certain message in a specific topic
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
String messageTemp;
for (int i = 0; i = 2)
{
ontvangentijd =10; // want maximum is 19...
for (int i = 0; i < 10; i++)
{
if (payload[1] == minutes[i] )
{ ontvangentijd += i;
Serial.print(" [1] i: ");
Serial.print(i); } //debug
}
}else
{
ontvangentijd=0; // dan kijken we alleen naar t eerste getal
for (int j = 0; j < 10; j++)
{
if (payload[0] == minutes[j] )
{ ontvangentijd += j;
Serial.print(" [0] j: ");
Serial.print(j);//debug
}
}
}
Serial.print(" ontvangentijd: ");
Serial.println(ontvangentijd); //debug
if (ontvangentijd <=1) { ontvangentijd = 1; } // errorhandling
timer=(60000*ontvangentijd); // timer is set to X milliseconds
Serial.print(" timer: ");
Serial.println(timer); //debug
}
Serial.println("Publish received.");
Serial.print(" message: ");
Serial.println(messageTemp);
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void setup() {
pinMode(oneWireBus, INPUT_PULLUP); // soms rare waarden op de temp , zoals -127
// Start the DS18B20 sensor
sensors.begin();
// Define LED as an OUTPUT and set it LOW
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(115200);
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToWifi));
WiFi.onEvent(WiFiEvent);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
connectToWifi();
}
void loop() {
unsigned long currentMillis = millis();
// Every X number of seconds (interval = 5 seconds)
// it publishes a new MQTT message on topic esp32/temperature
// interval set to timervalue, comment to disable
interval = timer;
if (currentMillis - previousMillis >= interval) {
// Save the last time a new reading was published
previousMillis = currentMillis;
// New temperature readings
sensors.requestTemperatures();
stemp=sensors.getTempCByIndex(0); // rare waarden ondervangen.
if ((stemp 70)) {
temperatureString = "";
}else {
temperatureString = " " + String(stemp) + " " ;
//+ "C" + String(sensors.getTempFByIndex(0))+ "F" //ertussenweg
}
Serial.println(temperatureString);
if (sensors.isParasitePowerMode()) {
digitalWrite(ledPin, HIGH);
delay(1500);
digitalWrite(ledPin, LOW);
delay(1500);
digitalWrite(ledPin,HIGH) ;
}
// Publish an MQTT message on topic esp32/temperature with Celsius and Fahrenheit temperature readings
uint16_t packetIdPub2 = mqttClient.publish("esp32/temperature", 2, true, temperatureString.c_str());
Serial.print("Publishing on topic esp32/temperature at QoS 2, packetId: ");
Serial.println(packetIdPub2);
}
}