HA + Arduino + M510...
 
Powiadomienia
Wyczyść wszystko

Home Assistant HA + Arduino + M5100 + MySensors

Dawid Kądziela
(@dawidkadziela)
Początkujący

Cześć,

W ostatnim wątku zdecydowałem iż zostanę przy sterowaniu oświetleniem opertym na Arduino w swojej instalacji inteligentnego domu. Zdecydowałem też że chcę to wszystko oprzeć na Home Assistant.

Chcąc podłączyć Arduino do HA naszukałem się i naczytałem sporo informacji w necie, lecz powiązanie nie nastąpiło. Przygotowałem skecz ale nie łączy się nawet z moją siecią LAN (nie ma go w liście urządzeń LAN).

Proszę o weryfikację:

Spoiler
Skecz

/*
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
* Copyright (C) 2013-2019 Sensnology AB
* Full contributor list: https://github.com/mysensors/MySensors/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
*******************************
*
* REVISION HISTORY
* Version 1.0 - Henrik Ekblad
*
* DESCRIPTION
* The W5100 MQTT gateway sends radio network (or locally attached sensors) data to your MQTT broker.
* The node also listens to MY_MQTT_TOPIC_PREFIX and sends out those messages to the radio network
*
* LED purposes:
* - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h
* - RX (green) - blink fast on radio message received. In inclusion mode will blink fast only on presentation received
* - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly
* - ERR (red) - fast blink on error during transmission error or receive crc error
*
* See http://www.mysensors.org/build/esp8266_gateway for wiring instructions.
* nRF24L01+ ESP8266
* VCC VCC
* CE GPIO4
* CSN/CS GPIO15
* SCK GPIO14
* MISO GPIO12
* MOSI GPIO13
*
* Not all ESP8266 modules have all pins available on their external interface.
* This code has been tested on an ESP-12 module.
* The ESP8266 requires a certain pin configuration to download code, and another one to run code:
* - Connect REST (reset) via 10K pullup resistor to VCC, and via switch to GND ('reset switch')
* - Connect GPIO15 via 10K pulldown resistor to GND
* - Connect CH_PD via 10K resistor to VCC
* - Connect GPIO2 via 10K resistor to VCC
* - Connect GPIO0 via 10K resistor to VCC, and via switch to GND ('bootload switch')
*
* Inclusion mode button:
* - Connect GPIO5 via switch to GND ('inclusion switch')
*
* Hardware SHA204 signing is currently not supported!
*
* Make sure to fill in your ssid and WiFi password below for ssid & pass.
*/

// Enable debug prints to serial monitor
#define MY_DEBUG

// Enables and select radio type (if attached)
#define MY_RADIO_RF24
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95

#define MY_GATEWAY_MQTT_CLIENT

// Set this node's subscribe and publish topic prefix
#define MY_MQTT_PUBLISH_TOPIC_PREFIX "sterownik_1_in"
#define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX "sterownik_1_out"

// Set MQTT client id
#define MY_MQTT_CLIENT_ID "Sterownik_1"

// W5100 Ethernet module SPI enable (optional if using a shield/module that manages SPI_EN signal)
#define MY_W5100_SPI_EN 4

// Enable Soft SPI for NRF radio (note different radio wiring is required)
// The W5100 ethernet module seems to have a hard time co-operate with
// radio on the same spi bus.
#if !defined(MY_W5100_SPI_EN) && !defined(ARDUINO_ARCH_SAMD)
#define MY_SOFTSPI
#define MY_SOFT_SPI_SCK_PIN 14
#define MY_SOFT_SPI_MISO_PIN 16
#define MY_SOFT_SPI_MOSI_PIN 15
#endif

// When W5100 is connected we have to move CE/CSN pins for NRF radio
#ifndef MY_RF24_CE_PIN
#define MY_RF24_CE_PIN 5
#endif
#ifndef MY_RF24_CS_PIN
#define MY_RF24_CS_PIN 6
#endif

// Enable these if your MQTT broker requires username/password
//#define MY_MQTT_USER "username"
//#define MY_MQTT_PASSWORD "password"

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };

// Enable MY_IP_ADDRESS here if you want a static ip address (no DHCP)
#define MY_IP_ADDRESS 192,168,0,201

// If using static ip you can define Gateway and Subnet address as well
#define MY_IP_GATEWAY_ADDRESS 192,168,0,1
#define MY_IP_SUBNET_ADDRESS 255,255,255,0

// MQTT broker ip address or url. Define one or the other.
//#define MY_CONTROLLER_URL_ADDRESS "m20.cloudmqtt.com"
#define MY_CONTROLLER_IP_ADDRESS 192,168,0,140

// The MQTT broker port to to open
#define MY_PORT 8123

