Merge branch 'master' of ssh://www.lexach.dns-cloud.net:56656/home/git/AHome into master

This commit is contained in:
2020-12-17 12:20:27 +03:00
26 changed files with 713 additions and 429 deletions

View File

@@ -15,8 +15,8 @@ framework = arduino
board_build.ldscript = eagle.flash.1m.ld
board_build.f_cpu = 26000000L
upload_protocol = espota
upload_port = 192.168.1.7
upload_port = 192.168.1.148
lib_deps =
Adafruit HTU21DF Library @ ^1.1.0
PubSubClient @ ^2.8
; ESP_EEPROM @ ^2.0.0
jwrw/ESP_EEPROM @ ^2.0.0

View File

@@ -7,7 +7,7 @@
#include <Adafruit_HTU21DF.h>
#include <PubSubClient.h>
#include <leds.h>
#include <EEPROM.h>
#include <ESP_EEPROM.h>
#define LED_BLUE D5 //GPIO14
#define LED_GREEN D6 //GPIO12
@@ -32,7 +32,7 @@ unsigned long cRun;
int minCnt = 0;
int measCnt = 1;
uint8_t mv, oldmv;
int adc, oldadc, delta;
uint16_t adc, oldadc, delta;
void reconnect();
void publishMin();
@@ -88,6 +88,7 @@ void setup() {
client.setCallback(callback);
EEPROM.begin(8);
EEPROM.get(0, delta);
adc = analogRead(A0);
cRun = millis();
}
@@ -105,7 +106,7 @@ void loop() {
if(cRun + 99 < millis()){
cRun = millis();
adc = analogRead(A0);
adc += int((analogRead(A0) - adc) / 10.0f);
mv = digitalRead(MOVE_SENS);
if(mv != oldmv){
oldmv = mv;
@@ -149,7 +150,7 @@ void reconnect() {
// подписываемся или переподписываемся на топик;
// можно подписаться не только на один, а на несколько топиков
char v[6];
ltoa(delta, v, 10);
itoa(delta, v, 10);
client.publish("/home/smallroom/ldelta", v);
client.subscribe("/home/smallroom/ldelta");
} else {
@@ -179,6 +180,8 @@ void publishMin()
client.publish("/home/smallroom/light", strFVal);
ultoa(cRun, strFVal, 10);
client.publish("/home/smallroom/millis", strFVal);
itoa(delta, strFVal, 10);
client.publish("/home/smallroom/ldelta", strFVal);
//digitalWrite(LED_BLUE, LOW);
}
}
@@ -203,7 +206,7 @@ void publishSec()
client.publish("/hometest/smallroom/millis", strFVal);
ltoa(adc, strFVal, 10);
client.publish("/hometest/smallroom/light", strFVal);
ultoa(delta, strFVal, 10);
itoa(delta, strFVal, 10);
client.publish("/hometest/smallroom/ldelta", strFVal);
//digitalWrite(LED_GREEN, LOW);
}
@@ -211,7 +214,9 @@ void publishSec()
void callback(char* topic, byte* payload, unsigned int length) {
if(strcmp(topic,"/home/smallroom/ldelta") == 0){
delta = atoi((char*)payload);
payload[length] = '\0';
String pl = String((char*)payload);
delta = pl.toInt();// atoi((char*)payload);
EEPROM.put(0, delta);
EEPROM.commit();
}

View File

@@ -17,3 +17,5 @@ board_build.ldscript = eagle.flash.1m.ld
;board_build.flash_mode = dout
upload_protocol = espota
upload_port = 192.168.1.132
lib_deps =
jwrw/ESP_EEPROM @ ^2.0.0

View File

@@ -3,6 +3,7 @@
#include <Ticker.h>
#include <AsyncMqttClient.h>
#include <leds.h>
#include <ESP_EEPROM.h>
#define R_LED (13)
#define G_LED (12)
@@ -13,9 +14,10 @@
bool meas = false;
short minCnt;
bool send_move = false;
int old_mov = 0;
int mov, old_mov = 0;
int adc = 0;
int lastADC = 0;
int mvDelay, mvDelaySet;
unsigned long cRun;
@@ -36,9 +38,9 @@ void onWifiConnect(const WiFiEventStationModeGotIP& event);
void onWifiDisconnect(const WiFiEventStationModeDisconnected& event);
void onMqttConnect(bool sessionPresent);
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason);
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total);
/* void onMqttSubscribe(uint16_t packetId, uint8_t qos);
void onMqttUnsubscribe(uint16_t packetId);
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total);
void onMqttPublish(uint16_t packetId); */
leds g_led(G_LED, 100);
@@ -83,8 +85,8 @@ void setup() {
mqttClient.onDisconnect(onMqttDisconnect);
/* mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish); */
mqttClient.onMessage(onMqttMessage);
mqttClient.setServer(mqtt_server, 1883);
mqttClient.setClientId("MidRoom");
@@ -122,6 +124,11 @@ void setup() {
Serial1.println(p); */
}
EEPROM.begin(16);
EEPROM.get(4, mvDelaySet);
//mvDelaySet = 90;
mvDelay = -1;
connectToWifi();
cRun = millis();
@@ -136,14 +143,25 @@ void loop() {
ArduinoOTA.handle();
g_led.tick();
//r_led.tick();
if (digitalRead(MOV_SENS) != old_mov){
if(digitalRead(MOV_SENS) > 0){
if(mvDelay == -1) mqttClient.publish("/home/midroom/move", 1, false, "1");
mvDelay = mvDelaySet;
}
/*if (digitalRead(MOV_SENS) != old_mov){
old_mov = digitalRead(MOV_SENS);
//Serial1.println(F("Change mov detected"));
mqttClient.publish("/home/midroom/move", 1, false, old_mov ? "1" : "0");
}
}*/
if(cRun + 999 < millis()){
cRun = millis();
if(mvDelay == 0) {
mqttClient.publish("/home/midroom/move", 1, false, "0");
mvDelay = -1;
}
if(mvDelay > 0) mvDelay--;
adc = analogRead(A0);
if(abs(adc - lastADC) > 50){
lastADC = adc;
@@ -175,10 +193,10 @@ void loop() {
//r_led.start();
//Serial1.println("Begin Publish");
dtostrf(t, 5, 1,v);
mqttClient.publish("/home/midroom/temp", 0, false, v);
mqttClient.publish("/home/midroom/temp", 1, false, v);
//Serial1.println("Publish1");
dtostrf(h, 5, 1,v);
mqttClient.publish("/home/midroom/humid", 0, false, v);
mqttClient.publish("/home/midroom/humid", 1, false, v);
//Serial1.println("Publish2");
if(firstRun){
stDelay++;
@@ -186,7 +204,7 @@ void loop() {
}
if(!firstRun && (mhz19.errorCode == RESULT_OK)){
itoa(co2, v, 10);
mqttClient.publish("/home/midroom/co2", 0, false, v);
mqttClient.publish("/home/midroom/co2", 1, false, v);
//Serial1.println("Publish3");
}
}
@@ -195,6 +213,10 @@ void loop() {
ultoa(millis(), v, 10);
if(mqttClient.connected()){
mqttClient.publish("/home/midroom/millis", 0, false, v);
itoa(mvDelay, v, 10);
mqttClient.publish("/home/midroom/movesec", 0, false, v);
itoa(mvDelaySet, v, 10);
mqttClient.publish("/home/midroom/movesecset", 0, false, v);
// dtostrf(t, 5, 1,v);
// mqttClient.publish("/home/midroom/temp", 0, false, v);
// //Serial1.println("Publish1");
@@ -236,21 +258,15 @@ void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
}
void onMqttConnect(bool sessionPresent) {
/* Serial1.println(F("Connected to MQTT."));
Serial1.print(F("Session present: "));
//Serial1.flush();
Serial1.println(sessionPresent); */
//digitalWrite(B_LED, HIGH);
//digitalWrite(R_LED, LOW);
//uint16_t packetIdSub =
// //Serial1.print("Subscribing Lamp1, packetId: ");
// //Serial1.println(packetIdSub);
//packetIdSub = mqttClient.subscribe("/home/kor/lamp2_set", 1);
////Serial1.print("Subscribing Lamp2, packetId: ");
////Serial1.println(packetIdSub);
////Serial1.println("Publishing at Lamp 1");
//mqttClient.publish("/home/kor/lamp2", 1, false, lStat2 ? "1" : "0");
////Serial1.println("Publishing at Lamp 2");
char v[15];
sprintf(v, "%u", mvDelaySet);
//itoa(mvDelaySet, v, 10);
mqttClient.publish("/home/midroom/mvdelay", 1, false, v);
mqttClient.subscribe("/home/midroom/mvdelay", 1);
// ultoa(ESP.getFlashChipSize(), v, 10);
// mqttClient.publish("/home/midroom/chipsize", 1, false, v);
// ultoa(ESP.getFlashChipRealSize(), v, 10);
// mqttClient.publish("/home/midroom/realchipsize", 1, false, v);
digitalWrite(B_LED, LOW);
}
@@ -264,7 +280,7 @@ void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
digitalWrite(B_LED, HIGH);
}
/* void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
// //Serial1.println("Subscribe acknowledged.");
// //Serial1.print(" packetId: ");
// //Serial1.println(packetId);
@@ -276,13 +292,16 @@ void onMqttUnsubscribe(uint16_t packetId) {
// //Serial1.println("Unsubscribe acknowledged.");
// //Serial1.print(" packetId: ");
// //Serial1.println(packetId);
}
}*/
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
if(strcmp(topic, "/home/kor/lamp1_set") == 0){
if(strcmp(topic, "/home/midroom/mvdelay") == 0){
mvDelaySet = atoi(payload);
EEPROM.put(4, mvDelaySet);
EEPROM.commit();
}
}
/*
void onMqttPublish(uint16_t packetId) {
//Serial1.println("Publish acknowledged.");
//Serial1.print(" packetId: ");

View File

@@ -2,6 +2,7 @@
#define MY_DEBUG
#define MY_RADIO_RF24
#define MY_RF24_CHANNEL (105)
#define MY_RF24_PA_LEVEL RF24_PA_HIGH
#include <MySensors.h>
#include <AHT10.h>
@@ -17,6 +18,10 @@ MyMessage msgTemp(0, V_TEMP);
MyMessage msgHum(1, V_HUM);
MyMessage msgMillis(2, V_VAR1);
MyMessage msgVolts(2, V_VAR2);
void sendData(MyMessage msg, int status);
void sendData(MyMessage msg, float status, uint8_t decm);
void sendData(MyMessage msg, bool status);
void sendData(MyMessage msg, uint32_t status);
AHT10 myAHT10(AHT10_ADDRESS_0X38);
@@ -24,40 +29,44 @@ void setup() {
analogReference(INTERNAL);
sensorValue = analogRead(BATTERY_SENSE_PIN);
v = sensorValue * 0.004659498;
batteryPcnt = (v * 100) / 4.2;
batteryPcnt = (v-3.0 * 100) / 1.2;
while (myAHT10.begin() != true)
{
Serial.println(F("AHT10 not connected or fail to load calibration coefficient")); //(F()) save string to flash & keeps dynamic memory free
delay(5000);
}
Serial.println(F("AHT10 OK"));
Serial.print(F("Temperature: ")); Serial.print(myAHT10.readTemperature(AHT10_FORCE_READ_DATA)); Serial.println(F(" +-0.3C"));
Serial.print(F("Humidity...: ")); Serial.print(myAHT10.readHumidity(AHT10_USE_READ_DATA)); Serial.println(F(" +-2%"));
Serial.print(F("T: ")); Serial.print(myAHT10.readTemperature(AHT10_FORCE_READ_DATA));// Serial.println(F(" +-0.3C"));
Serial.print(F("H: ")); Serial.print(myAHT10.readHumidity(AHT10_USE_READ_DATA));// Serial.println(F(" +-2%"));
cRun = millis();
send(msgMillis.set(cRun));
cRun = 0;
sendData(msgMillis, cRun);
//send(msgMillis.set(cRun));
}
void loop() {
float temp, hum;
//if((cRun + 29999) < millis()){
cRun = millis();
unsigned long t = millis();
temp = myAHT10.readTemperature(AHT10_FORCE_READ_DATA);
hum = myAHT10.readHumidity(AHT10_USE_READ_DATA);
Serial.print(F("Temperature: ")); Serial.print(temp); Serial.println(F(" +-0.3C"));
Serial.print(F("Humidity...: ")); Serial.print(hum); Serial.println(F(" +-2%"));
Serial.print(F("T: ")); Serial.println(temp);// Serial.println(F(" +-0.3C"));
Serial.print(F("H: ")); Serial.println(hum);// Serial.println(F(" +-2%"));
if (temp < 200){
send(msgTemp.set(temp, 1));
send(msgHum.set(hum, 1));
sendData(msgTemp, temp, 1);
sendData(msgHum, hum, 1);
// send(msgTemp.set(temp, 1));
// send(msgHum.set(hum, 1));
}
send(msgMillis.set(cRun));
sensorValue = analogRead(BATTERY_SENSE_PIN);
v = sensorValue * 0.004659498;
batteryPcnt = (v * 100) / 4.2;
sendBatteryLevel(batteryPcnt);
send(msgVolts.set(v, 2));
//}
sleep(60000 - (millis() - cRun));
//batteryPcnt = ((v-3.0) * 100) / 1.2;
//sendBatteryLevel(batteryPcnt);
sendData(msgVolts, v, 2);
//send(msgVolts.set(v, 2));
Serial.println(F("Tm run")); Serial.println(millis() - t);
sendData(msgMillis, cRun++);
//send(msgMillis.set(cRun++));
sleep(60000 - (millis() - t));
}
void presentation()
@@ -67,3 +76,61 @@ void presentation()
present(1, S_HUM, "Humid");
present(2, S_CUSTOM, "ESMillis");
}
void sendData(MyMessage msg, bool status)
{
bool send_data = false;
uint8_t count = 0;
while(send_data == false){
count++;
send_data = send(msg.set(status));
wait(100, C_SET, V_STATUS);
if ((count == 3 )&&(send_data == 0)){ // Если сделано 3 попытки и нет подтверждения отправки
count = 0; // Обнуляем счётчик
send_data = 1; // Выходим из цикла
}
}
}
void sendData(MyMessage msg, float status, uint8_t decm)
{
bool send_data = false;
uint8_t count = 0;
while(send_data == false){
count++;
send_data = send(msg.set(status, decm));
wait(100, C_SET, V_STATUS);
if ((count == 3 )&&(send_data == 0)){ // Если сделано 3 попытки и нет подтверждения отправки
count = 0; // Обнуляем счётчик
send_data = 1; // Выходим из цикла
}
}
}
void sendData(MyMessage msg, int status)
{
bool send_data = false;
uint8_t count = 0;
while(send_data == false){
count++;
send_data = send(msg.set(status));
wait(100, C_SET, V_STATUS);
if ((count == 3 )&&(send_data == 0)){ // Если сделано 3 попытки и нет подтверждения отправки
count = 0; // Обнуляем счётчик
send_data = 1; // Выходим из цикла
}
}
}
void sendData(MyMessage msg, uint32_t status)
{
bool send_data = false;
uint8_t count = 0;
while(send_data == false){
count++;
send_data = send(msg.set(status));
wait(100, C_SET, V_STATUS);
if ((count == 3 )&&(send_data == 0)){ // Если сделано 3 попытки и нет подтверждения отправки
count = 0; // Обнуляем счётчик
send_data = 1; // Выходим из цикла
}
}
}

View File

@@ -1,97 +1,28 @@
#include <Arduino.h>
/**
* 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.
*
*******************************
*
* DESCRIPTION
* The ArduinoGateway prints data received from sensors on the serial link.
* The gateway accepts input on serial which will be sent out on radio network.
*
* The GW code is designed for Arduino Nano 328p / 16MHz
*
* Wire connections (OPTIONAL):
* - Inclusion button should be connected between digital pin 3 and GND
* - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series
*
* LEDs (OPTIONAL):
* - To use the feature, uncomment any of the MY_DEFAULT_xx_LED_PINs
* - 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
*
*/
// Enable debug prints to serial monitor
#define MY_DEBUG
// Enable and select radio type attached
#define MY_RADIO_RF24
//#define MY_RADIO_NRF5_ESB
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95
// Set LOW transmit power level as default, if you have an amplified NRF-module and
// power your radio separately with a good regulator you can turn up PA level.
#define MY_RF24_CHANNEL (105)
#define MY_RF24_PA_LEVEL RF24_PA_HIGH
// Enable serial gateway
//#define MY_GATEWAY_SERIAL
// Define a lower baud rate for Arduinos running on 8 MHz (Arduino Pro Mini 3.3V & SenseBender)
#if F_CPU == 8000000L
#define MY_BAUD_RATE 38400
#endif
#define MY_TRANSPORT_WAIT_READY_MS 10000
// Enable inclusion mode
//#define MY_INCLUSION_MODE_FEATURE
// Enable Inclusion mode button on gateway
//#define MY_INCLUSION_BUTTON_FEATURE
// Inverses behavior of inclusion button (if using external pullup)
//#define MY_INCLUSION_BUTTON_EXTERNAL_PULLUP
// 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
// Inverses the behavior of leds
#define MY_WITH_LEDS_BLINKING_INVERSE
// Flash leds on rx/tx/err
// Uncomment to override default HW configurations
#define MY_DEFAULT_ERR_LED_PIN A3 // Error led pin
#define MY_DEFAULT_TX_LED_PIN A4 // the PCB, on board LED
#define MY_DEFAULT_RX_LED_PIN A5 // Receive led pin
#include <MySensors.h>
//#include <SdsDustSensor.h>
#include <SDS011.h>
#include <SoftwareSerial.h>
unsigned long cRun;
int cSec, adc, move, oldmov, minLight, minLightDB, LightInt;
int cSec, adc, move, oldmov, minLight, minLightDB, LightInt, timeDelay, curDelay;
uint8_t sdsPeriod;
bool lamp;
//float avgL;
@@ -108,7 +39,9 @@ MyMessage msgLightLevSet(3, V_VAR1);
MyMessage msgMillis(3, V_VAR4);
MyMessage msgMove(4, V_TRIPPED);
MyMessage msgLamp(5, V_VAR1);
void sendData(MyMessage msg, int status);
void sendData(MyMessage msg, float status);
void sendData(MyMessage msg, bool status);
void SDS011workmode(byte mode, SoftwareSerial *ser);
void setup()
@@ -132,6 +65,13 @@ void setup()
minLightDB = (loadState(2) << 8) + loadState(3);
LightInt = (loadState(4) << 8) + loadState(5);
sdsPeriod = loadState(6);
timeDelay = (loadState(8) << 8) + loadState(9);
curDelay = -1;
Serial.print(F("Min Light"));Serial.println(minLight);
Serial.print(F("Min LightDB"));Serial.println(minLightDB);
Serial.print(F("LightInt"));Serial.println(LightInt);
Serial.print(F("SDS Period"));Serial.println(sdsPeriod);
Serial.print(F("Time Delay"));Serial.println(timeDelay);
SDS011workmode(sdsPeriod, &sSerial);
// if(minLight == 0) minLight = 5;
//adc = analogRead(A0);
@@ -155,56 +95,73 @@ void presentation()
void loop()
{
float p25, p10;
move = digitalRead(A1);
if(move != oldmov){
oldmov = move;
send(msgMove.set(move));
//move = digitalRead(A1);
if(digitalRead(A1) > 0){
if(curDelay == -1) sendData(msgMove, true);
move = true;
curDelay = timeDelay;
}
// if(move != oldmov){
// oldmov = move;
// sendData(msgMove, move);
// //send(msgMove.set(move));
// }
adc = analogRead(A0);
//avgL += ((float)(adc) - avgL) * 0.1f;
if ((adc <= minLight) && (move == 1)){
analogWrite(LAMP_OUT, LightInt);
//digitalWrite(6, HIGH);
if(lamp == false){
Serial.println("Lamp ON");
Serial.print("ADC: ");Serial.print(adc);
Serial.print(", Move: ");Serial.println(move);
send(msgLightLev.set(adc, 2));
sendData(msgLightLev, adc);
//send(msgLightLev.set(adc, 2));
wait(50);
send(msgLamp.set(true));
sendData(msgLamp, true);
//send(msgLamp.set(true));
lamp = true;
}
}
else if((adc > (minLight + minLightDB)) || (move == 0)){
analogWrite(LAMP_OUT, 0);
//digitalWrite(6, LOW);
if(lamp == true){
Serial.println("Lamp OFF");
Serial.print("ADC: ");Serial.print(adc);
Serial.print(", Move: ");Serial.println(move);
send(msgLightLev.set(adc, 2));
sendData(msgLightLev, adc);
//send(msgLightLev.set(adc, 2));
wait(50);
send(msgLamp.set(false));
sendData(msgLamp, false);
//send(msgLamp.set(false));
lamp = false;
}
}
if(cRun + 999 < millis()){
cRun = millis();
if(curDelay == 0) {
sendData(msgMove, false);
move = false;
curDelay = -1;
}
if(curDelay > 0) curDelay--;
int error = sds.read(&p25, &p10);
//Serial.print("ADC: ");Serial.print(adc);Serial.print(", Move: ");Serial.println(move);
if (!error) {
Serial.println(millis()/1000);
Serial.println("P2.5: " + String(p25));
Serial.println("P10: " + String(p10));
send(msgHum25.set(p25, 1));
sendData(msgHum25, p25);
//send(msgHum25.set(p25, 1));
wait(100);
send(msgHum10.set(p10, 1));
sendData(msgHum10, p10);
//send(msgHum10.set(p10, 1));
}
if (++cSec > 19){
cSec = 0;
//sendHeartbeat();
wait(100);
send(msgLightLev.set(adc));
sendData(msgLightLev, adc);
//send(msgLightLev.set(adc));
wait(100);
uint32_t ms = millis();
send(msgMillis.set(ms));
@@ -240,12 +197,18 @@ void receive(const MyMessage &message)
sdsPeriod = message.getInt();
saveState(6, sdsPeriod);
Serial.print("Sds period:");
Serial.println(sdsPeriod);
}
if((message.sensor == 5) && (message.type == V_VAR2)){
timeDelay = message.getInt();
saveState(8, (timeDelay>>8) & 0xFF);
saveState(9, timeDelay & 0xFF);
Serial.print("time period:");
Serial.println(timeDelay);
}
}
////////////////// sends work mode command to SDS011 //////////////////////
void SDS011workmode(byte mode, SoftwareSerial *ser)
{
byte cs = 7 + mode;
@@ -255,3 +218,46 @@ void SDS011workmode(byte mode, SoftwareSerial *ser)
ser->write(sleep_command[i]);
}
}
void sendData(MyMessage msg, bool status)
{
bool send_data = false;
uint8_t count = 0;
while(send_data == false){
count++;
send_data = send(msg.set(status));
wait(1000, C_SET, msg.type);
if ((count == 3)&&(send_data == 0)){ // Если сделано 3 попытки и нет подтверждения отправки
count = 0; // Обнуляем счётчик
send_data = true; // Выходим из цикла
}
}
}
void sendData(MyMessage msg, float status)
{
bool send_data = false;
uint8_t count = 0;
while(send_data == false){
count++;
send_data = send(msg.set(status, 1));
wait(1000, C_SET, msg.type);
if ((count == 3 )&&(send_data == 0)){ // Если сделано 3 попытки и нет подтверждения отправки
count = 0; // Обнуляем счётчик
send_data = 1; // Выходим из цикла
}
}
}
void sendData(MyMessage msg, int status)
{
bool send_data = false;
uint8_t count = 0;
while(send_data == false){
count++;
send_data = send(msg.set(status));
wait(1000, C_SET, msg.type);
if ((count == 3 )&&(send_data == 0)){ // Если сделано 3 попытки и нет подтверждения отправки
count = 0; // Обнуляем счётчик
send_data = 1; // Выходим из цикла
}
}
}

View File

@@ -120,7 +120,7 @@ void loop() {
bool switchLight(uint8_t nLamp, int state, bool pub)
{
digitalWrite(nLamp, state);
if (pub) mqttClient.publish("/home/kuh/lighttbl", 1, false, state ? "1" : "0");
if (pub) mqttClient.publish("/home/kuh/lighttbl", 1, false, state ? "true" : "false");
return state;
}
@@ -145,7 +145,7 @@ void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
void onMqttConnect(bool sessionPresent) {
mqttClient.subscribe("/home/kuh/lighttbl", 1);
mqttClient.publish("/home/kuh/lighttbl", 1, false, digitalRead(LAMP) == 1 ? "1" : "0");
mqttClient.publish("/home/kuh/lighttbl", 1, false, digitalRead(LAMP) == 1 ? "true" : "false");
digitalWrite(LED_MQ, HIGH);
}
@@ -158,7 +158,7 @@ void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
if(strcmp(topic, "/home/kuh/lighttbl") == 0){
if (atoi(payload) == 1) switchLight(LAMP, 1, false);//lStat2 = true;
if (strcmp("true", payload) == 0) switchLight(LAMP, 1, false);//lStat2 = true;
else switchLight(LAMP, 0, false);//lStat2 = false;
}
}

View File

@@ -69,6 +69,10 @@
{
"name": "ExtSens",
"path": "ExtSens"
},
{
"name": "MainDoorMyS",
"path": "MainDoorMyS"
}
],
"settings": {

5
MainDoorMyS/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

7
MainDoorMyS/.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
]
}

View File

@@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

46
MainDoorMyS/lib/README Normal file
View File

@@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

View File

@@ -0,0 +1,25 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:pro16MHzatmega328]
platform = atmelavr
board = pro16MHzatmega328
framework = arduino
monitor_speed = 115200
lib_deps =
MySensors @ ^2.3.2
;[env:pro8MHzatmega168]
;platform = atmelavr
;board = pro8MHzatmega168
;framework = arduino
;monitor_speed = 115200
;lib_deps =
; MySensors @ ^2.3.2

138
MainDoorMyS/src/main.cpp Normal file
View File

@@ -0,0 +1,138 @@
#include <Arduino.h>
#define MY_DEBUG
// Enable and select radio type attached
#define MY_RF24_PA_LEVEL RF24_PA_HIGH
#define MY_RADIO_RF24
#define MY_RF24_CHANNEL (105)
#if F_CPU == 8000000L
#define MY_BAUD_RATE 38400
#endif
#define MY_DEFAULT_LED_BLINK_PERIOD 100
#define MY_WITH_LEDS_BLINKING_INVERSE
#define MY_DEFAULT_ERR_LED_PIN 2 // Error led pin
#define MY_DEFAULT_TX_LED_PIN 3 // the PCB, on board LED
#define MY_DEFAULT_RX_LED_PIN 4 // Receive led pin
#include <MySensors.h>
#define TOP_LOCK A0
#define INT_LOCK A1
#define DOWN_LOCK A3
#define SMALL_LOCK A2
#define DOOR A4
#define TOP_LOCK_ID 0
#define INT_LOCK_ID 1
#define DOWN_LOCK_ID 2
#define SMALL_LOCK_ID 3
#define DOOR_ID 4
#define CUSTOM_ID 5
bool bpTop, bpInt, bpDown, bpSmall, bpDoor;
MyMessage msgTop(TOP_LOCK_ID, V_LOCK_STATUS);
MyMessage msgInt(INT_LOCK_ID, V_LOCK_STATUS);
MyMessage msgDown(DOWN_LOCK_ID, V_LOCK_STATUS);
MyMessage msgSmall(SMALL_LOCK_ID, V_LOCK_STATUS);
MyMessage msgDoor(DOOR_ID, V_LOCK_STATUS);
MyMessage msgCust(CUSTOM_ID, V_VAR1);
void sendData(MyMessage msg, bool status);
void before()
{
pinMode(TOP_LOCK, INPUT_PULLUP);
pinMode(INT_LOCK, INPUT_PULLUP);
pinMode(DOWN_LOCK, INPUT_PULLUP);
pinMode(SMALL_LOCK, INPUT_PULLUP);
pinMode(DOOR, INPUT_PULLUP);
}
void presentation()
{
// Send the sketch version information to the gateway and Controller
sendSketchInfo("Main Door", "1.0");
present(TOP_LOCK_ID, S_LOCK, "Top");
present(INT_LOCK_ID, S_LOCK, "Int");
present(DOWN_LOCK_ID, S_LOCK, "Down");
present(SMALL_LOCK_ID, S_LOCK, "Small");
present(DOOR_ID, S_LOCK, "Door");
present(CUSTOM_ID, S_CUSTOM);
}
void setup() {
bpDoor = !digitalRead(DOOR);
bpTop = !digitalRead(TOP_LOCK);
bpInt = !digitalRead(INT_LOCK);
bpSmall = !digitalRead(SMALL_LOCK);
bpDown = !digitalRead(DOWN_LOCK);
sendData(msgDoor, bpDoor);
wait(100);
sendData(msgTop, bpTop);
wait(100);
sendData(msgInt, bpInt);
wait(100);
sendData(msgDown, bpDown);
wait(100);
sendData(msgSmall, bpSmall);
}
void loop() {
static uint32_t cRun = millis();
bool bTop, bInt, bDown, bSmall, bDoor;
bTop = !digitalRead(TOP_LOCK);
bInt = !digitalRead(INT_LOCK);
bDown = !digitalRead(DOWN_LOCK);
bSmall = !digitalRead(SMALL_LOCK);
bDoor = !digitalRead(DOOR);
if(bTop != bpTop){
bpTop = bTop;
Serial.print(F("Top Lock-"));Serial.println(bTop);
sendData(msgTop, bTop);
}
if(bInt != bpInt){
bpInt = bInt;
Serial.print(F("Int Lock-"));Serial.println(bInt);
sendData(msgInt, bInt);
}
if(bDown != bpDown){
bpDown = bDown;
Serial.print(F("Down Lock-"));Serial.println(bDown);
sendData(msgDown, bDown);
}
if(bSmall != bpSmall){
bpSmall = bSmall;
Serial.print(F("Small Lock-"));Serial.println(bSmall);
sendData(msgSmall, bSmall);
}
if(bDoor != bpDoor){
bpDoor = bDoor;
Serial.print(F("Door-"));Serial.println(bDoor);
sendData(msgDoor, bDoor);
}
if((cRun + 29999) < millis()){
cRun = millis();
send(msgCust.set(cRun));
}
}
void sendData(MyMessage msg, bool status)
{
bool send_data = false;
uint8_t count = 0;
while(send_data == false){
count++;
Serial.print("Sending a message, try No."); // Выводим в монитор порта попытку отправки
Serial.println(count); // и её номер
send_data = send(msg.set(status));
wait(1000, C_SET, V_STATUS);
if(send_data)
Serial.println("Message sent");
if ((count == 3 )&&(send_data == 0)){ // Если сделано 3 попытки и нет подтверждения отправки
count = 0; // Обнуляем счётчик
send_data = 1; // Выходим из цикла
Serial.println("Send failed"); // Выводим сообщение "Отправка не удалась"
}
}
}

11
MainDoorMyS/test/README Normal file
View File

@@ -0,0 +1,11 @@
This directory is intended for PlatformIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html

View File

@@ -1,98 +1,77 @@
#include <Arduino.h>
/*
* 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
* Example sketch showing how to control physical relays.
* This example will remember relay state after power failure.
* http://www.mysensors.org/build/relay
*/
// Enable debug prints to serial monitor
#define MY_DEBUG
//#define MY_WITH_LEDS_BLINKING_INVERSE
#define MY_DEFAULT_ERR_LED_PIN 4 // Error led pin
#define MY_DEFAULT_RX_LED_PIN 5 // Receive led pin
#define MY_DEFAULT_TX_LED_PIN 6 // the PCB, on board LED
// Enable and select radio type attached
#define MY_RADIO_RF24
//#define MY_RADIO_NRF5_ESB
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95
// Enable repeater functionality for this node
//#define MY_REPEATER_FEATURE
#define MY_RF24_CHANNEL (105)
#include <MySensors.h>
#define RELAY_PIN 4 // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
#define NUMBER_OF_RELAYS 1 // Total number of attached relays
#define RELAY_ON 1 // GPIO value to write to turn on attached relay
#define RELAY_OFF 0 // GPIO value to write to turn off attached relay
#define RELAY_PIN 3 // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
//MyMessage msgLev(1, V_DIMMER);
uint16_t lightLevel;
bool lightOn = false;
MyMessage msgMillis(1, V_VAR1);
void before()
{
for (int sensor=1, pin=RELAY_PIN; 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);
}
}
void setup()
{
pinMode(RELAY_PIN, OUTPUT);
lightLevel = loadState(0);
}
void presentation()
{
// Send the sketch version information to the gateway and Controller
sendSketchInfo("Relay", "1.0");
for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
// Register all sensors to gw (they will be created as child devices)
present(sensor, S_BINARY);
}
sendSketchInfo("Night Light", "2.1");
present(0, S_DIMMER, "Dimmer");
present(1, S_CUSTOM, "Service");
}
void loop()
{
static uint32_t cRun = millis();
if((cRun + 10000) <= millis()){
cRun = millis();
send(msgMillis.set(cRun));
}
}
void receive(const MyMessage &message)
{
// We only expect one type of message from controller. But we better check anyway.
if (message.getType()==V_STATUS) {
// Change relay state
digitalWrite(message.getSensor()-1+RELAY_PIN, message.getBool()?RELAY_ON:RELAY_OFF);
// Store state in eeprom
saveState(message.getSensor(), message.getBool());
// Write some debug info
switch(message.getType()){
case V_STATUS:
if(message.getBool() == true) {
analogWrite(RELAY_PIN, lightLevel);
lightOn = true;
}
else {
analogWrite(RELAY_PIN, 0);
lightOn = false;
}
Serial.print("Incoming change for sensor:");
Serial.print(message.getSensor());
Serial.print(", New status: ");
Serial.println(message.getBool());
break;
case V_PERCENTAGE:
uint16_t lev = message.getUInt();
if(lev > 100) lev = 100;
saveState(0, int(lev * 2.55));
lightLevel = int(lev * 2.55);
if(lightOn) analogWrite(RELAY_PIN, lightLevel);
Serial.print("Incoming change for dimmer:");
Serial.print(message.getSensor());
Serial.print(", New value: ");
Serial.println(message.getUInt());
break;
}
}

28
SerialGateWayMyS/.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,28 @@
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: avr-gcc.exe build active file",
"command": "C:/Users/lexa-/.platformio/packages/toolchain-atmelavr@1.50400.190710/bin/avr-gcc.exe",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"-mmcu=atmega328p"
],
"options": {
"cwd": "C:/Users/lexa-/.platformio/packages/toolchain-atmelavr@1.50400.190710/bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Generated task by Debugger"
}
],
"version": "2.0.0"
}

