[SOLVED] esp8266---mqtt----WS2801/WS2812/neopixel


// Neopixel
#include <Adafruit_NeoPixel.h>



// ESP 8266
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// MQTT Subscribes
const char* SubscribeTo = "esp/1/out";
const char* SubscribeFrom = "esp/1/in";

// WiFi & MQTT Server
const char* ssid = "YourWlan";
const char* password = "YourPassword";
const char* mqtt_server = "192.168.178.38";

WiFiClient espClient;
PubSubClient pubClient(espClient);
long lastMsg = 0;
char msg[50];
String message("#000000");
String lastMessage("#000000");

// Neopixel Config
#define NeoPIN D3
#define NUM_LEDS 30
int brightness = 150;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, NeoPIN, NEO_RGB + NEO_KHZ800);

void setup() {
  Serial.begin ( 115200 );
  
  // ##############
  // NeoPixel start
  Serial.println();
  strip.setBrightness(brightness);
  strip.begin();
  strip.show(); 
  delay(50);
  
  // WiFi
  setup_wifi();
  
  // MQTT
  Serial.print("Connecting to MQTT...");
  // connecting to the mqtt server
  pubClient.setServer(mqtt_server, 1883);
  pubClient.setCallback(callback);
  Serial.println("done!");
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String color("#");
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    if(i > 0){
      color = color + String((char)payload[i]);  
    }  
  }
  
  Serial.println();


  // finding payload
  if((char)payload[0] == '#'){
    // setting color
     setNeoColor(color);
  }
  
}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if (!pubClient.connected()) {
    delay(100);
    reconnect();
  }
  pubClient.loop();
  
  long now = millis();
  if (now - lastMsg > 60000 || lastMessage.indexOf(message) < 0 ) {
    
    lastMsg = now;
    Serial.print("Publish message: ");
    Serial.println(message);
    char msg[7];
    message.toCharArray(msg, message.length());
    Serial.print("Publishing...");
    pubClient.publish(SubscribeTo, msg);
    Serial.println("Done!!!");
    lastMessage = message;
  }
  delay(10);
}


void setNeoColor(String value){
    Serial.println("Setting Neopixel..." + value);
    message = value;
    int number = (int) strtol( &value[1], NULL, 16);
    
    int r = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;

    

     Serial.print("RGB: ");
    Serial.print(r, DEC);
    Serial.print(" ");
    Serial.print(g, DEC);
    Serial.print(" ");
    Serial.print(b, DEC);
    Serial.println(" ");
  
   for(int i=0; i < NUM_LEDS; i++) {
      strip.setPixelColor(i, strip.Color( g, r, b ) );
    }
    strip.show();
    
    Serial.println("on.");
}