/*
// Enable inclusion mode
#define MY_INCLUSION_MODE_FEATURE
// Enable Inclusion mode button on gateway
//#define MY_INCLUSION_BUTTON_FEATURE
// Set inclusion mode duration (in seconds)
#define MY_INCLUSION_MODE_DURATION 60
// Digital pin used for inclusion mode button
//#define MY_INCLUSION_MODE_BUTTON_PIN 3

// Set blinking period
#define MY_DEFAULT_LED_BLINK_PERIOD 300

// Flash leds on rx/tx/err
// Uncomment to override default HW configurations
//#define MY_DEFAULT_ERR_LED_PIN 16 // Error led pin
//#define MY_DEFAULT_RX_LED_PIN 16 // Receive led pin
//#define MY_DEFAULT_TX_LED_PIN 16 // the PCB, on board LED
*/

#include
#include
#include

// Enable repeater functionality for this node
#define MY_REPEATER_FEATURE

#define RELAY_LA_01 4 // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
#define RELAY_LA_02 5
#define RELAY_LA_03 6
#define RELAY_LA_04 7
#define RELAY_LA_05 8
#define RELAY_LA_06 9
#define RELAY_LA_07 10
#define RELAY_LA_08 11
#define RELAY_LA_09 12
#define RELAY_LA_10 13

#define NUMBER_OF_RELAYS 10 // Total number of attached relays
#define RELAY_ON 0 // GPIO value to write to turn on attached relay
#define RELAY_OFF 1 // GPIO value to write to turn off attached relay

#define LA_01 A1
#define LA_02 A2
#define LA_03 A3
#define LA_04 A4
#define LA_05 A5
#define LA_06 A6
#define LA_07 A7
#define LA_08 A8
#define LA_09 A9
#define LA_10 A10

void before() {
for (int sensor=1, pin=RELAY_LA_01; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) {
// Then set relay pins in output mode
pinMode(pin, OUTPUT);
// Set relay to last known state (using eeprom storage)
digitalWrite(pin, loadState(sensor)?RELAY_ON:RELAY_OFF);
}
}
Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();
Bounce debouncer3 = Bounce();
Bounce debouncer4 = Bounce();
Bounce debouncer5 = Bounce();
Bounce debouncer6 = Bounce();
Bounce debouncer7 = Bounce();
Bounce debouncer8 = Bounce();
Bounce debouncer9 = Bounce();
Bounce debouncer10 = Bounce();

void setup() {
// Setup locally attached sensors
delay(10000);
// Setup the button.
pinMode(LA_01, INPUT_PULLUP);
pinMode(LA_02, INPUT_PULLUP);
pinMode(LA_03, INPUT_PULLUP);
pinMode(LA_04, INPUT_PULLUP);
pinMode(LA_05, INPUT_PULLUP);
pinMode(LA_06, INPUT_PULLUP);
pinMode(LA_07, INPUT_PULLUP);
pinMode(LA_08, INPUT_PULLUP);
pinMode(LA_09, INPUT_PULLUP);
pinMode(LA_10, INPUT_PULLUP);
// After setting up the button, setup debouncer.
debouncer.attach(LA_01);
debouncer.interval(5);
debouncer2.attach(LA_02);
debouncer2.interval(5);
debouncer3.attach(LA_03);
debouncer3.interval(5);
debouncer4.attach(LA_04);
debouncer4.interval(5);
debouncer5.attach(LA_05);
debouncer5.interval(5);
debouncer6.attach(LA_06);
debouncer6.interval(5);
debouncer7.attach(LA_07);
debouncer7.interval(5);
debouncer8.attach(LA_08);
debouncer8.interval(5);
debouncer9.attach(LA_09);
debouncer9.interval(5);
debouncer10.attach(LA_10);
debouncer10.interval(5);

//presentation();
}
void presentation()
{
// Send the sketch version information to the gateway and Controller
sendSketchInfo("Relay", "1.0");

for (int sensor=1, pin=RELAY_LA_01; sensor<=NUMBER_OF_RELAYS;sensor++, pin++) {
// Register all sensors to gw (they will be created as child devices)
present(sensor, S_LIGHT);
}
}

MyMessage msg(1, V_LIGHT);
MyMessage msg2(2, V_LIGHT);
MyMessage msg3(3, V_LIGHT);
MyMessage msg4(4, V_LIGHT);
MyMessage msg5(5, V_LIGHT);
MyMessage msg6(6, V_LIGHT);
MyMessage msg7(7, V_LIGHT);
MyMessage msg8(8, V_LIGHT);
MyMessage msg9(9, V_LIGHT);
MyMessage msg10(10, V_LIGHT);

