//Subscriber
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h>
//#include "arduino_secrets.h"
#define DELAY_LETTURA_SERIALE 20
#define LUNGHEZZA_COMANDO_SERIALE 50
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "Davide05"; // your network SSID
char pass[] = "facciolacacca"; // your network password
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
const char broker[] = "broker.hivemq.com";
int port = 1883;
const char nome[] = "calvinomqtt5dit/davide_racco";
int i = 0;
char nome_e_cognome[LUNGHEZZA_COMANDO_SERIALE];
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
}
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to 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();
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();
// set the message receive callback
mqttClient.onMessage(onMqttMessage);
Serial.print("Subscribing to topic: ");
Serial.println(nome);
Serial.println();
// subscribe to a topic
mqttClient.subscribe(nome);
// topics can be unsubscribed using:
// mqttClient.unsubscribe(topic);
Serial.print("Topic: ");
Serial.print(nome);
Serial.println();
}
void loop() {
// call poll() regularly to allow the library to receive MQTT messages and
// send MQTT keep alive which avoids being disconnected by the broker
mqttClient.poll();
}
void onMqttMessage(int messageSize) {
// we received a message, print out the topic and contents
Serial.println("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()) {
Serial.print((char)mqttClient.read());
}
Serial.println();
Serial.println();
}