Hello,
I'll admit that I'm not an expert developer, and am trying to learn. So I'm probably missing something obvious. I'm developing a device to monitoring the critical electrical systems on my boat while I'm away from it. I've purchased an Ardunio Uno WIFI REV 2 and have setup the Arduino MQTT library. I have a few sensors connected which I can read and then publish to an MQTT topic. All that works great. But I also want to subscribe to several MQTT topics to get commands back that I can use to control variables in my program. I can subscribe to multiple topics and am receiving those messages. Where I'm struggling is getting the character array into something useful. In this section of code I am able to pull the char data out of the MQTT buffer into a SafeString. But from there I don't know what the correct method is to conver that data into something else. I've google a lot about the string methods in the Arduino like .toInt() but those don't seem to work on SafeString. Can anyone point me in the right direction?
void onMqttMessage(int messageSize) {
// we received a message, print out the topic and contents
Serial.print("Received a message with topic: ");
Serial.print(mqttClient.messageTopic());
Serial.print(" Length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available()) {
if (mqttClient.messageTopic() == commandUpdate) {
refresh_buf += (char)mqttClient.read();
} else if (mqttClient.messageTopic() == commandStartOffset)
soffset_buff +=(char)mqttClient.read();
}
Serial.println(refresh_buf);
refresh = refresh_buf.toInt(); //This is not valid
refresh_buf.clear();
Serial.println();
Serial.println();
}
Full Code:
/*
Development of Sensor Platform for Necessity, Designed to monitor the following
House Batter Bank Voltage
Starting Battery Bank
Tempurature
Humidity
GPS Location
Movement
*/
//Libraries
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h>
#include <DHT.h>
#include <SoftwareSerial.h>
#include <ArduinoBlue.h>
#include <EEPROM.h>
#include <SafeString.h>
// Wifi SSID and Password Information
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
// To connect with SSL/TLS:
// 1) Change WiFiClient to WiFiSSLClient.
// 2) Change port value from 1883 to 8883.
// 3) Change broker value to a server with a known SSL/TLS root certificate
// flashed in the WiFi module.
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
const char broker[] = "SERVER_Removed"; //MQTT Server
int port = 1883; //MQTT Server Port
char topicTemperature[] = "Necessity/Sensors/Temperature";
const char topicHumidity[] = "Necessity/Sensors/Humidity";
const char topicHouseBank[] = "Necessity/Sensors/HouseBank";
const char topicStartBank[] = "Necessity/Sensors/StartingBank";
const char commandUpdate[] = "Necessity/Commands/Update";
const char commandStartOffset[] = "Necessity/Commands/StartOffset";
createSafeString(refresh_buf, 10); //Refresh rate recevied from MQTT Server
createSafeString(soffset_buf, 10); //Starting Battery Voltage Correction Offset
int refresh = 0;
float soffset = 0;
const long interval = 10000; //Main Loop Delay Interval
unsigned long previousMillis = 0;
//int count = 0;
// Hardware Setup
//Battery Montiors
#define HOUSE_IN_PIN A0
#define STARTING_IN_PIN A1
// Floats for ADC voltage & Input voltage
float house_adc_voltage = 0.0;
float starting_adc_voltage = 0.0;
float house_voltage = 0.0;
float starting_voltage = 0.0;
// Floats for resistor values in divider (in ohms)
float R1 = 30000.0;
float R2 = 7500.0;
// Float for Reference Voltage
float ref_voltage = 5.0;
// Integer for ADC value
int adc_house_value = 0;
int adc_starting_value = 0;
//DHT Sensor
#define tempPin 2
#define DHTTYPE DHT11 // DHT 11
DHT dht(tempPin, DHTTYPE);
float necessityTemperature;
float necessityHumidity;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
//Initalize Temp/Humidity Sensor
Serial.println("Initalizing DHT Sensor");
dht.begin();
//Set Voltage Monitor Pins as Inputs
pinMode(HOUSE_IN_PIN, INPUT);
pinMode(STARTING_IN_PIN, INPUT);
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println("You're connected to the network");
Serial.println();
// You can provide a unique client ID, if not set the library uses Arduino-millis()
// Each client must have a unique client ID
// mqttClient.setId("clientId");
// You can provide a username and password for authentication
mqttClient.setUsernamePassword("user", "pass");
Serial.print("Attempting to connect to the MQTT broker: ");
Serial.println(broker);
if (!mqttClient.connect(broker, port)) {
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqttClient.connectError());
while (1);
}
Serial.println("You're connected to the MQTT broker!");
Serial.println();
mqttClient.onMessage(onMqttMessage);
Serial.println("Getting Inital Subscriptions");
mqttClient.subscribe(commandUpdate);
mqttClient.subscribe(commandStartOffset);
}
void loop() {
// call poll() regularly to allow the library to send MQTT keep alives which
// avoids being disconnected by the broker
mqttClient.poll();
// avoid having delays in loop, we'll use the strategy from BlinkWithoutDelay
// see: File -> Examples -> 02.Digital -> BlinkWithoutDelay for more info
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time a message was sent
previousMillis = currentMillis;
sensorRead();
sendToMQTTBroker();
storeDataToEeprom();
getFromMQTTBroker();
}
}
void sendToMQTTBroker() {
// send Temp
Serial.print("Sending message to topic: ");
Serial.println(topicTemperature);
mqttClient.beginMessage(topicTemperature);
mqttClient.print(necessityTemperature);
mqttClient.endMessage();
// send Temp
Serial.print("Sending message to topic: ");
Serial.println(topicHumidity);
mqttClient.beginMessage(topicHumidity);
mqttClient.print(necessityHumidity);
mqttClient.endMessage();
// send House Bank
Serial.print("Sending message to topic: ");
Serial.println(topicHouseBank);
mqttClient.beginMessage(topicHouseBank);
mqttClient.print(house_voltage);
mqttClient.endMessage();
// send House Bank
Serial.print("Sending message to topic: ");
Serial.println(topicStartBank);
mqttClient.beginMessage(topicStartBank);
mqttClient.print(starting_voltage);
mqttClient.endMessage();
Serial.println();
}
void getFromMQTTBroker() {
//Serial.print("Refresh Period: "); Serial.println(refresh);
}
void onMqttMessage(int messageSize) {
// we received a message, print out the topic and contents
Serial.print("Received a message with topic: ");
Serial.print(mqttClient.messageTopic());
Serial.print(" Length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available()) {
if (mqttClient.messageTopic() == commandUpdate) {
refresh_buf += (char)mqttClient.read();
} else if (mqttClient.messageTopic() == commandStartOffset)
soffset_buff +=(char)mqttClient.read();
}
Serial.println(refresh_buf);
refresh = refresh_buf.toInt();
refresh_buf.clear();
Serial.println();
Serial.println();
}
void sensorRead() {
//Get the temperature and humidity inside the boat
necessityTemperature = dht.readTemperature(true);
necessityHumidity = dht.readHumidity();
Serial.print("Temperature: "); Serial.println(necessityTemperature);
Serial.print("Humidity: "); Serial.println(necessityHumidity);
//Get the house bank voltages
// Read the Analog Input
adc_house_value = analogRead(HOUSE_IN_PIN);
// Determine voltage at ADC input
house_adc_voltage = (adc_house_value * ref_voltage) / 1024.0;
// Calculate voltage at divider input
house_voltage = house_adc_voltage / (R2 / (R1 + R2)) ;
Serial.print("House Voltage: "); Serial.println(house_voltage);
//Get the starting bank voltages
// Read the Analog Input
adc_starting_value = analogRead(STARTING_IN_PIN);
// Determine voltage at ADC input
starting_adc_voltage = (adc_starting_value * ref_voltage) / 1024.0;
// Calculate voltage at divider input
starting_voltage = starting_adc_voltage / (R2 / (R1 + R2)) ;
Serial.print("Starting Voltage: "); Serial.println(starting_voltage - .15);
Serial.println();
}
void storeDataToEeprom () {
//Serial.println(ssid);
//Serial.println(pass);
//Serial.println(strlen(ssid));
//Serial.println(strlen(pass));
//EEPROM.update(0, ssid);
}