void loop() {
// Send locally attached sensor data here
if (debouncer.update()) {
// Get the update value.
int value = debouncer.read();
// Send in the new value.
if(value == LOW){
saveState(1, !loadState(1));
digitalWrite(RELAY_LA_01, loadState(1)?RELAY_ON:RELAY_OFF);
send(msg.set(loadState(1)));
}
}
if (debouncer2.update()) {
int value2 = debouncer2.read();
if(value2 == LOW){
saveState(2, !loadState(2));
digitalWrite(RELAY_LA_02, loadState(2)?RELAY_ON:RELAY_OFF);
send(msg2.set(loadState(2)));
}
}
if (debouncer3.update()) {
// Get the update value.
int value3 = debouncer3.read();
// Send in the new value.
if(value3 == LOW){
saveState(3, !loadState(3));
digitalWrite(RELAY_LA_03, loadState(3)?RELAY_ON:RELAY_OFF);
send(msg3.set(loadState(3)));
}
}
if (debouncer4.update()) {
// Get the update value.
int value4 = debouncer4.read();
// Send in the new value.
if(value4 == LOW){
saveState(4, !loadState(4));
digitalWrite(RELAY_LA_04, loadState(4)?RELAY_ON:RELAY_OFF);
send(msg4.set(loadState(4)));
}
}
if (debouncer5.update()) {
// Get the update value.
int value5 = debouncer5.read();
// Send in the new value.
if(value5 == LOW){
saveState(5, !loadState(5));
digitalWrite(RELAY_LA_05, loadState(5)?RELAY_ON:RELAY_OFF);
send(msg5.set(loadState(5)));
}
}
if (debouncer6.update()) {
// Get the update value.
int value6 = debouncer6.read();
// Send in the new value.
if(value6 == LOW){
saveState(6, !loadState(6));
digitalWrite(RELAY_LA_06, loadState(6)?RELAY_ON:RELAY_OFF);
send(msg6.set(loadState(6)));
}
}
if (debouncer7.update()) {
// Get the update value.
int value7 = debouncer7.read();
// Send in the new value.
if(value7 == LOW){
saveState(7, !loadState(7));
digitalWrite(RELAY_LA_07, loadState(7)?RELAY_ON:RELAY_OFF);
send(msg7.set(loadState(7)));
}
}
if (debouncer8.update()) {
// Get the update value.
int value8 = debouncer8.read();
// Send in the new value.
if(value8 == LOW){
saveState(8, !loadState(8));
digitalWrite(RELAY_LA_08, loadState(8)?RELAY_ON:RELAY_OFF);
send(msg8.set(loadState(8)));
}
}
if (debouncer9.update()) {
// Get the update value.
int value9 = debouncer9.read();
// Send in the new value.
if(value9 == LOW){
saveState(9, !loadState(9));
digitalWrite(RELAY_LA_09, loadState(9)?RELAY_ON:RELAY_OFF);
send(msg9.set(loadState(9)));
}
}
if (debouncer10.update()) {
// Get the update value.
int value10 = debouncer10.read();
// Send in the new value.
if(value10 == LOW){
saveState(10, !loadState(10));
digitalWrite(RELAY_LA_10, loadState(10)?RELAY_ON:RELAY_OFF);
send(msg10.set(loadState(10)));
}
}
}

void receive(const MyMessage &message) {
// We only expect one type of message from controller. But we better check anyway.
if (message.type==V_LIGHT) {
// Change relay state
digitalWrite(message.sensor-1+RELAY_LA_01, message.getBool()?RELAY_ON:RELAY_OFF);
// Store state in eeprom
saveState(message.sensor, message.getBool());
// Write some debug info
Serial.print("Incoming change for sensor:");
Serial.print(message.sensor);
Serial.print(", New status: ");
Serial.println(message.getBool());
}
}

 
Cytuj
Autor tematu Dodane : 22/09/2021 7:57 pm
isom
 isom
(@isom)
Prezes Moderator Zasłużony dla Forum, Donator 2K19, Donator 2K20

@dawidkadziela najlepiej zacznij od wgrania kodu podstawowej bramki mqtt i jak zobaczysz że łączy się z siecią i brokerem którego port masz niby 8123 a to zapewne port HA a nie brokera , więc pewnie trzeba ustawić ten port na 1883 . Zresztą może tak , wgraj do arduino to co poniżej i uruchom podgląd monitor szeregowy

// Enable debug prints to serial monitor
#define MY_DEBUG

// Enables and select radio type (if attached)
//#define MY_RADIO_RF24
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95

#define MY_GATEWAY_MQTT_CLIENT

// Set this node's subscribe and publish topic prefix
#define MY_MQTT_PUBLISH_TOPIC_PREFIX "mygateway1-out"
#define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX "mygateway1-in"

// Set MQTT client id
#define MY_MQTT_CLIENT_ID "mysensors-1"