View File

@@ -10,8 +10,8 @@
[env:nanoatmega328]
platform = atmelavr
;board = nanoatmega328
board = uno
board = nanoatmega328
;board = uno
framework = arduino
monitor_speed = 115200
lib_deps = featherfly/SoftwareSerial @ ^1.0

View File

@@ -1,167 +1,33 @@
#include <Arduino.h>
/**
* 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.
*
*******************************
*
* DESCRIPTION
* The ArduinoGateway prints data received from sensors on the serial link.
* The gateway accepts input on serial which will be sent out on radio network.
*
* The GW code is designed for Arduino Nano 328p / 16MHz
*
* Wire connections (OPTIONAL):
* - Inclusion button should be connected between digital pin 3 and GND
* - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series
*
* LEDs (OPTIONAL):
* - To use the feature, uncomment any of the MY_DEFAULT_xx_LED_PINs
* - 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
*
*/
// Enable debug prints to serial monitor
#define MY_DEBUG
// Enable and select radio type attached
#define MY_RADIO_RF24
//#define MY_RADIO_NRF5_ESB
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95
// Set LOW transmit power level as default, if you have an amplified NRF-module and
// power your radio separately with a good regulator you can turn up PA level.
#define MY_RF24_PA_LEVEL RF24_PA_HIGH
// Enable serial gateway
#define MY_GATEWAY_SERIAL
#define MY_RF24_CHANNEL (105)
// Define a lower baud rate for Arduinos running on 8 MHz (Arduino Pro Mini 3.3V & SenseBender)
#if F_CPU == 8000000L
#define MY_BAUD_RATE 38400
#endif
// Enable inclusion mode
//#define MY_INCLUSION_MODE_FEATURE
// Enable Inclusion mode button on gateway
//#define MY_INCLUSION_BUTTON_FEATURE
// Inverses behavior of inclusion button (if using external pullup)
//#define MY_INCLUSION_BUTTON_EXTERNAL_PULLUP
// 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
// Inverses the behavior of leds
#define MY_WITH_LEDS_BLINKING_INVERSE
// Flash leds on rx/tx/err
// Uncomment to override default HW configurations
#define MY_DEFAULT_ERR_LED_PIN 4 // Error led pin
#define MY_DEFAULT_RX_LED_PIN 6 // Receive led pin
#define MY_DEFAULT_TX_LED_PIN 5 // the PCB, on board LED
#include <MySensors.h>
//#include <SdsDustSensor.h>
#include <SDS011.h>
#include <SoftwareSerial.h>
unsigned long cRun;
int cSec;
#define RX_PIN 2
#define TX_PIN 3
SoftwareSerial sSerial(RX_PIN, TX_PIN);
SDS011 sds;
//SdsDustSensor sds(sSerial);
MyMessage msgHum25(0, V_LEVEL);
MyMessage msgHum25_UN(0, V_UNIT_PREFIX);
MyMessage msgHum10(1, V_LEVEL);
MyMessage msgHum10_UN(1, V_UNIT_PREFIX);
void set_per(uint8_t per, SoftwareSerial *ser);
void setup()
{
Serial.begin(115200);
sSerial.begin(9600);
set_per(2, &sSerial);
sds.begin(&sSerial);
Serial.println("Begin");
//Serial.println(sds.queryFirmwareVersion().toString()); // prints firmware version
//Serial.println(sds.setActiveReportingMode().toString()); // ensures sensor is in 'active' reporting mode
//Serial.println(sds.setCustomWorkingPeriod(3).toString()); // sensor sends data every 3 minutes
//sds.setActiveReportingMode();
//sds.setCustomWorkingPeriod(1);
cRun = millis();
cSec = 0;
}
void presentation()
{
present(0, S_DUST, "pm2.5");
present(1, S_DUST, "pm10");
}
void loop()
{
float p25, p10;
if(cRun + 999 < millis()){
cRun = millis();
int error = sds.read(&p25, &p10);
if (!error) {
Serial.println(millis()/1000);
Serial.println("P2.5: " + String(p25));
Serial.println("P10: " + String(p10));
}
/* PmResult pm = sds.readPm();
if (pm.isOk()) {
send(msgHum25.set(pm.pm25, 2));
wait(100);
send(msgHum10.set(pm.pm10, 2));
}
if(++cSec == 60){
wait(100);
send(msgHum25_UN.set("pm2.5"));
wait(100);
send(msgHum10_UN.set("pm10"));
}*/
}
}
void set_per(uint8_t per, SoftwareSerial *ser)
{
ser->write(0xAA);
ser->write(0xB4);
ser->write(0x08);
ser->write(0xAA);
ser->write(0x01);
for(int i = 0; i < 10; i++) ser->print(0x00);
ser->write(0xFF);
ser->write(0xFF);
uint8_t crc = 0x07 + per;
ser->write(crc);
ser->write(0xAB);
}

