MQTT_modbus_write_multiple_registers 5.81 KB
#include <WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#include "identifiants.h"
#include "ModbusMaster.h"
ModbusMaster node;

//identifiants
const char* ssid = MY_SSID;
const char* password = MY_PASS;


//adresse du broker MQTT cloud et son port (8883 car protocole SSL)
const char* mqttServer = "f63f940361134f62957ef137f9d2e29f.s1.eu.hivemq.cloud";
const int mqttPort = 8883;

//identifiants du broker MQTT cloud pour s'authentifier
const char* mqttUser = MQTT_USER;
const char* mqttPassword = MQTT_PASSWORD;

unsigned long previousMillis = 0;
const long interval = 5000;
uint8_t  result;
int  messageMQTT;

uint8_t coil_value;

WiFiClientSecure wifiClient;
PubSubClient mqttClient(wifiClient);
String messageToPublish;

// Certificat CA du serveur MQTT obligatoire pour authentifier l'appareil qui se connecte
const char* caCert = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" \
"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" \
"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" \
"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" \
"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n" \
"MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n" \
"h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n" \
"0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n" \
"A5/TR5d8mUgjU+g4rk8Kb4Mu0UlX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vtd7u+Nxe5AW0wdeRlN8NwdC\n" \
"jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" \
"oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" \
"4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" \
"mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" \
"emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" \
"-----END CERTIFICATE-----\n";

void setup() {
  Serial.begin(115200); //port série activé

  WiFi.begin(ssid, password);               //connexion au WiFi
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
                                            //connexion au broker MQTT
  mqttClient.setServer(mqttServer, mqttPort);
  mqttClient.setCallback(callback);

  // Chargement du certificat CA du serveur MQTT
  wifiClient.setCACert(caCert);

  while (!mqttClient.connected()) {
    Serial.println("Connecting to MQTT server...");
    if (mqttClient.connect("ESP32Client", mqttUser, mqttPassword)) {
      Serial.println("Connected to MQTT server");
      mqttClient.subscribe("topic/hello");
    } else {
      Serial.print("Failed to connect to MQTT server, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" Retrying in 5 seconds...");
      delay(5000);
    }
  }

  Serial.print("\r\n*****************PRET!*******************");
  Serial2.begin(9600, SERIAL_8N1);  //communication modbus à 9600 bauds
  node.begin(1, Serial2); //ID node 1
}

void loop() {
  mqttClient.loop();

  if (!mqttClient.connected()) {
    reconnect();
  }

  if (Serial.available()){
    Serial.println();
    messageToPublish = Serial.readString();
    mqttClient.publish("topic/hello",messageToPublish.c_str());
  }
}

void reconnect() {
  while (!mqttClient.connected()) {
    Serial.println("Connecting to MQTT server...");
    if (mqttClient.connect("ESP32Client", mqttUser, mqttPassword)) {
      Serial.println("Connected to MQTT server");
    } else {
      Serial.print("Failed to connect to MQTT server, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" Retrying in 5 seconds...");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  // Fonction de rappel pour la réception des messages MQTT
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  char messageBuffer[length + 1];
  memcpy(messageBuffer, payload, length);
  messageBuffer[length] = '\0';  // Ajouter le caractère de fin de chaîne
  //messageMQTT = 0; //Clear messsage
  messageMQTT = atoi((char*)messageBuffer); //convertir le 
  
  Serial.print("message MQTT:");
  Serial.println(messageMQTT);

  if(messageMQTT < 32767){
  
    static uint16_t register_values[10] = {0b0000000100100011, 0b0001001010000011, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001,0x0001,0x0001};
 
    for (int i = 0; i < 10; i++) { //
      node.setTransmitBuffer(i, register_values[i]); 
    }    
    result = node.writeMultipleRegisters(0,40);
  
    if (result == node.ku8MBSuccess)
    {
      Serial.printf("\r\nSucces");
    }
    else
    {
        Serial.printf("\r\nFail");
    }
    
    
  }
  else
    Serial.println("number is too big");
}