// W5100 Ethernet module SPI enable (optional if using a shield/module that manages SPI_EN signal)
//#define MY_W5100_SPI_EN 4

// Enable Soft SPI for NRF radio (note different radio wiring is required)
// The W5100 ethernet module seems to have a hard time co-operate with
// radio on the same spi bus.
//#if !defined(MY_W5100_SPI_EN) && !defined(ARDUINO_ARCH_SAMD)
//#define MY_SOFTSPI
//#define MY_SOFT_SPI_SCK_PIN 14
//#define MY_SOFT_SPI_MISO_PIN 16
//#define MY_SOFT_SPI_MOSI_PIN 15
//#endif

// When W5100 is connected we have to move CE/CSN pins for NRF radio
//#ifndef MY_RF24_CE_PIN
//#define MY_RF24_CE_PIN 5
//#endif
//#ifndef MY_RF24_CS_PIN
//#define MY_RF24_CS_PIN 6
//#endif

// Enable these if your MQTT broker requires username/password
#define MY_MQTT_USER "admin"
#define MY_MQTT_PASSWORD "password"

// Enable MY_IP_ADDRESS here if you want a static ip address (no DHCP)
#define MY_IP_ADDRESS 192,168,0,201

// If using static ip you can define Gateway and Subnet address as well
//#define MY_IP_GATEWAY_ADDRESS 192,168,1,1
//#define MY_IP_SUBNET_ADDRESS 255,255,255,0

// MQTT broker ip address or url. Define one or the other.
//#define MY_CONTROLLER_URL_ADDRESS "m20.cloudmqtt.com"
#define MY_CONTROLLER_IP_ADDRESS 192, 168, 0, 140

// The MQTT broker port to to open
#define MY_PORT 1883

/*
// Enable inclusion mode
#define MY_INCLUSION_MODE_FEATURE
// Enable Inclusion mode button on gateway
//#define MY_INCLUSION_BUTTON_FEATURE
// Set inclusion mode duration (in seconds)
#define MY_INCLUSION_MODE_DURATION 60
// Digital pin used for inclusion mode button
//#define MY_INCLUSION_MODE_BUTTON_PIN  3

// Set blinking period
#define MY_DEFAULT_LED_BLINK_PERIOD 300

// Flash leds on rx/tx/err
// Uncomment to override default HW configurations
//#define MY_DEFAULT_ERR_LED_PIN 16  // Error led pin
//#define MY_DEFAULT_RX_LED_PIN  16  // Receive led pin
//#define MY_DEFAULT_TX_LED_PIN  16  // the PCB, on board LED
*/

#include 
#include 

void setup()
{
	// Setup locally attached sensors
}

void presentation()
{
	// Present locally attached sensors here
}

void loop()
{
	// Send locally attached sensors data here
}

Powinieneś zobaczyć taki ekran , tylko IP będzie takie jak Twoje

2

Jak tak będzie to możesz walczyć dalej deklarując przekaźniki i przyciski 

PS

Zapomniałem dodać że w kodzie musisz zmienić usera i hasło do brokera bo nie podałeś jakie masz więc nie mogłem wpisać :))

 

OdpowiedzCytuj
Dodane : 22/09/2021 9:26 pm
Dawid Kądziela
(@dawidkadziela)
Początkujący

@isom 

Na twoim skeczu nic nie pokazuje się w okienku. Z kolei na standardowym szkicu GatewayW5100MQTTClient:

obraz

Ni cholery nie chce się połączyć z LAN.

Udało mi się tylko raz połączyć ale na poniższym:

Spoiler
a
/*
Example MQTT-switch-relay-node with 4 buttons and 4 relays

- connects to an MQTT server
- subscribes to the topic "relay"
- controls 4 relays
- reads 4 button
- turns on/off a specific relay when it receives a specific "on"/"off" from the "relay" topic
- sends a specific "on"/"off" to the "relay" topic a specific button is pressed
- multiple arduino's with same generic sketch can run parallel to each other
- multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID
- control DHT11 sensor temperature and humidity sensor
- control PIR sensor HC-SR501HC - NEED TO CHECK!
- led for PIR sensor (showing activity)
- tested on arduino-mega with W5100 ethernet shield - NEED more testing!
- Ethernet Shield W5100
*/

//------------------------------------------------------------------------------

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <Bounce2.h>
#include "DHT.h"

// --- temp/hum sensor --//
#define DHTPIN 11 // what pin we're connected to
#define humidity_topic "home/humidity1"
#define temperature_topic "home/temperature1"
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// --- temp/hum sensor --//

// --- PIR sensor --//
int pirPin = 12; //the digital pin connected to the PIR sensor's output
int ledpirPin = 13;
int lastPirValue = LOW;
// --- PIR sensor --//

