Newer
Older
const char ssid[] = "AndroidAP438F_84";//"Galaxy A52s 5G8EA7_84";//"DaBroswitch"; // your network SSID (name)
const char pass[] = "yhpu9011";//"daje666.";//"iotLab/00"; // your network password (use for WPA, or use as key for WEP)
const char broker[] = "192.168.254.194";//"192.168.72.194";//"luci.local";//"192.168.1.157"//"test.mosquitto.org";
/*
ArduinoMqttClient - WiFi Advanced Callback
This example connects to a MQTT broker and subscribes to a single topic,
it also publishes a message to another topic every 10 seconds.
When a message is received it prints the message to the serial monitor,
it uses the callback functionality of the library.
It also demonstrates how to set the will message, get/set QoS,
duplicate and retain values of messages.
The circuit:
- Arduino MKR 1000, MKR 1010 or Uno WiFi Rev.2 board
This example code is in the public domain.
*/
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h> // for MKR1000 change to: #include <WiFi101.h>
#include <avr/wdt.h>
//#include <PubSubClient.h>
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
// 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. ???
//#include <time.h>
//#include <WiFiUdp.h>
//#include <NTPClient.h>
//WiFiUDP ntpUDP;
//NTPClient timeClient(ntpUDP);
//randomSeed(analogRead(0));
const String clientID = "aindout";//+(String)random(300)+(String)random(300)+(String)random(300);
const String mqttUser = "gruppo2";//"pissir";
const String mqttPassword = "funziona";//"pissir2020";
//PubSubClient mqttClient(wifiClient);
//const char broker[] = "193.206.52.98";//smartcity-challenge
// broker non funzionanti: localhost, tcp://localhost, luci.local
int port = 1883;
const String willTopic = "arduino/will";
const String requestTopic = "to/all";
const String inTopic = "to/";
const String outTopic = "from/";
const String statusTopic = "gm/station/status";
const String dom_subdom_service = "gruppo2/luci/arduino";
const String receiveTopic = inTopic+dom_subdom_service+"/#";
const String jsonBegin = "{";
const String descriptionBegin = dom_subdom_service+"\":[\n";
const String descriptionAN0 = "{\"name\":\"AN0\",\"type\":\"analogin\"},\n";
const String descriptionAN1 = "{\"name\":\"AN1\",\"type\":\"analogin\"},\n";
const String descriptionAN2 = "{\"name\":\"AN2\",\"type\":\"analogin\"},\n";
const String descriptionEnd = "]";
const String jsonEnd = "}";
const String description = "{\""+descriptionBegin+descriptionAN0+descriptionAN1+descriptionAN2+descriptionEnd+"\"}";
// define sensors on the 6 Analog inputs
const int number_of_sensors = 3;
const int sensor[number_of_sensors] = {A0, A1, A2};//, A3, A4, A5};
/*
A0 = sensore di luce
A1 = sensore di temperatura
A2 = sensore di suono
*/
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 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 Arduin-millis()
// Each client must have a unique client ID
mqttClient.setId(clientID);
// You can provide a username and password for authentication
mqttClient.setUsernamePassword(mqttUser, mqttPassword);
// set a will message, used by the broker when the connection dies unexpectantly
// you must know the size of the message before hand, and it must be set before connecting
String willPayload = "oh no!";
bool willRetain = true;
int willQos = 1;
//mqttClient.beginWill(willTopic, willPayload.length(), willRetain, willQos);
//mqttClient.print(willPayload);
//mqttClient.endWill();
//mqttClient.setId(clientID);
//mqttClient.setUsernamePassword(mqttUser,mqttPassword);
//Serial.print("Attempting to connect to the MQTT broker: ");
//Serial.println(broker);
//mqttClient.setServer(broker,port);
//if (!mqttClient.connect(clientID,mqttUser,mqttPassword,willTopic,willQos,willRetain,willPayload,true)) {
if(!mqttClient.connect(broker,port)){
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqttClient.connectError());
Serial.println(broker);
Serial.println(port);
//Serial.println("aindout"+random(10000));
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
delay(10000);
wdt_enable(WDTO_2S);
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();
// subscribe to a topic
// the second paramter set's the QoS of the subscription,
// the the library supports subscribing at QoS 0, 1, or 2
int subscribeQos = 1;
// Serial.println(receiveTopic);
mqttClient.subscribe(receiveTopic.c_str(), subscribeQos);
mqttClient.subscribe(requestTopic, subscribeQos);
// topics can be unsubscribed using:
// mqttClient.unsubscribe(inTopic);
//Serial.print("Waiting for messages on topic: ");
//Serial.println(inTopic);
//Serial.println();
wdt_enable(WDTO_2S);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
const long interval = 10000;
unsigned long previousMillis = 0;
const bool retained = false;
const int qos = 1;
const bool dup = false;
int count = 0;
void loop() {
wdt_reset();
// call poll() regularly to allow the library to receive MQTT messages and
// 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;
//from/gruppo2/luci/arduino/AN0
const String source = String(outTopic)+String(dom_subdom_service)+String("/AN")+count;
uint32_t x = analogRead(sensor[count]);
const String payload = jsonBegin+"\"event\":"+x+jsonEnd;
// send message, the Print interface can be used to set the message contents
// in this case we know the size ahead of time, so the message payload can be streamed
mqttClient.beginMessage(source.c_str(), payload.length(),retained, qos, dup);
mqttClient.print(payload);
if(mqttClient.endMessage()==0){
Serial.println("I'm disconnected. Trying setup...");
setup();
}
}
void onMqttMessage(int messageSize) {
String msg;
String topic = mqttClient.messageTopic();
while (mqttClient.available()) {
msg += ((char)mqttClient.read());
}
Serial.println("Arrived: "+topic);
if(topic=="to/all") {
if(msg=="{\"request\":\"description.json\"}"||msg=="{request:description.json}") {
Serial.println("sending Description");
String descriptionTopic = String(outTopic)+String(dom_subdom_service)+String("/description");
mqttClient.beginMessage(descriptionTopic.c_str(), description.length(), retained, qos, dup);
mqttClient.print(description);
int rel = topic.substring(topic.indexOf("OUT")+3).toInt();
int val;
sscanf(msg.c_str(),"{\"cmd\":%d}",&val);
if(val <0 || val >1)//retry
if(rel<6 && rel>1)
digitalWrite(rel,val);
const String response = jsonBegin+"\"event\":"+val+jsonEnd;
topic = String(outTopic)+String(dom_subdom_service)+String("/OUT")+rel;
//Serial.println(topic);
mqttClient.beginMessage(topic.c_str(), response.length(), retained, qos, dup);
mqttClient.print(response);