внесу свои 5 копеек в тему... надеюсь будет полезно сообществу.
скетч продвинутого выключателя, работает с МДМ, управляется по HTTP
у выключателя две функции:
1.короткое нажатие - обычное включение выключение света с отправкой запроса на изменение статуса в МДМ для отображения на сцене
2.длинное нажатие - просто отправка запроса в МДМ на выполнение скрипта, скрипт можно написать любой, соответственно и выполнить любое действие
у меня например один выключатель коротким нажатием управляет светом в своей комнате, а длинным - светом в прихожей, т.к. до выключателя в прихожей нужно идти к входной двери. (аналог проходного)
скетч для ардуино IDE....
осторожно, код не идеален, сам я не программист, собирал по кусочкам, оптимизировал под себя.
сейчас дома работает уже 4 шт, нареканий не заметил.
скриншот сцены:
http://prntscr.com/7o98hp
Зеленые индикаторы под лампочкой - статус доступности хоста (пингуется - зеленый, не пингуется - красный) для отслеживания доступности ESP8266
Код: Выделить всё
#include <ESP8266WiFi.h>
const int buttonPin = 14; // really - 14
const int ledPin = 4; // actually - 5
bool ledState = LOW; // the current state of the output pin
bool led2State = LOW;
bool buttonState; // the current reading from the input pin
bool lastButtonState = HIGH;
bool countStart = 0;
bool ignoreUp = 0;
#define holdTime 1000
long btnDnTime; // time the button was pressed down
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50;
String sensor_id = "kitchen-light-switch";
const char* ssid = "net1";
const char* password = "passpass";
const char* host = "192.168.10.200";
WiFiServer server(80);
void setup() {
WiFi.mode(WIFI_STA);
// initialize digital pin 13 as an output.
pinMode(ledPin, OUTPUT);
Serial.begin(57600);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
Serial.println("Server started");
digitalWrite(ledPin, 1);
}
// the loop function runs over and over again forever
void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading == LOW && countStart && (millis() - btnDnTime) > long(holdTime))
{
Serial.println("tringger down");
led2State = !led2State;
String url = String("/objects/?script=holdbutton&name=")+sensor_id+"&type=remoteswitch&action="+led2State; //запрос на долгое нажатие
send_switch(url);
btnDnTime = millis();
ignoreUp = 1;
}
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW){
countStart = 1;
btnDnTime = millis();
}
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
countStart = 0;
if (!ignoreUp){
// if (led2State){
// led2State = !led2State;
// String url = String("/objects/?script=holdbutton&name=")+sensor_id+"&type=remoteswitch&action="+led2State;
// send_switch(url);
// }
// else{
digitalWrite(ledPin, ledState);
ledState = !ledState;
String url = String("/objects/?object=")+sensor_id+"&op=set&p=status&v="+!ledState;
send_switch(url);
// }
}
ignoreUp = 0;
}
}
}
lastButtonState = reading;
///#######################################
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
// Match the request
int val;
if (req.indexOf("/?pin=off") != -1){
val = 0;
lastButtonState = 0;
ledState = 0;
digitalWrite(ledPin, val);
// String url = String("/objects/?object=")+sensor_id+"&op=set&p=status&v="+ledState;
// send_switch(url);
}
else if (req.indexOf("/?pin=on") != -1){
val = 1;
lastButtonState = 1;
ledState = 1;
digitalWrite(ledPin, val);
// String url = String("/objects/?object=")+sensor_id+"&op=set&p=status&v="+ledState;
// send_switch(url);
}
else if (req.indexOf("/?status") != -1){
//fg
}
else {
//Serial.println("invalid request");
client.stop();
return;
}
// Set GPIO2 according to the request
// digitalWrite(ledPin, val);
client.flush();
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n";
s += ledState;
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");
//#########################
}
void send_switch(String turl){
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
//String url = String("/objects/?script=tempsensor&name=")+sensor_id+"&temp="+t+"&hum="+h+"&freemem="+freemem+"&moving="+moving_detected;
String url = turl;
Serial.print("Requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(50);
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
client.stop();
}