void reconnect() {
  // Loop until we're reconnected
  while (!pubClient.connected()) {
    // Attempt to connect
    if (pubClient.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      pubClient.publish(SubscribeTo, "Restart");
      // ... and resubscribe
      pubClient.subscribe(SubscribeFrom);
    } else {
      Serial.print("failed, rc=");
      Serial.print(pubClient.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
items

Group All
Color RGBLed "NeoPixel Color" (All)
String RGBLedColor (All) {mqtt=">[mosquitto:esp/1/out:command:*:default]"}
sitemap NeoPixel label="NeoPixel"
{
	Frame label="NeoPixel" {
		Colorpicker item=RGBLed icon="slider"
	}
}
rules file

import org.openhab.core.library.types.*

rule "Set HSB value of item RGBLed to RGB color value"
when
	Item RGBLed changed
then
	val hsbValue = RGBLed.state as HSBType

	val brightness = hsbValue.brightness.intValue 
	val redValue = ((((hsbValue.red.intValue * 255) / 100) *brightness) /100).toString
	val greenValue = ((((hsbValue.green.intValue * 255) / 100) *brightness) /100).toString
	val blueValue = ((((hsbValue.blue.intValue * 255) / 100) *brightness) /100).toString

	val color = redValue + "," + greenValue + "," + blueValue

	sendCommand( RGBLedColor, color)
end

the code works fine with phone app mqtt dashboard—but i cant put it to openhab
i think i m not good with subcribtions–please help----with item configuration and rule

{mqtt=">[mosquitto:esp/1/out:command:*:default]"}

Please post the corresponding lines in event.log and openhab.log.

2018-04-17 10:01:53.735 [ome.event.ItemCommandEvent] - Item ‘RGBLed’ received command OFF

2018-04-17 10:01:53.752 [vent.ItemStateChangedEvent] - RGBLed changed from 67,47,100 to 67,47,0

2018-04-17 10:01:55.453 [ome.event.ItemCommandEvent] - Item ‘RGBLed’ received command 320,38,100

2018-04-17 10:01:55.468 [vent.ItemStateChangedEvent] - RGBLed changed from 67,47,0 to 320,38,100

2018-04-17 10:01:55.893 [ome.event.ItemCommandEvent] - Item ‘RGBLed’ received command 216,65,100

2018-04-17 10:01:55.908 [vent.ItemStateChangedEvent] - RGBLed changed from 320,38,100 to 216,65,100

2018-04-17 10:01:56.196 [ome.event.ItemCommandEvent] - Item ‘RGBLed’ received command 227,86,100

2018-04-17 10:01:56.208 [vent.ItemStateChangedEvent] - RGBLed changed from 216,65,100 to 227,86,100

thanks------do u have a esp8266 code


i want to build every think from scretch
but there is no good examples

Your esp code is good, so there are good examples


I didn’t read the end of the esp code, It should be good to go
I think you have problems with your OH code instead.

What do you see on your phone mqtt dashboard when you trigger the OH rule?
Does OH send anything at all?
What do the OH logs show?

You don’t need the import statement at the top of your rule file

Try adding logInfo statement to see what happens if the rule:

rule "Set HSB value of item RGBLed to RGB color value"
when
	Item RGBLed changed
then
	val hsbValue = RGBLed.state as HSBType

	val brightness = hsbValue.brightness.intValue
        logInfo("BRIGHTNESS", brightness.toString)
	val redValue = ((((hsbValue.red.intValue * 255) / 100) *brightness) /100).toString
        logInfo("REDVALUE", redValue.toString)
	val greenValue = ((((hsbValue.green.intValue * 255) / 100) *brightness) /100).toString
        logInfo("GREENVALUE", greenValue.toString)
	val blueValue = ((((hsbValue.blue.intValue * 255) / 100) *brightness) /100).toString
        logInfo("BLUEVALUE", blueValue.toString)

	val color = redValue + "," + greenValue + "," + blueValue
        logInfo("COLOR", color)

	RGBLedColor.sendCommand(color)
end

on my phone i see this picture
on openhab nothing hapens
the color changes very good on mqtt dashboard app
i think i not send the right topic on the item file

Group All
Color RGBLed “NeoPixel Color” (All)
String RGBLedColor (All) {mqtt=">[mosquitto:esp/1/out:command:*:default]"}

`

2018-04-17 20:58:38.250 [INFO ] [rest.core.internal.item.ItemResource] - Received HTTP POST request at ‘items/RGBLed’ for the unknown item ‘RGBLed’.

It looks like you items are not defined
Please do a small modification on your items file and look at the openhab log, what happens?

Group All

Color RGBLed “NeoPixel Color” (All){mqtt=">[mosquitto:esp/1/out:command:*:default]"}

String RGBLedColor (All) {mqtt=">[mosquitto:esp/1/out:command:*:default]"}


2018-04-18 09:50:26.473 [ome.event.ItemCommandEvent] - Item ‘RGBLedColor’ received command 51,255,117

2018-04-18 09:50:26.480 [vent.ItemStateChangedEvent] - RGBLedColor changed from 15,58,255 to 51,255,117

still not working
i cant send a command to broker i think
i change from esp/1/out to esp/1/in and it same
god help me

When that happens:

2018-04-18 09:50:26.473 [ome.event.ItemCommandEvent] - Item ‘RGBLedColor’ received command 51,255,117

What do you see on the MQTT dashboard?

Can you post your mqtt.cfg file, please?

when i change the color on my telephone mqtt dashboard then is see on mqtt fx for example this #F700BA
but on openhab logviever i see nothing

#
# Define your MQTT broker connections here for use in the MQTT Binding or MQTT
# Persistence bundles. Replace <broker> with an ID you choose.
#

# URL to the MQTT broker, e.g. tcp://localhost:1883 or ssl://localhost:8883
mqtt:broker.url=tcp://192.168.2.122:1883

# Optional. Client id (max 23 chars) to use when connecting to the broker.
# If not provided a random default is generated.
#<broker>.clientId=<clientId>

# Optional. True or false. If set to true, allows the use of clientId values
# up to 65535 characters long. Defaults to false.
# NOTE: clientId values longer than 23 characters may not be supported by all
# MQTT servers. Check the server documentation.
#<broker>.allowLongerClientIds=false

# Optional. User id to authenticate with the broker.
#<broker>.user=<user>

# Optional. Password to authenticate with the broker.
#<broker>.pwd=<password>

# Optional. Set the quality of service level for sending messages to this broker.
# Possible values are 0 (Deliver at most once),1 (Deliver at least once) or 2
# (Deliver exactly once). Defaults to 0.
#<broker>.qos=<qos>

# Optional. True or false. Defines if the broker should retain the messages sent to
# it. Defaults to false.
#<broker>.retain=<retain>

# Optional. True or false. Defines if messages are published asynchronously or
# synchronously. Defaults to true.
#<broker>.async=<async>

# Optional. Defines the last will and testament that is sent when this client goes offline
# Format: topic:message:qos:retained <br/>
#<broker>.lwt=<last will definition>

This is wrong:
mqtt:broker.url=tcp://192.168.2.122:1883

Replace with:
mosquitto.url=tcp://192.168.2.122:1883

And then restart openHAB to make sure the binding is updated

The items are:

Color RGBLed “NeoPixel Color” (All){mqtt=">[mosquitto:esp/1/out:command:*:default]"}
String RGBLedColor (All) {mqtt=">[mosquitto:esp/1/out:command:*:default]"}

So the broker name is mosquitto
Your bindings are set to send data not receive.
If you want to receive data on RGBLed you need to change it to:

Color RGBLed “NeoPixel Color” (All){mqtt="<[mosquitto:esp/1/out:state:default]"}
Group All


Color RGBLed NeoPixel Color(All){mqtt="<[mosquitto:esp/1/out:state:default]"}


String RGBLedColor  (All) {mqtt=">[mosquitto:esp/1/out:command:*:default]"}


2018-04-18 11:47:56.268 [INFO ] [rest.core.internal.item.ItemResource] - Received HTTP POST request at 'items/RGBLed' for the unknown item 'RGBLed'.

This item definiton is incorrect too. I didn’t spot it before.

Color RGBLed (All) {mqtt="<[mosquitto:esp/1/out:state:default]"}
2018-04-18 12:34:34.076 [ome.event.ItemCommandEvent] - Item 'RGBLedColor' received command 107,91,255

2018-04-18 12:34:34.082 [ERROR] [.mqtt.internal.MqttMessageSubscriber] - Error processing MQTT message.

java.lang.IllegalArgumentException: Value must be between 0 and 100


java.lang.IllegalArgumentException: Value must be between 0 and 100

	at org.openhab.core.library.types.PercentType.validateValue(PercentType.java:48) [208:org.openhab.core.compat1x:2.2.0]

	at org.openhab.core.library.types.PercentType.<init>(PercentType.java:43) [208:org.openhab.core.compat1x:2.2.0]

	at org.openhab.core.library.types.HSBType.getBrightness(HSBType.java:105) [208:org.openhab.core.compat1x:2.2.0]

	at org.openhab.core.library.types.HSBType.toString(HSBType.java:132) [208:org.openhab.core.compat1x:2.2.0]

	at org.openhab.core.compat1x.internal.TypeMapper.mapToESHType(TypeMapper.java:125) [208:org.openhab.core.compat1x:2.2.0]

	at org.openhab.core.events.EventPublisherDelegate.postUpdate(EventPublisherDelegate.java:63) [208:org.openhab.core.compat1x:2.2.0]

	at org.openhab.binding.mqtt.internal.MqttMessageSubscriber.processMessage(MqttMessageSubscriber.java:150) [212:org.openhab.binding.mqtt:1.11.0]

	at org.openhab.io.transport.mqtt.internal.MqttBrokerConnection.messageArrived(MqttBrokerConnection.java:556) [213:org.openhab.io.transport.mqtt:1.11.0]

	at org.eclipse.paho.client.mqttv3.internal.CommsCallback.deliverMessage(CommsCallback.java:475) [213:org.openhab.io.transport.mqtt:1.11.0]

	at org.eclipse.paho.client.mqttv3.internal.CommsCallback.handleMessage(CommsCallback.java:379) [213:org.openhab.io.transport.mqtt:1.11.0]

	at org.eclipse.paho.client.mqttv3.internal.CommsCallback.run(CommsCallback.java:183) [213:org.openhab.io.transport.mqtt:1.11.0]

	at java.lang.Thread.run(Thread.java:748) [?:?]```

but i have now a good news
i have logs now from openhab when i change the color with phone mqtt dashboard


2018-04-18 12:42:55.566 [WARN ] [b.core.events.EventPublisherDelegate] - given new state is NULL, couldn’t post update for ‘RGBLed’

Yes this is because the format sent by your dashboard cannot be parsed into a color
Step by step, we will get there.

First change RGBLed to a String for testing:

String RGBLed (All) {mqtt="<[mosquitto:esp/1/out:state:default]"}

What do you get in your log?