hi this is the arduino:
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#define OFF D1
#define ON D2
const char* ssid = “WifiUsername”;
const char* password = “WifiPassword”;
char* espTopic = “ha/esp”;
char* controlTopic = “ha/somfy2”;
char* stateTopic = “ha/somfy2/state”;
char* server = “mqtt ip”;
char* mqttMessage;
WiFiClient wifiClient;
PubSubClient pubSubClient(wifiClient);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(OFF, OUTPUT);
pinMode(ON, OUTPUT);
digitalWrite(OFF, HIGH);
digitalWrite(ON, HIGH);
connectToWifi();
pubSubClient.setServer(server, 1883);
pubSubClient.setCallback(mqttCallback);
if (!pubSubClient.connected()) {
reconnect();
}
}
void reconnect() {
while (!pubSubClient.connected()) {
if (pubSubClient.connect(“client id”, “mqtt username”, “mqtt password”)) {
Serial.println(“Connected to MQTT broker”);
pubSubClient.publish(espTopic, “somfy control online”);
if (!pubSubClient.subscribe(controlTopic, 1)) {
Serial.println(“MQTT: unable to subscribe”);
}
} else {
Serial.print(“failed, rc=”);
Serial.print(pubSubClient.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!pubSubClient.connected()) {
reconnect();
}
pubSubClient.loop();
}
void connectToWifi() {
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println(“WiFi connected”);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
Serial.print(F(“MQTT Message Arrived [”));
Serial.print(topic);
Serial.print(F("] "));
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
mqttMessage = (char*) payload;
if (strcmp(topic, controlTopic) == 0) {
if (strncmp(mqttMessage, “OFF”, length) == 0) {
Serial.println(“Somfy Close”);
closeSomfy();
} else if (strncmp(mqttMessage, “ON”, length) == 0) {
Serial.println(“Somfy Open”);
openSomfy();
}
}
}
void openSomfy() {
pubSubClient.publish(stateTopic, “ON”);
digitalWrite(ON, LOW);
delay(250);
digitalWrite(ON, HIGH);
}
void closeSomfy() {
pubSubClient.publish(stateTopic, “OFF”);
digitalWrite(OFF, LOW);
delay(250);
digitalWrite(OFF, HIGH);
}
And this is the configuration.yaml entry:
Switch:
- platform: mqtt
name: “Curtains”
command_topic: “ha/somfy2”
state_topic: “ha/somfy2/state”
qos: 1
payload_on: “ON”
payload_off: “OFF”
retain: true