// Set relay variables to Arduino digital pins
int relay1 = 2;
int relay2 = 3;
int relay3 = 5; // pin 4 used by ethernet shield
int relay4 = 6;

// Set button variables to Arduino digital pins
int button1 = 7;
int button2 = 8;
int button3 = 9;
int button4 = 31; // pins 10,51,52 used by ethernetshield

// Set variables to act as virtual switches
// Set variable values initially to LOW (and not HIGH)
int relay1Value = LOW;
int relay2Value = LOW;
int relay3Value = LOW;
int relay4Value = LOW;

//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192,168,0,201);

// IP Address of your MQTT broker - change to adapt to your network
IPAddress server(192, 168, 1, 140);
char message_buff[100]; // this buffers our incoming messages so we can do something on certain commands

EthernetClient ethClient;
PubSubClient client(ethClient);
long lastReconnectAttempt = 0;

boolean reconnect() {
//Serial.print("Attempting MQTT connection...");
if (client.connect("ethClient", "mqtt", "xxx")) {
// Once connected, publish an announcement...
client.publish("home","connected");
Serial.println("connected");
// ... and resubscribe
client.subscribe("home/#");
}
else {
Serial.print("fairelay, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
return client.connected();

}
// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
String content="";
char character;
for (int num=0;num<length;num++) {
character = payload[num];
content.concat(character);
}
Serial.println(topic);
Serial.println(content); // message sent out by button actions is returned from broker and serial printed

// Set specific virtual switches on basis of specific incoming messages ----------------------------

if (content == "1on") {
relay1Value = HIGH;
}

if (content == "1off") {
relay1Value = LOW;
}

if (content == "2on") {
relay2Value = HIGH;
}

if (content == "2off") {
relay2Value = LOW;
}

if (content == "3on") {
relay3Value = HIGH;
}

if (content == "3off") {
relay3Value = LOW;
}

if (content == "4on") {
relay4Value = HIGH;
}

if (content == "4off") {
relay4Value = LOW;
}

// Set digital pin states according to virtual switch settings

digitalWrite(relay1,relay1Value);
digitalWrite(relay2,relay2Value);
digitalWrite(relay3,relay3Value);
digitalWrite(relay4,relay4Value);

}

// Initiate instances -----------------------------------

// Initiate a bouncer instance for each button
Bounce bouncer1 = Bounce();
Bounce bouncer2 = Bounce();
Bounce bouncer3 = Bounce();
Bounce bouncer4 = Bounce();

//-------------------------------------------------------

void setup()

{

// setup relay, button, bouncer 1 -----------------------
pinMode(relay1, OUTPUT);
pinMode(button1,INPUT);
digitalWrite(button1,HIGH);
bouncer1 .attach(button1);
bouncer1 .interval(5);

// setup relay, button, bouncer 2 -----------------------
pinMode(relay2, OUTPUT);
pinMode(button2,INPUT);
digitalWrite(button2,HIGH);
bouncer2 .attach(button2);
bouncer2 .interval(5);

// setup relay, button, bouncer 3 -----------------------
pinMode(relay3, OUTPUT);
pinMode(button3,INPUT);
digitalWrite(button3,HIGH);
bouncer3 .attach(button3);
bouncer3 .interval(5);

// setup relay, button, bouncer 4 -----------------------
pinMode(relay4, OUTPUT);
pinMode(button4,INPUT);
digitalWrite(button4,HIGH);
bouncer4 .attach(button4);
bouncer4 .interval(5);

// setup serial and ethernet communications -------------------------------
// Setup serial connection
Serial.begin(9600);

// Setup ethernet connection to MQTT broker
client.setServer("192.168.0.140", 8123);
client.setCallback(callback);
Ethernet.begin(mac, ip);
delay(1500);
lastReconnectAttempt = 0;
Serial.println(Ethernet.localIP());

// --- temp/hum sensor --//
dht.begin();
// --- temp/hum sensor --//

// --- PIR sensor --//
pinMode(pirPin, INPUT);
pinMode(ledpirPin, OUTPUT);
// --- PIR sensor --//

}

// --- temp/hum sensor --//
bool checkBound(float newValue, float prevValue, float maxDiff) {
return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff;
}

long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;
// --- temp/hum sensor --//

void loop()

{
if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
}
else {
client.loop(); }
// Listen for button interactions and take actions ----------------------------------------
// Note: Button actions do send MQTT message AND do set relay(x)Value to HIGH or LOW

if (bouncer1.update()) {
if (bouncer1.read() == HIGH) {
if (relay1Value == LOW) {
relay1Value = HIGH;
client.publish("home/relay","1on");
} else {
relay1Value = LOW;
client.publish("home/relay","1off");
}
}
}

//-----------------------------------------------

if (bouncer2.update()) {
if (bouncer2.read() == HIGH) {
if (relay2Value == LOW) {
relay2Value = HIGH;
client.publish("home/relay","2on");
} else {
relay2Value = LOW;
client.publish("home/relay","2off");
}
}
}

//------------------------------------------------

if (bouncer3.update()) {
if (bouncer3.read() == HIGH) {
if (relay3Value == LOW) {
relay3Value = HIGH;
client.publish("home/relay","3on");
} else {
relay3Value = LOW;
client.publish("home/relay","3off");
}
}
}

//-----------------------------------------------

if (bouncer4.update()) {
if (bouncer4.read() == HIGH) {
if (relay4Value == LOW) {
relay4Value = HIGH;
client.publish("home/relay","4on");
} else {
relay4Value = LOW;
client.publish("home/relay","4off");
}
}
}

// --- temp/hum sensor --//

long now = millis();
if (now - lastMsg > 60000) {
lastMsg = now;

// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float newHum = dht.readHumidity();
// Read temperature as Fahrenheit (isFahrenheit = true)
float newTemp = dht.readTemperature();

if (checkBound(newTemp, temp, diff)) {
temp = newTemp;
Serial.print("New temperature:");
Serial.println(String(temp).c_str());
client.publish(temperature_topic, String(temp).c_str());
}

if (checkBound(newHum, hum, diff)) {
hum = newHum;
Serial.print("New humidity:");
Serial.println(String(hum).c_str());
client.publish(humidity_topic, String(hum).c_str());
}
}
// --- temp/hum sensor --//

// --- PIR sensor --//
int pirValue = digitalRead(pirPin);
if (pirValue != lastPirValue) {
if (pirValue == HIGH) {
digitalWrite(ledpirPin, HIGH);
String message = String(pirValue);
client.publish("home/ruch1", message.c_str());
Serial.println(message.c_str());
}
if (pirValue == LOW) {
digitalWrite(ledpirPin, LOW);
String message = String(pirValue);
client.publish("home/ruch1", message.c_str());
Serial.println(message.c_str());
}
Serial.println(pirValue);
lastPirValue = pirValue;

// delay(30 * 1000);
}
// --- PIR sensor --//

}

