Skip to content
Snippets Groups Projects
AinDout_Arduino1wifi.ino 8.34 KiB
Newer Older
Alfredo Chissotti's avatar
Alfredo Chissotti committed
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";
Alfredo Chissotti's avatar
Alfredo Chissotti committed
/*
  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>

Alfredo Chissotti's avatar
Alfredo Chissotti committed
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
Alfredo Chissotti's avatar
Alfredo Chissotti committed
//pissir/pissir2000
Alfredo Chissotti's avatar
Alfredo Chissotti committed
// 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";
Alfredo Chissotti's avatar
Alfredo Chissotti committed

Alfredo Chissotti's avatar
Alfredo Chissotti committed
WiFiClient wifiClient;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
MqttClient mqttClient(wifiClient);
//PubSubClient mqttClient(wifiClient);
Alfredo Chissotti's avatar
Alfredo Chissotti committed

//const char broker[]    = "193.206.52.98";//smartcity-challenge
Alfredo Chissotti's avatar
Alfredo Chissotti committed
//const char broker[]    = "192.168.20.67";
// broker non funzionanti: localhost, tcp://localhost, luci.local
Alfredo Chissotti's avatar
Alfredo Chissotti committed
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+"/#";
Alfredo Chissotti's avatar
Alfredo Chissotti committed

const String jsonBegin = "{";
Alfredo Chissotti's avatar
Alfredo Chissotti committed
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+"\"}";
Alfredo Chissotti's avatar
Alfredo Chissotti committed

Alfredo Chissotti's avatar
Alfredo Chissotti committed
// 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
*/
Alfredo Chissotti's avatar
Alfredo Chissotti committed

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
Alfredo Chissotti's avatar
Alfredo Chissotti committed

  // 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);
Alfredo Chissotti's avatar
Alfredo Chissotti committed

  // You can provide a username and password for authentication
  mqttClient.setUsernamePassword(mqttUser, mqttPassword);

Alfredo Chissotti's avatar
Alfredo Chissotti committed

  // 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);
Alfredo Chissotti's avatar
Alfredo Chissotti committed


  //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)){
Alfredo Chissotti's avatar
Alfredo Chissotti committed
      Serial.print("MQTT connection failed! Error code = ");
      Serial.println(mqttClient.connectError());
      Serial.println(broker);
      Serial.println(port);
      //Serial.println("aindout"+random(10000));
Alfredo Chissotti's avatar
Alfredo Chissotti committed
      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);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
}

Alfredo Chissotti's avatar
Alfredo Chissotti committed

const long interval = 10000;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
unsigned long previousMillis = 0;
const bool retained = false;
const int qos = 1;
const bool dup = false;
int count = 0;

Alfredo Chissotti's avatar
Alfredo Chissotti committed
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 
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    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;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
//= "{\"event\":\""+x+"\", \"sensorNo\":\""+count+"\"}";
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    Serial.println(source);
    Serial.println(payload);
Alfredo Chissotti's avatar
Alfredo Chissotti committed

    // 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

Alfredo Chissotti's avatar
Alfredo Chissotti committed
    mqttClient.beginMessage(source.c_str(), payload.length(),retained, qos, dup);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    mqttClient.print(payload);
    if(mqttClient.endMessage()==0){
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        Serial.println("I'm disconnected. Trying setup...");
        setup();
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    };
    count++;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    count = count % number_of_sensors;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
  }
}

void onMqttMessage(int messageSize) {
  String msg;
  String topic = mqttClient.messageTopic();
  while (mqttClient.available()) {
    msg += ((char)mqttClient.read());
  }
  Serial.println("Arrived: "+topic);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
  Serial.println(msg);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
  if(topic=="to/all") {

    if(msg=="{\"request\":\"description.json\"}"||msg=="{request:description.json}") {
Alfredo Chissotti's avatar
Alfredo Chissotti committed
      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);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    }
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    int rel = topic.substring(topic.indexOf("OUT")+3).toInt();
    int val;
    
    sscanf(msg.c_str(),"{\"cmd\":%d}",&val);
    if(val <0 || val >1)//retry
Alfredo Chissotti's avatar
Alfredo Chissotti committed
      sscanf(msg.c_str(),"{cmd:%d}",&val);
    if(rel<6 && rel>1)
      digitalWrite(rel,val);
    const String response = jsonBegin+"\"event\":"+val+jsonEnd;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    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);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
  mqttClient.endMessage();
Alfredo Chissotti's avatar
Alfredo Chissotti committed
}