View File

@@ -15,3 +15,5 @@ framework = arduino
board_build.ldscript = eagle.flash.2m.ld
upload_protocol = espota
upload_port = 192.168.1.129
lib_deps =
joaolopesf/RemoteDebug @ ^3.0.5

View File

@@ -5,6 +5,13 @@
#include <ESP_EEPROM.h>
#include <Bounce2.h>
//#define DEBUG_DISABLED true
#include "RemoteDebug.h" //https://github.com/JoaoLopesF/RemoteDebug
#ifndef DEBUG_DISABLED // Only if debug is not disabled (for production/release)
RemoteDebug Debug;
#endif
const char* ssid = "wf-home";
const char* password = "0ndthnrf";
const char* mqtt_server = "192.168.1.250";
@@ -29,7 +36,7 @@ unsigned long cRun;
Bounce l1 = Bounce();
Bounce l2 = Bounce();
bool switchLight(uint8_t nLamp, int state, bool pub);
bool switchLight(uint8_t nLamp, bool state, bool pub);
void connectToWifi();
void connectToMqtt();
void onWifiConnect(const WiFiEventStationModeGotIP& event);
@@ -103,6 +110,12 @@ void setup() {
connectToWifi();
cRun = millis();
Debug.begin("SW-BigRoom"); // Initialize the WiFi server
Debug.setResetCmdEnabled(true); // Enable the reset command
Debug.showProfiler(true); // Profiler (Good to measure times, to optimize codes)
Debug.showColors(true); // Colors
}
void loop() {
@@ -110,49 +123,35 @@ void loop() {
l1.update();
l2.update();
if(l1.fell()){
switchLight(R_LED1, !digitalRead(R_LED1), true);
//lStat1 = !lStat1;
lStat1 = !lStat1;
switchLight(R_LED1, lStat1, true);
}
if(l2.fell()){
switchLight(R_LED2, !digitalRead(R_LED2), true);
//lStat2 = !lStat2;
lStat2 = !lStat2;
switchLight(R_LED2, lStat2, true);
}
// if(lStat1 != oldLStat1){
// digitalWrite(R_LED1, lStat1);
// oldLStat1 = lStat1;
// if(!rcv)
// mqttClient.publish("/home/bigroom/lamp1", 0, false, lStat1 ? "1" : "0");
// else
// rcv = false;
// EEPROM.put(0, lStat1);
// EEPROM.commit();
// }
// if(lStat2 != oldLStat2){
// digitalWrite(R_LED2, lStat2);
// oldLStat2 = lStat2;
// if(!rcv)
// mqttClient.publish("/home/bigroom/lamp2", 0, false, lStat2 ? "1" : "0");
// else
// rcv = false;
// EEPROM.put(1, lStat2);
// EEPROM.commit();
// }
if (cRun + 9999 < millis()){
cRun = millis();
char v[11];
ultoa(cRun, v, 10);
mqttClient.publish("/home/bigroom/millislamp", 0, false, v);
//debugI("*Publish Millis: %u");
}
Debug.handle();
yield();
}
bool switchLight(uint8_t nLamp, int state, bool pub)
bool switchLight(uint8_t nLamp, bool state, bool pub)
{
digitalWrite(nLamp, state);
EEPROM.put(nLamp == R_LED1 ? 0 : 1, state);
EEPROM.commit();
String topic = "/home/bigroom/lamp";
char n = nLamp == R_LED1 ? '1' : '2';
if (pub) mqttClient.publish(String(topic + n).c_str(), 1, false, state ? "1" : "0");
//if (pub){
mqttClient.publish(String(topic + n).c_str(), 1, false, state ? "true" : "false");
debugI("*Publish State %d-%s, lst1:%d, lst2%d", n, state ? "true" : "false", lStat1, lStat2);
//}
return state;
}
@@ -174,10 +173,12 @@ void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
}
void onMqttConnect(bool sessionPresent) {
mqttClient.subscribe("/home/bigroom/lamp1", 1);
mqttClient.subscribe("/home/bigroom/lamp2", 1);
mqttClient.publish("/home/bigroom/lamp1", 1, false, lStat1 ? "1" : "0");
mqttClient.publish("/home/bigroom/lamp2", 1, false, lStat2 ? "1" : "0");
mqttClient.publish("/home/bigroom/lamp1", 1, false, lStat1 ? "true" : "false");
mqttClient.publish("/home/bigroom/lamp2", 1, false, lStat2 ? "true" : "false");
mqttClient.publish("/home/bigroom/lamp1_set", 1, false, lStat1 ? "true" : "false");
mqttClient.publish("/home/bigroom/lamp2_set", 1, false, lStat2 ? "true" : "false");
mqttClient.subscribe("/home/bigroom/lamp1_set", 1);
mqttClient.subscribe("/home/bigroom/lamp2_set", 1);
digitalWrite(B_LED, LOW);
}
@@ -189,17 +190,31 @@ void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
}
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
if(String(topic) == "/home/bigroom/lamp1"){
if (atoi(payload) == 1) switchLight(R_LED1, 1, false);
//lStat1 = true;
else switchLight(R_LED1, 0, false);
//lStat1 = false;
//rcv = true;
char s[10];
strncpy(s, payload, len);
if(String(topic) == "/home/bigroom/lamp1_set"){
// if (atoi(payload) == 1) switchLight(R_LED1, 1, false);
if (strncmp("true", payload, 4) == 0){
switchLight(R_LED1, true, false);
debugI("*Switch from MQTT T1: %s", s);
}
if(String(topic) == "/home/bigroom/lamp2"){
if (atoi(payload) == 1) switchLight(R_LED2, 1, false);
//if (atoi(payload) == 1) switchLight(R_LED2, 1, false);
//lStat1 = true;
else switchLight(R_LED2, 0, false);
else{
switchLight(R_LED1, false, false);
debugI("*Switch from MQTT F1: %s", s);
}
}
if(String(topic) == "/home/bigroom/lamp2_set"){
if (strncmp("true", payload, 4) == 0){
switchLight(R_LED2, true, false);
debugI("*Switch from MQTT T2: %s", s);
}
//if (atoi(payload) == 1) switchLight(R_LED2, 1, false);
//lStat1 = true;
else{
switchLight(R_LED2, false, false);
debugI("*Switch from MQTT F2: %s", s);
}
}
}

View File

@@ -57,13 +57,13 @@ void longPress()
{
//lStat1 = false;
switchLight(R_LED, 0, true);
mqttClient.publish("/home/bigroom/lamp1", 0, false, "0");
mqttClient.publish("/home/bigroom/lamp2", 0, false, "0");
mqttClient.publish("/home/midroom/lamp1", 0, false, "0");
mqttClient.publish("/home/midroom/lamp2", 0, false, "0");
mqttClient.publish("/home/smallroom/lamp1", 0, false, "0");
mqttClient.publish("/home/smallroom/lamp2", 0, false, "0");
mqttClient.publish("/home/kuh/lighttbl", 0, false, "0");
mqttClient.publish("/home/bigroom/lamp1_set", 0, false, "false");
mqttClient.publish("/home/bigroom/lamp2_set", 0, false, "false");
mqttClient.publish("/home/midroom/lamp1_set", 0, false, "false");
mqttClient.publish("/home/midroom/lamp2_set", 0, false, "false");
mqttClient.publish("/home/smallroom/lamp1_set", 0, false, "false");
mqttClient.publish("/home/smallroom/lamp2_set", 0, false, "false");
mqttClient.publish("/home/kuh/lighttbl", 0, false, "false");
}
void setup() {
@@ -158,7 +158,8 @@ bool switchLight(uint8_t nLamp, int state, bool pub)
digitalWrite(nLamp, state);
EEPROM.put(0, state);
EEPROM.commit();
if (pub) mqttClient.publish("/home/kor/lamp1", 1, false, state ? "1" : "0");
//if (pub)
mqttClient.publish("/home/kor/lamp1", 1, false, state ? "true" : "false");
return state;
}
@@ -186,8 +187,9 @@ void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
}
void onMqttConnect(bool sessionPresent) {
mqttClient.subscribe("/home/kor/lamp1", 1);
mqttClient.publish("/home/kor/lamp1", 0, false, digitalRead(R_LED) == 1 ? "1" : "0");
mqttClient.publish("/home/kor/lamp1", 0, false, digitalRead(R_LED) == 1 ? "true" : "false");
mqttClient.publish("/home/kor/lamp1_set", 0, false, digitalRead(R_LED) == 1 ? "true" : "false");
mqttClient.subscribe("/home/kor/lamp1_set", 1);
digitalWrite(B_LED, LOW);
}
@@ -215,8 +217,8 @@ void onMqttUnsubscribe(uint16_t packetId) {
}
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
if(strcmp(topic, "/home/kor/lamp1") == 0){
if (atoi(payload) == 1) switchLight(R_LED, 1, false);//lStat1 = true;
if(strcmp(topic, "/home/kor/lamp1_set") == 0){
if (strncmp("true", payload, 4) == 0) switchLight(R_LED, 1, false);//lStat1 = true;
else switchLight(R_LED, 0, false);//lStat1 = false;
//rcv = true;
}

View File

@@ -117,7 +117,8 @@ bool switchLight(uint8_t nLamp, int state, bool pub)
EEPROM.commit();
String topic = "/home/midroom/lamp";
char n = nLamp == R_LED1 ? '1' : '2';
if (pub) mqttClient.publish(String(topic + n).c_str(), 1, false, state ? "1" : "0");
//if (pub)
mqttClient.publish(String(topic + n).c_str(), 1, false, state ? "true" : "false");
return state;
}
@@ -139,10 +140,12 @@ void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
}
void onMqttConnect(bool sessionPresent) {
mqttClient.subscribe("/home/midroom/lamp1", 1);
mqttClient.subscribe("/home/midroom/lamp2", 1);
mqttClient.publish("/home/midroom/lamp1", 1, false, digitalRead(R_LED1) == 1 ? "1" : "0");
mqttClient.publish("/home/midroom/lamp2", 1, false, digitalRead(R_LED2) == 1 ? "1" : "0");
mqttClient.publish("/home/midroom/lamp1", 1, false, digitalRead(R_LED1) == 1 ? "true" : "false");
mqttClient.publish("/home/midroom/lamp2", 1, false, digitalRead(R_LED2) == 1 ? "true" : "false");
mqttClient.publish("/home/midroom/lamp1_set", 1, false, digitalRead(R_LED1) == 1 ? "true" : "false");
mqttClient.publish("/home/midroom/lamp2_set", 1, false, digitalRead(R_LED2) == 1 ? "true" : "false");
mqttClient.subscribe("/home/midroom/lamp1_set", 1);
mqttClient.subscribe("/home/midroom/lamp2_set", 1);
digitalWrite(B_LED, LOW);
}
@@ -154,12 +157,12 @@ void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
}
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
if(strcmp(topic, "/home/midroom/lamp1") == 0){
if (atoi(payload) == 1) switchLight(R_LED1, 1, false);//lStat1 = true;
if(strcmp(topic, "/home/midroom/lamp1_set") == 0){
if (strncmp("true", payload, 4) == 0) switchLight(R_LED1, 1, false);//lStat1 = true;
else switchLight(R_LED1, 0, false);//lStat1 = false;
}
if(strcmp(topic, "/home/midroom/lamp2") == 0){
if (atoi(payload) == 1) switchLight(R_LED2, 1, false);//lStat2 = true;
if(strcmp(topic, "/home/midroom/lamp2_set") == 0){
if (strncmp("true", payload, 4) == 0) switchLight(R_LED2, 1, false);//lStat2 = true;
else switchLight(R_LED2, 0, false);//lStat2 = false;
}
}

View File

@@ -125,7 +125,8 @@ bool switchLight(uint8_t nLamp, int state, bool pub)
EEPROM.commit();
String topic = "/home/smallroom/lamp";
char n = nLamp == R_LED1 ? '1' : '2';
if (pub) mqttClient.publish(String(topic + n).c_str(), 1, false, state ? "1" : "0");
//if (pub)
mqttClient.publish(String(topic + n).c_str(), 1, false, state ? "true" : "false");
return state;
}
@@ -153,10 +154,12 @@ void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
}
void onMqttConnect(bool sessionPresent) {
mqttClient.subscribe("/home/smallroom/lamp1", 1);
mqttClient.subscribe("/home/smallroom/lamp2", 1);
mqttClient.publish("/home/smallroom/lamp1", 1, false, digitalRead(R_LED1) == 1 ? "1" : "0");
mqttClient.publish("/home/smallroom/lamp2", 1, false, digitalRead(R_LED2) == 1 ? "1" : "0");
mqttClient.publish("/home/smallroom/lamp1", 1, false, digitalRead(R_LED1) == 1 ? "true" : "false");
mqttClient.publish("/home/smallroom/lamp2", 1, false, digitalRead(R_LED2) == 1 ? "true" : "false");
mqttClient.publish("/home/smallroom/lamp1_set", 1, false, digitalRead(R_LED1) == 1 ? "true" : "false");
mqttClient.publish("/home/smallroom/lamp2_set", 1, false, digitalRead(R_LED2) == 1 ? "true" : "false");
mqttClient.subscribe("/home/smallroom/lamp1_set", 1);
mqttClient.subscribe("/home/smallroom/lamp2_set", 1);
digitalWrite(B_LED, LOW);
}
@@ -168,12 +171,12 @@ void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
}
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
if(strcmp(topic, "/home/smallroom/lamp1") == 0){
if (atoi(payload) == 1) switchLight(R_LED1, 1, false);//lStat1 = true;
if(strcmp(topic, "/home/smallroom/lamp1_set") == 0){
if (strncmp("true", payload, 4) == 0) switchLight(R_LED1, 1, false);//lStat1 = true;
else switchLight(R_LED1, 0, false);//lStat1 = false;
}
if(strcmp(topic, "/home/smallroom/lamp2") == 0){
if (atoi(payload) == 1) switchLight(R_LED2, 1, false);//lStat2 = true;
if(strcmp(topic, "/home/smallroom/lamp2_set") == 0){
if (strncmp("true", payload, 4) == 0) switchLight(R_LED2, 1, false);//lStat2 = true;
else switchLight(R_LED2, 0, false);//lStat2 = false;
}
}

View File

@@ -15,3 +15,8 @@ framework = arduino
monitor_speed = 115200
upload_protocol = espota
upload_port = 192.168.1.134
lib_deps =
closedcube/ClosedCube HDC1080 @ ^1.3.2
mathertel/RotaryEncoder @ ^1.3.0
robtillaart/PCF8574 @ ^0.2.1
robtillaart/I2C_EEPROM @ ^1.3.0

View File

@@ -574,8 +574,10 @@ void onMqttConnect(bool sessionPresent) {
mqttClient.subscribe("/home/vt/hdb_set", 1);
sprintf(v, "%.2f", wCounter.QH);
mqttClient.publish("/home/vt/qhot", 1, false, v);
mqttClient.publish("/home/vt/qhot_set", 1, false, v);
sprintf(v, "%.2f", wCounter.QC);
mqttClient.publish("/home/vt/qcold", 1, false, v);
mqttClient.publish("/home/vt/qcold_set", 1, false, v);
itoa(wUstavki.hDB, v, 10);
mqttClient.publish("/home/vt/hdb", 1, false, v);
itoa(wUstavki.hSP, v, 10);
@@ -653,8 +655,13 @@ void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties
ee.writeBlock(8, (uint8_t*)&wUstavki, sizeof(wCounter));
itoa(wUstavki.hDB, v, 10);
mqttClient.publish("/home/vt/hdb", 1, false, v);
} else
if(strcmp(topic, "/home/vt/flood") == 0){
pcf.write(LED_RED, !atoi(payload));
c_flood = atoi(payload);
}
}
void onMqttPublish(uint16_t packetId) {
//Serial1.println("Publish acknowledged.");
//Serial1.print(" packetId: ");