// End of sketch ---------------------------------

OdpowiedzCytuj
Autor tematu Dodane : 22/09/2021 10:07 pm
isom
 isom
(@isom)
Prezes Moderator Zasłużony dla Forum, Donator 2K19, Donator 2K20

@dawidkadziela a możesz wgrać ten mój skecz i ustawić prawidłowe baud rate ? Zgodnie z moimi bazgrołami poniżej

3

 

OdpowiedzCytuj
Dodane : 22/09/2021 10:31 pm
Dawid Kądziela
(@dawidkadziela)
Początkujący

@isom No normalnie pusto nadal. Może sprzęt nie robi?

obraz
OdpowiedzCytuj
Autor tematu Dodane : 22/09/2021 10:42 pm
isom
 isom
(@isom)
Prezes Moderator Zasłużony dla Forum, Donator 2K19, Donator 2K20

Ok to arduino mega , zmień w moim skeczu ten fragment 

// Enable Soft SPI for NRF radio (note different radio wiring is required)
// The W5100 ethernet module seems to have a hard time co-operate with
// radio on the same spi bus.
//#if !defined(MY_W5100_SPI_EN) && !defined(ARDUINO_ARCH_SAMD)
#define MY_SOFTSPI
#define MY_SOFT_SPI_SCK_PIN 52
#define MY_SOFT_SPI_MISO_PIN 50
#define MY_SOFT_SPI_MOSI_PIN 51
//#endif
OdpowiedzCytuj
Dodane : 22/09/2021 10:53 pm
Dawid Kądziela
(@dawidkadziela)
Początkujący

Nadal cisza. Próbowałem też usunąć // z lini powyżej i poniżej ale nic to nie daje.

OdpowiedzCytuj
Autor tematu Dodane : 22/09/2021 11:01 pm
isom
 isom
(@isom)
Prezes Moderator Zasłużony dla Forum, Donator 2K19, Donator 2K20

@dawidkadziela dziwna to sprawa, jeszcze możesz sprawdzić taki prosty skecz cztery przekaźniki + przyciski , potrzebna biblioteka mqtt PubSubClient. jak nie wiesz która pobrać to wejdz w zarządzanie bibliotekami i wpisz mqtt i zainstaluj wszytko co dotyczy HA i mqtt , tylko bez ESP8266.

Przyciski sa na wejściach analogowych i aktywacja to zwarcie do GND 

Reszta powinna być jasna

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <Bounce2.h>

