Window Blinds - MQTT / Nodemcu problems

Hi everyone, i really need some help here.
I am running hass v0.54.0
1 x nodemcu v0.9 blue standard one.
1 x MG995 Servo that can run continuously - http://www.electronicoscaldas.com/datasheet/MG995_Tower-Pro.pdf

Here is my code for HASS:

# T-Room - troomblinds1 - NodeMCU device.
- platform: mqtt
  name: "T-Room blinds1"
  state_topic: "/troomblinds1/state"
  command_topic: "/troomblinds1/command"
  payload_on: "open"
  payload_off: "close"
  optimistic: true
  qos: 1
  retain: false

My nodemcu .ino code that i uploaded to the nodemcu via Arduino IDE:
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <PubSubClient.h>

/************************* WiFi Access Point (CHANGE THIS) **********************************/

#define WLAN_SSID "wifi_ssid"
#define WLAN_PASS "wifi_password"
#define mqtt_user "mqtt_username" 
#define mqtt_password "mqtt_password"
#define SENSORNAME "blinds1"

/************************* MQTT Setup (CHANGE THIS****************************************/

const char* mqtt_server  = "mqtt_server_ip";
const char* username = "username";
const char* password = "password";
const char* topic_state = "/troomblinds1/state";
const char* topic_command = "/troomblinds1/command";
WiFiClient espClient;
PubSubClient client (espClient);

/*********************** Sketch Code ****************************************************/
Servo myservo;
int state = 0;
int prevstate = 0;
int dirc = 0;
int spintime = 0;
int servoPin = D4; //CHANGE TO WHATEVETR PIN YOUR USING

void MQTT_connect();
void callback(char* topic, byte* payload, unsigned int length);


void setup() {
  Serial.begin(115200);
  myservo.detach();
  delay(10);
  Serial.println("Blind Startup Sequence");
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

}
void servo_move() {
  Serial.println("State Change. Rotating Servo");
  if ( dirc == 180) {
    client.publish(topic_state,"opened");
  }
  else if (dirc == 0) {
    client.publish(topic_state,"closed");
}
  myservo.attach(servoPin);
  myservo.write(dirc);
  delay(spintime);
  myservo.detach();

  Serial.println("Returning to main loop");
  return;
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: [");
  Serial.print(topic);
  Serial.print(" ]");
  char *blindcommand = (char *) payload; // convert mqtt byte array into char array
  blindcommand[length] ='\0';            // Must delimit with 0

  Serial.print(blindcommand);
  if (strcmp(blindcommand,"open") == 0) {
    Serial.println("OPEN COMMAND RECEIVED");
    dirc = 180; // direction for servo to run
    spintime = 20000; // << CHANGE TO WHATEVER TIME YOU NEED TO OPEN YOUR BLINDS
    state = 1; //sets current state
  }
  else if (strcmp(blindcommand,"close") == 0) {
    Serial.println("CLOSE COMMAND RECEIVED");
    dirc = 0;
    spintime = 18000; // << CHANGE TO WHATEVER TIME YOU NEED TO CLOSE YOUR BLINDS
    state = 2; //sets current state
  }
  if (state != prevstate) {
    Serial.println("State change!");
    servo_move();
  }
  prevstate = state;
}

void MQTT_connect() {
  while (!client.connected()) {  
Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(SENSORNAME, mqtt_user, mqtt_password)) {
      Serial.println("MQTT connected");
    client.subscribe(topic_command);
  } else {
    Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  delay(1000); // wait 5 seconds
  }
  }
}


void loop() {
  if (!client.connected()) {
    MQTT_connect();
  }
  client.loop();
}

Everything is working great, the ONLY problem i have is this:
When i close my blinds, and if the nodemcu loose power, and starts again, its going to close state again, so the blinds is running the same way as the last time i run it.

I have been changing the nodemcu and the hass code alot of time, but i cant get this to work properly.

Can anyone help me in the right direction for my project?

Greetings DK.

If this is because it receives a MQTT message when it restarts, then you have a retained message in the broker’s database. Clear it by sending a retained message with a null payload

mosquitto_pub -t /troomblinds1/command -r -n

So the problem is on the hass site, not the nodemcu code site?

If i restart the hass with the mqtt server on, should it work?

No. If it is a message retained by the broker, it is in the broker’s database. It won’t get cleared unless you either send it a message like I said, or delete and recreate the broker’s database.

But first you should establish if a message is actually being sent by looking at the output of your script to see if a message is actually being sent. There may be another reason for the behaviour.

How can i run this`?

I receive this when i try.

Connection Refused: not authorised.
Error: The connection was refused.

Sorry, I should have noticed that you are using a username and password for your broker, so you will need those as well.

try

mosquitto_pub -t /troomblinds1/command -r -n -u mqtt_user -P mqtt_password

You can get help for mosquitto_pub with

mosquitto_pub --help
1 Like

I think this code helped me, but now is the servo running really short at startup, like 0,5 sec forward and 0,5 backwards.

Do you know why?

This sounds like it is more to do with the electronics than the software. I assume that the 0.5s is different from either of the times set by the spintime variable?

When i mount the blinds its working fine, so no worries.

Do you know something about sonoff and the retain flag with mqtt also?

When my sonoff switch are on, when i restart my hass the state becomes to off insteaf of the last know state.

Can you help me with that?

The servo needs more power to open the blinds, than closing it.
Thats the reason the different spintime.

When i change the power from my pc hub to a normal wall adapter, the spin forward and backwards fast is gone.

So meaby some power issues on my pc.

This seems more likely to be something in HA sending the message than anything in the broker. Perhaps an automation that runs at startup, or maybe the switch defaulting to off (although I don’t remember seeing that myself).

How should I implement this fix, do I have to use ssh?

You can use many methods to send the MQTT message. Windows, Android and Ios all have MQTT clients that can send messages to the broker.

But if you don’t have one of those already installed its easiest to ssh on to your machine and use mosquitto_pub.

really weird… If try this code using ssh and hit enter:

mosquitto_pub -t /blind/bc/command -r -n -u myusername -P mypassword

or this one:

mosquitto_pub -t /blind/bc/command -r -n

and If I disconnect the nodemcu and plug it back in the servo keeps running to the same direction, mmmm I would appreciate any help.

Do either of these commands give any errors?

What happens when you do

mosquitto_sub -v -t /blind/bc/command 

(add your username and password if necessary)

I apologize for the delay but Im still having a hard time trying to figure this out… If I type mosquitto_sub -v -t /blind/bc/command

I get this in terminal:
/blind/bc/command STOP

But even when I use the other commands, I don’t get any response in terminal and the servo keeps running when I unplug it and plug it back in. I have HASS installed.

I appreciate any help.

You need to set the mqtt to be retained.

But how can I do that? The above commands won’t do anything

You are not really giving enough information to allow anyone to help. For instance, is the nodemcu receiving commands and not responding, or not receiving them at all?

I had this issue alot, but i need to send you the MQTT command.