// Set relay variables to Arduino digital pins
int rel1 = 2;
int rel2 = 3;
int rel3 = 5;                   //przekaźniki          
int rel4 = 6;


// Set button variables to Arduino analog pins
int button1 = A1;
int button2 = A2;              //przyciski
int button3 = A3;
int button4 = A4;                         

// Set variables to act as virtual switches
// Set variable values initially to LOW (and not HIGH)
int rel1Value = LOW;             
int rel2Value = LOW;
int rel3Value = LOW;
int rel4Value = LOW;


//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[]    = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };  

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192,168,0,208);

// IP Address of your MQTT broker - change to adapt to your network
byte server[] = { 192, 168, 0, 110 };

// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  String content="";
  char character;
  for (int num=0;num<length;num++) {
      character = payload[num];
      content.concat(character);
  }   
  Serial.println(topic);
  Serial.println(content); // message sent out by button actions is returned from broker and serial printed


// Set specific virtual switches on basis of specific incoming messages ----------------------------
  
  if (content == "1on") {
    rel1Value = HIGH;
  }
  
  if (content == "1off") {
    rel1Value = LOW;
  }
  
  if (content == "2on") {
    rel2Value = HIGH;
  }
  
  if (content == "2off") {
    rel2Value = LOW;
  }

  
  if (content == "3on") {
    rel3Value = HIGH;
  }
  
  if (content == "3off") {
    rel3Value = LOW;
  }
  
  if (content == "4on") {
    rel4Value = HIGH;
  }
  
  if (content == "4off") {
    rel4Value = LOW;
  }
  
    
  // Set digital pin states according to virtual switch settings
    
  digitalWrite(rel1,rel1Value);
  digitalWrite(rel2,rel2Value);
  digitalWrite(rel3,rel3Value);
  digitalWrite(rel4,rel4Value);

}

// Initiate instances -----------------------------------

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

// Initiate a bouncer instance for each button
Bounce bouncer1 = Bounce();
Bounce bouncer2 = Bounce();
Bounce bouncer3 = Bounce();
Bounce bouncer4 = Bounce();

//-------------------------------------------------------

void setup()

{

  // setup rel, button, bouncer 1 -----------------------
  pinMode(rel1, OUTPUT);
  pinMode(button1,INPUT);
  digitalWrite(button1,HIGH);
  bouncer1 .attach(button1);
  bouncer1 .interval(5);

  // setup rel, button, bouncer 2 -----------------------
  pinMode(rel2, OUTPUT);
  pinMode(button2,INPUT);
  digitalWrite(button2,HIGH);
  bouncer2 .attach(button2);
  bouncer2 .interval(5);

  // setup rel, button, bouncer 3 -----------------------
  pinMode(rel3, OUTPUT);
  pinMode(button3,INPUT);
  digitalWrite(button3,HIGH);
  bouncer3 .attach(button3);
  bouncer3 .interval(5);

  // setup rel, button, bouncer 4 -----------------------
  pinMode(rel4, OUTPUT);
  pinMode(button4,INPUT);
  digitalWrite(button4,HIGH);
  bouncer4 .attach(button4);
  bouncer4 .interval(5);

  // setup serial and ethernet communications -------------------------------

  // Setup serial connection
  Serial.begin(9600);

  // Setup ethernet connection to MQTT broker
  Ethernet.begin(mac);
  if (client.connect("arduino-ip-208")) {  							// change as desired - clientname must be unique for MQTT broker
    client.publish("relay","hello world - here arduino ip 208");
    Serial.println("connected");
    client.subscribe("relay");										// subscribe to topic "relay"
  }
}

//----------------------------------------------

void loop()
{

// Listen for button interactions and take actions ----------------------------------------  
// Note: Button actions do send MQTT message AND do set rel(x)Value to HIGH or LOW

  if (bouncer1.update()) {
    if (bouncer1.read() == HIGH) {
      if (rel1Value == LOW) {
        rel1Value = HIGH;
        client.publish("relay","1on");								
      } else {
        rel1Value = LOW;
        client.publish("relay","1off");
      }
    }
  }  

//-----------------------------------------------
  
  if (bouncer2.update()) {
    if (bouncer2.read() == HIGH) {
      if (rel2Value == LOW) {
        rel2Value = HIGH;
        client.publish("relay","2on");
      } else {
        rel2Value = LOW;
        client.publish("relay","2off");
      }
    }
  }  
  
//------------------------------------------------  

  if (bouncer3.update()) {
    if (bouncer3.read() == HIGH) {
      if (rel3Value == LOW) {
        rel3Value = HIGH;
        client.publish("relay","3on");
      } else {
        rel3Value = LOW;
        client.publish("relay","3off");
      }
    }
  }  

//-----------------------------------------------
  
  if (bouncer4.update()) {
    if (bouncer4.read() == HIGH) {
      if (rel4Value == LOW) {
        rel4Value = HIGH;
        client.publish("relay","4on");
      } else {
        rel4Value = LOW;
        client.publish("relay","4off");
      }
    }
  }  
  
//------------------------------------------------  
  
  client.loop();
}

// End of sketch ---------------------------------

U mnie przy baud rate 9600 wszytko działa

1

 Ten skrypt jest gotowcem i publikuje tematy do brokera mqtt o stanie przekaźników , nie mam HA więc nie sprawdzę ale powinno działać. Rozbudowa o kolejne przekaźniki i przyciski nie powinna sprawiać problemu 

PS ustaw sobie IP dla arduino i IP HA , w kodzie jest adres mojego brokera i IP dla arduino jakie mi przyszło do głowy

Dla jasności to nie jest skecz mysensors , ale pozwoli sprawdzić czy twój moduł W5100-Ethernet jest ok

OdpowiedzCytuj
Dodane : 23/09/2021 7:08 pm
Dawid Kądziela
(@dawidkadziela)
Początkujący

@isom 

Dzięki Isom. Twój szkic nie mógł się skompilować nawet po zainstalowaniu dodatkowych bibliotek. Przy okazji znalazłem bibliotekę naszego rodaka "home-assistant-integration" i w przykładowym szkicu o nazwie "multi-state-button" dodałem linijki o nazwie użytkownika i hasła i się połączyło z HA! 🙂

Teraz muszę wymyślić jak to połączyć z moim szkicem aby My sensors zadziałało 🙂

Szkic

#include <Ethernet.h>
#include <ArduinoHA.h>

// This example uses JC Button library
// https://github.com/JChristensen/JC_Button
#include <JC_Button.h>

#define BUTTON_PIN 9
#define BUTTON_NAME "mybtn"
#define BROKER_ADDR IPAddress(192,168,0,140)
#define MY_MQTT_USER "mqtt"
#define MY_MQTT_PASSWORD "888496429"
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};

EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
HATriggers triggers;
Button btn(BUTTON_PIN);
bool holdingBtn = false;

void setup() {
// you don't need to verify return status
Ethernet.begin(mac);

// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");

// setup triggers
triggers.add("button_short_press", BUTTON_NAME);
triggers.add("button_long_press", BUTTON_NAME);
btn.begin();

mqtt.begin(BROKER_ADDR);
}

void loop() {
Ethernet.maintain();
mqtt.loop();
btn.read();

if (btn.pressedFor(3000) && !holdingBtn) {
triggers.trigger("button_long_press", BUTTON_NAME);
holdingBtn = true;
} else if (btn.wasReleased()) {
if (holdingBtn) {
holdingBtn = false;
} else {
triggers.trigger("button_short_press", BUTTON_NAME);
}
}
}

OdpowiedzCytuj
Autor tematu Dodane : 23/09/2021 9:42 pm
Dawid Kądziela
(@dawidkadziela)
Początkujący

Cześć,

Przepraszam że długo nie odpowiadałem. Sprawdziłem wszystkie opcje i wygląda na to że jednak łączy się do sieci LAN. Sprawdziłem to pingując adres.

Pozostaje jedynie konfiguracja w samym HA. Próbuję dodać integrację ale nic z tego nie wychodzi.

Przechwsssssytywanie

 

 

OdpowiedzCytuj
Autor tematu Dodane : 27/09/2021 1:14 pm
isom
 isom
(@isom)
Prezes Moderator Zasłużony dla Forum, Donator 2K19, Donator 2K20

@dawidkadziela a to w końcu ma być bramka LAN czy mqtt ? Bo jak LAN to raczej nie port 1883, na tym porcie masz brokera mqtt , przy LAN domyślny port to 5003 

OdpowiedzCytuj
Dodane : 27/09/2021 4:52 pm
Dawid Kądziela
(@dawidkadziela)
Początkujący

@isom teraz to ja już sam nie wiem. Ale udało mi się połączyć po zmianie portu na 5003 i utworzyłem dzięki temu integrację, która podczas łączenia nie wyświetliła błędu. Jednakże nadal nie widzę żadnego urządzenia w HA 🙁

obraz
OdpowiedzCytuj
Autor tematu Dodane : 28/09/2021 9:23 am
isom
 isom
(@isom)
Prezes Moderator Zasłużony dla Forum, Donator 2K19, Donator 2K20

@dawidkadziela nie wiem na którym skeczu bazujesz ale może aktywuj jakieś wejście w arduino i zrestartuj HA i zobacz czy coś się zmieni , jak nie to logi trzeba sprawdzać 

OdpowiedzCytuj
Dodane : 28/09/2021 1:41 pm
Udostępnij: