Merge branch 'development' of https://github.com/arendst/Tasmota into development

This commit is contained in:
Luis Teixeira 2020-03-10 22:46:48 +00:00
commit 4910e033b3
14 changed files with 443 additions and 1689 deletions

View File

@ -55,13 +55,13 @@ The following binary downloads have been compiled with ESP8266/Arduino library c
### Version 8.1.0.10
- Change default my_user_config.h driver and sensor support removing most sensors and adding most drivers
- Change DHT driver (#7468, #7717)
- Change Lights: simplified gamma correction and 10 bits internal computation
- Change commands ``Prefix``, ``Ssid``, ``StateText``, ``NTPServer``, and ``FriendlyName`` displaying all items
- Change IRremoteESP8266 library updated to v2.7.4
- Change Zigbee command prefix from ``Zigbee*`` to ``Zb*``
- Change MQTT message size with additional 200 characters
- Change display of some date and time messages from "Wed Feb 19 10:45:12 2020" to "2020-02-19T10:45:12"
- Change switchmode 6 according to issue 7778 (#7831)
- Fix Sonoff Bridge, Sc, L1, iFan03 and CSE7766 serial interface to forced speed, config and disable logging
- Fix commands ``Display`` and ``Counter`` from overruling command processing (#7322)
- Fix ``White`` added to light status (#7142)
@ -108,8 +108,6 @@ The following binary downloads have been compiled with ESP8266/Arduino library c
- Add ``ZbZNPReceived``and ``ZbZCLReceived`` being published to MQTT when ``SetOption66 1``
- Add optional Wifi AccessPoint passphrase define WIFI_AP_PASSPHRASE in my_user_config.h (#7690)
- Add support for FiF LE-01MR energy meter by saper-2 (#7584)
- Add new DHT driver. The old driver can still be used using define USE_DHT_OLD (#7468)
- Add another new DHT driver based on ESPEasy. The old driver can still be used using define USE_DHT_OLD. The previous new driver can be used with define USE_DHT_V2 (#7717)
- Add initial support for Sensors AHT10 and AHT15 by Martin Wagner (#7596)
- Add support for Wemos Motor Shield V1 by Denis Sborets (#7764)
- Add Zigbee enhanced commands decoding, added ``ZbPing``

View File

@ -4,12 +4,13 @@
- Change default my_user_config.h driver and sensor support removing most sensors and adding most drivers
- Change IRremoteESP8266 library updated to v2.7.4
- Change switchmode 6 according to issue 7778 (#7831)
- Revert switchmode 6 according to issue 7778 (#7831)
- Add support for Jarolift rollers by Keeloq algorithm
- Add Zigbee features and improvements and remove support for Zigbee commands starting with ``Zigbee...``
- Add support for MaxBotix HRXL-MaxSonar ultrasonic range finders by Jon Little (#7814)
- Add support for Romanian language translations by Augustin Marti
- Add command ``SetOption89 0/1`` for Zigbee distinct MQTT topics per device for SENSOR, allowing retained messages (#7835)
- Change Hue emulation code optimization
### 8.1.0.9 20200220

View File

@ -221,6 +221,17 @@ void SwitchHandler(uint8_t mode)
switchflag = POWER_TOGGLE; // ...and Toggle
}
break;
case PUSHBUTTONHOLD_INV:
if ((NOT_PRESSED == button) && (PRESSED == Switch.last_state[i])) {
Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; // Start timer on button press...
}
if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i]) && (Switch.hold_timer[i])) {
Switch.hold_timer[i] = 0; // Button released and hold timer not expired : stop timer.
switchflag = POWER_TOGGLE; // ...and Toggle
}
break;
/*
// Reverted Fix switchmode 6 according to issue 7778 (#7831)
case PUSHBUTTONHOLD_INV:
if ((PRESSED == button) && (NOT_PRESSED == Switch.last_state[i])) {
Switch.hold_timer[i] = loops_per_second * Settings.param[P_HOLD_TIME] / 10; // Start timer on button press...
@ -230,6 +241,7 @@ void SwitchHandler(uint8_t mode)
Switch.hold_timer[i] = 0; // Button released : stop timer.
}
break;
*/
case TOGGLEMULTI:
case FOLLOWMULTI:
case FOLLOWMULTI_INV:

View File

@ -58,7 +58,7 @@ bool UdpDisconnect(void)
bool UdpConnect(void)
{
if (!udp_connected) {
if (!udp_connected && !restart_flag) {
// Simple Service Discovery Protocol (SSDP)
if (PortUdp.beginMulticast(WiFi.localIP(), IPAddress(239,255,255,250), 1900)) {
AddLog_P(LOG_LEVEL_INFO, PSTR(D_LOG_UPNP D_MULTICAST_REJOINED));

View File

@ -1935,6 +1935,7 @@ void OtherSaveSettings(void)
SettingsUpdateText(SET_WEBPWD, (!strlen(tmp)) ? "" : (strchr(tmp,'*')) ? SettingsText(SET_WEBPWD) : tmp);
Settings.flag.mqtt_enabled = WebServer->hasArg("b1"); // SetOption3 - Enable MQTT
#ifdef USE_EMULATION
UdpDisconnect();
#if defined(USE_EMULATION_WEMO) || defined(USE_EMULATION_HUE)
WebGetArg("b2", tmp, sizeof(tmp));
Settings.flag2.emulation = (!strlen(tmp)) ? 0 : atoi(tmp);

View File

@ -55,7 +55,9 @@ String HueBridgeId(void)
{
String temp = WiFi.macAddress();
temp.replace(":", "");
String bridgeid = temp.substring(0, 6) + "FFFE" + temp.substring(6);
String bridgeid = temp.substring(0, 6);
bridgeid += "FFFE";
bridgeid += temp.substring(6);
return bridgeid; // 5CCF7FFFFE139F3D
}
@ -83,16 +85,17 @@ void HueRespondToMSearch(void)
char response[320];
snprintf_P(response, sizeof(response), HUE_RESPONSE, WiFi.localIP().toString().c_str(), HueBridgeId().c_str());
int len = strlen(response);
String uuid = HueUuid();
snprintf_P(response + len, sizeof(response) - len, HUE_ST1, HueUuid().c_str());
snprintf_P(response + len, sizeof(response) - len, HUE_ST1, uuid.c_str());
PortUdp.write(response);
PortUdp.endPacket();
snprintf_P(response + len, sizeof(response) - len, HUE_ST2, HueUuid().c_str(), HueUuid().c_str());
snprintf_P(response + len, sizeof(response) - len, HUE_ST2, uuid.c_str(), uuid.c_str());
PortUdp.write(response);
PortUdp.endPacket();
snprintf_P(response + len, sizeof(response) - len, HUE_ST3, HueUuid().c_str());
snprintf_P(response + len, sizeof(response) - len, HUE_ST3, uuid.c_str());
PortUdp.write(response);
PortUdp.endPacket();
@ -134,17 +137,15 @@ const char HUE_DESCRIPTION_XML[] PROGMEM =
"</device>"
"</root>\r\n"
"\r\n";
const char HUE_LIGHTS_STATUS_JSON1[] PROGMEM =
"{\"on\":{state},"
"{light_status}"
"\"alert\":\"none\","
const char HUE_LIGHTS_STATUS_JSON1_SUFFIX[] PROGMEM =
"%s\"alert\":\"none\","
"\"effect\":\"none\","
"\"reachable\":true}";
const char HUE_LIGHTS_STATUS_JSON2[] PROGMEM =
",\"type\":\"Extended color light\","
"\"name\":\"{j1\","
"\"name\":\"%s\","
"\"modelid\":\"LCT007\","
"\"uniqueid\":\"{j2\","
"\"uniqueid\":\"%s\","
"\"swversion\":\"5.50.1.19085\"}";
const char HUE_GROUP0_STATUS_JSON[] PROGMEM =
"{\"name\":\"Group 0\","
@ -173,8 +174,6 @@ const char HueConfigResponse_JSON[] PROGMEM =
"\"linkbutton\":false,"
"\"portalservices\":false"
"}";
const char HUE_LIGHT_RESPONSE_JSON[] PROGMEM =
"{\"success\":{\"/lights/{id/state/{cm\":{re}}";
const char HUE_ERROR_JSON[] PROGMEM =
"[{\"error\":{\"type\":901,\"address\":\"/\",\"description\":\"Internal Error\"}}]";
@ -182,7 +181,9 @@ const char HUE_ERROR_JSON[] PROGMEM =
String GetHueDeviceId(uint8_t id)
{
String deviceid = WiFi.macAddress() + F(":00:11-") + String(id);
String deviceid = WiFi.macAddress();
deviceid += F(":00:11-");
deviceid += String(id);
deviceid.toLowerCase();
return deviceid; // 5c:cf:7f:13:9f:3d:00:11-1
}
@ -318,49 +319,35 @@ void HueLightStatus1(uint8_t device, String *response)
// hue, sat, bri, prev_hue, prev_sat, prev_bri);
}
*response += FPSTR(HUE_LIGHTS_STATUS_JSON1);
response->replace("{state}", (power & (1 << (device-1))) ? "true" : "false");
const size_t buf_size = 256;
char * buf = (char*) malloc(buf_size); // temp buffer for strings, avoid stack
//String resp;
snprintf_P(buf, buf_size, PSTR("{\"on\":%s,"), (power & (1 << (device-1))) ? "true" : "false");
// Brightness for all devices with PWM
if ((1 == echo_gen) || (LST_SINGLE <= local_light_subtype)) { // force dimmer for 1st gen Echo
light_status += "\"bri\":";
light_status += String(bri);
light_status += ",";
snprintf_P(buf, buf_size, PSTR("%s\"bri\":%d,"), buf, bri);
}
if (LST_COLDWARM <= local_light_subtype) {
light_status += F("\"colormode\":\"");
light_status += (g_gotct ? "ct" : "hs");
light_status += "\",";
snprintf_P(buf, buf_size, PSTR("%s\"colormode\":\"%s\","), buf, g_gotct ? "ct" : "hs");
}
if (LST_RGB <= local_light_subtype) { // colors
if (prev_x_str[0] && prev_y_str[0]) {
light_status += "\"xy\":[";
light_status += prev_x_str;
light_status += ",";
light_status += prev_y_str;
light_status += "],";
snprintf_P(buf, buf_size, PSTR("%s\"xy\":[%s,%s],"), buf, prev_x_str, prev_y_str);
} else {
float x, y;
light_state.getXY(&x, &y);
light_status += "\"xy\":[";
light_status += String(x, 5);
light_status += ",";
light_status += String(y, 5);
light_status += "],";
light_state.getXY(&x, &y);
snprintf_P(buf, buf_size, PSTR("%s\"xy\":[%s,%s],"), buf, String(x, 5).c_str(), String(y, 5).c_str());
}
light_status += "\"hue\":";
light_status += String(hue);
light_status += ",";
light_status += "\"sat\":";
light_status += String(sat);
light_status += ",";
snprintf_P(buf, buf_size, PSTR("%s\"hue\":%d,\"sat\":%d,"), buf, hue, sat);
}
if (LST_COLDWARM == local_light_subtype || LST_RGBW <= local_light_subtype) { // white temp
light_status += "\"ct\":";
light_status += String(ct > 0 ? ct : 284); // if no ct, default to medium white
light_status += ",";
snprintf_P(buf, buf_size, PSTR("%s\"ct\":%d,"), buf, ct > 0 ? ct : 284);
}
response->replace("{light_status}", light_status);
snprintf_P(buf, buf_size, HUE_LIGHTS_STATUS_JSON1_SUFFIX, buf);
*response += buf;
free(buf);
}
// Check whether this device should be reported to Alexa or considered hidden.
@ -372,14 +359,16 @@ bool HueActive(uint8_t device) {
void HueLightStatus2(uint8_t device, String *response)
{
*response += FPSTR(HUE_LIGHTS_STATUS_JSON2);
if (device <= MAX_FRIENDLYNAMES) {
response->replace("{j1", SettingsText(SET_FRIENDLYNAME1 +device -1));
} else {
char fname[33];
strcpy(fname, SettingsText(SET_FRIENDLYNAME1 + MAX_FRIENDLYNAMES -1));
const size_t buf_size = 192;
char * buf = (char*) malloc(buf_size);
const size_t max_name_len = 32;
char fname[max_name_len + 1];
strlcpy(fname, SettingsText(device <= MAX_FRIENDLYNAMES ? SET_FRIENDLYNAME1 + device -1 : SET_FRIENDLYNAME1 + MAX_FRIENDLYNAMES -1), max_name_len + 1);
if (device > MAX_FRIENDLYNAMES) {
uint32_t fname_len = strlen(fname);
if (fname_len > 30) { fname_len = 30; }
if (fname_len > max_name_len - 2) { fname_len = max_name_len - 2; }
fname[fname_len++] = '-';
if (device - MAX_FRIENDLYNAMES < 10) {
fname[fname_len++] = '0' + device - MAX_FRIENDLYNAMES;
@ -387,35 +376,55 @@ void HueLightStatus2(uint8_t device, String *response)
fname[fname_len++] = 'A' + device - MAX_FRIENDLYNAMES - 10;
}
fname[fname_len] = 0x00;
response->replace("{j1", fname);
}
response->replace("{j2", GetHueDeviceId(device));
snprintf_P(buf, buf_size, HUE_LIGHTS_STATUS_JSON2, fname, GetHueDeviceId(device).c_str());
*response += buf;
free(buf);
}
// generate a unique lightId mixing local IP address and device number
// it is limited to 32 devices.
// last 24 bits of Mac address + 4 bits of local light + high bit for relays 16-31, relay 32 is mapped to 0
// Zigbee extension: bit 29 = 1, and last 16 bits = short address of Zigbee device
// #ifndef USE_ZIGBEE
uint32_t EncodeLightId(uint8_t relay_id)
// #else
// uint32_t EncodeLightId(uint8_t relay_id, uint16_t z_shortaddr = 0)
// #endif
{
uint8_t mac[6];
WiFi.macAddress(mac);
uint32_t id = 0;
uint32_t id = (mac[3] << 20) | (mac[4] << 12) | (mac[5] << 4);
if (relay_id >= 32) { // for Relay #32, we encode as 0
relay_id = 0;
}
if (relay_id > 15) {
id = (1 << 28);
id |= (1 << 28);
}
id |= (relay_id & 0xF);
// #ifdef USE_ZIGBEE
// if ((z_shortaddr) && (!relay_id)) {
// // fror Zigbee devices, we have relay_id == 0 and shortaddr != 0
// id = (1 << 29) | z_shortaddr;
// }
// #endif
id |= (mac[3] << 20) | (mac[4] << 12) | (mac[5] << 4) | (relay_id & 0xF);
return id;
}
// get hue_id and decode the relay_id
// 4 LSB decode to 1-15, if bit 28 is set, it encodes 16-31, if 0 then 32
uint32_t DecodeLightId(uint32_t hue_id) {
// Zigbee:
// If the Id encodes a Zigbee device (meaning bit 29 is set)
// it returns 0 and sets the 'shortaddr' to the device short address
// #ifndef USE_ZIGBEE
uint32_t DecodeLightId(uint32_t hue_id)
// #else
// uint32_t DecodeLightId(uint32_t hue_id, uint16_t * shortaddr = nullptr)
// #endif
{
uint8_t relay_id = hue_id & 0xF;
if (hue_id & (1 << 28)) { // check if bit 25 is set, if so we have
relay_id += 16;
@ -423,6 +432,13 @@ uint32_t DecodeLightId(uint32_t hue_id) {
if (0 == relay_id) { // special value 0 is actually relay #32
relay_id = 32;
}
// #ifdef USE_ZIGBEE
// if (hue_id & (1 << 29)) {
// // this is actually a Zigbee ID
// if (shortaddr) { *shortaddr = hue_id & 0xFFFF; }
// relay_id = 0;
// }
// #endif // USE_ZIGBEE
return relay_id;
}
@ -453,22 +469,14 @@ uint32_t findEchoGeneration(void) {
void HueGlobalConfig(String *path) {
String response;
uint8_t maxhue = (devices_present > MAX_HUE_DEVICES) ? MAX_HUE_DEVICES : devices_present;
path->remove(0,1); // cut leading / to get <id>
response = F("{\"lights\":{");
bool appending = false; // do we need to add a comma to append
for (uint32_t i = 1; i <= maxhue; i++) {
if (HueActive(i)) {
if (appending) { response += ","; }
response += "\"";
response += EncodeLightId(i);
response += F("\":{\"state\":");
HueLightStatus1(i, &response);
HueLightStatus2(i, &response);
appending = true;
}
}
CheckHue(&response, appending);
// #ifdef USE_ZIGBEE
// ZigbeeCheckHue(&response, appending);
// #endif // USE_ZIGBEE
response += F("},\"groups\":{},\"schedules\":{},\"config\":");
HueConfigResponse(&response);
response += "}";
@ -481,6 +489,212 @@ void HueAuthentication(String *path)
snprintf_P(response, sizeof(response), PSTR("[{\"success\":{\"username\":\"%s\"}}]"), GetHueUserId().c_str());
WSSend(200, CT_JSON, response);
AddLog_P2(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_HTTP D_HUE " Authentication Result (%s)"), response);
}
// refactored to remove code duplicates
void CheckHue(String * response, bool &appending) {
uint8_t maxhue = (devices_present > MAX_HUE_DEVICES) ? MAX_HUE_DEVICES : devices_present;
for (uint32_t i = 1; i <= maxhue; i++) {
if (HueActive(i)) {
if (appending) { *response += ","; }
*response += "\"";
*response += EncodeLightId(i);
*response += F("\":{\"state\":");
HueLightStatus1(i, response);
HueLightStatus2(i, response);
appending = true;
}
}
}
void HueLightsCommand(uint8_t device, uint32_t device_id, String &response) {
uint16_t tmp = 0;
uint16_t hue = 0;
uint8_t sat = 0;
uint8_t bri = 254;
uint16_t ct = 0;
bool on = false;
bool resp = false; // is the response non null (add comma between parameters)
bool change = false; // need to change a parameter to the light
uint8_t local_light_subtype = getLocalLightSubtype(device); // get the subtype for this device
const size_t buf_size = 100;
char * buf = (char*) malloc(buf_size);
if (WebServer->args()) {
response = "[";
StaticJsonBuffer<300> jsonBuffer;
JsonObject &hue_json = jsonBuffer.parseObject(WebServer->arg((WebServer->args())-1));
if (hue_json.containsKey("on")) {
on = hue_json["on"];
snprintf_P(buf, buf_size,
PSTR("{\"success\":{\"/lights/%d/state/on\":%s}}"),
device_id, on ? "true" : "false");
#ifdef USE_SHUTTER
if (ShutterState(device)) {
if (!change) {
bri = on ? 1.0f : 0.0f; // when bri is not part of this request then calculate it
change = true;
resp = true;
response += buf; // actually publish the state
}
} else {
#endif
switch(on)
{
case false : ExecuteCommandPower(device, POWER_OFF, SRC_HUE);
//response.replace("{re", "false");
break;
case true : ExecuteCommandPower(device, POWER_ON, SRC_HUE);
//response.replace("{re", "true");
break;
}
response += buf;
resp = true;
#ifdef USE_SHUTTER
}
#endif // USE_SHUTTER
}
if (light_type && (local_light_subtype >= LST_SINGLE)) {
if (!Settings.flag3.pwm_multi_channels) { // SetOption68 - Enable multi-channels PWM instead of Color PWM
light_state.getHSB(&hue, &sat, nullptr);
bri = light_state.getBri(); // get the combined bri for CT and RGB, not only the RGB one
ct = light_state.getCT();
uint8_t color_mode = light_state.getColorMode();
if (LCM_RGB == color_mode) { g_gotct = false; }
if (LCM_CT == color_mode) { g_gotct = true; }
// If LCM_BOTH == color_mode, leave g_gotct unchanged
} else { // treat each channel as simple dimmer
bri = LightGetBri(device);
}
}
prev_x_str[0] = prev_y_str[0] = 0; // reset xy string
if (hue_json.containsKey("bri")) { // Brightness is a scale from 1 (the minimum the light is capable of) to 254 (the maximum). Note: a brightness of 1 is not off.
bri = hue_json["bri"];
prev_bri = bri; // store command value
if (resp) { response += ","; }
snprintf_P(buf, buf_size,
PSTR("{\"success\":{\"/lights/%d/state/%s\":%d}}"),
device_id, "bri", bri);
response += buf;
if (LST_SINGLE <= Light.subtype) {
// extend bri value if set to max
if (254 <= bri) { bri = 255; }
change = true;
}
resp = true;
}
// handle xy before Hue/Sat
// If the request contains both XY and HS, we wan't to give priority to HS
if (hue_json.containsKey("xy")) {
float x = hue_json["xy"][0];
float y = hue_json["xy"][1];
const String &x_str = hue_json["xy"][0];
const String &y_str = hue_json["xy"][1];
x_str.toCharArray(prev_x_str, sizeof(prev_x_str));
y_str.toCharArray(prev_y_str, sizeof(prev_y_str));
uint8_t rr,gg,bb;
LightStateClass::XyToRgb(x, y, &rr, &gg, &bb);
LightStateClass::RgbToHsb(rr, gg, bb, &hue, &sat, nullptr);
prev_hue = changeUIntScale(hue, 0, 359, 0, 65535); // calculate back prev_hue
prev_sat = (sat > 254 ? 254 : sat);
//AddLog_P2(LOG_LEVEL_DEBUG_MORE, "XY RGB (%d %d %d) HS (%d %d)", rr,gg,bb,hue,sat);
if (resp) { response += ","; }
snprintf_P(buf, buf_size,
PSTR("{\"success\":{\"/lights/%d/state/xy\":[%s,%s]}}"),
device_id, prev_x_str, prev_y_str);
response += buf;
g_gotct = false;
resp = true;
change = true;
}
if (hue_json.containsKey("hue")) { // The hue value is a wrapping value between 0 and 65535. Both 0 and 65535 are red, 25500 is green and 46920 is blue.
hue = hue_json["hue"];
prev_hue = hue;
if (resp) { response += ","; }
snprintf_P(buf, buf_size,
PSTR("{\"success\":{\"/lights/%d/state/%s\":%d}}"),
device_id, "hue", hue);
response += buf;
if (LST_RGB <= Light.subtype) {
// change range from 0..65535 to 0..359
hue = changeUIntScale(hue, 0, 65535, 0, 359);
g_gotct = false;
change = true;
}
resp = true;
}
if (hue_json.containsKey("sat")) { // Saturation of the light. 254 is the most saturated (colored) and 0 is the least saturated (white).
sat = hue_json["sat"];
prev_sat = sat; // store command value
if (resp) { response += ","; }
snprintf_P(buf, buf_size,
PSTR("{\"success\":{\"/lights/%d/state/%s\":%d}}"),
device_id, "sat", sat);
response += buf;
if (LST_RGB <= Light.subtype) {
// extend sat value if set to max
if (254 <= sat) { sat = 255; }
g_gotct = false;
change = true;
}
resp = true;
}
if (hue_json.containsKey("ct")) { // Color temperature 153 (Cold) to 500 (Warm)
ct = hue_json["ct"];
prev_ct = ct; // store commande value
if (resp) { response += ","; }
snprintf_P(buf, buf_size,
PSTR("{\"success\":{\"/lights/%d/state/%s\":%d}}"),
device_id, "ct", ct);
response += buf;
if ((LST_COLDWARM == Light.subtype) || (LST_RGBW <= Light.subtype)) {
g_gotct = true;
change = true;
}
resp = true;
}
if (change) {
#ifdef USE_SHUTTER
if (ShutterState(device)) {
AddLog_P2(LOG_LEVEL_DEBUG, PSTR("Settings.shutter_invert: %d"), Settings.shutter_options[device-1] & 1);
ShutterSetPosition(device, bri * 100.0f );
} else
#endif
if (light_type && (local_light_subtype > LST_NONE)) { // not relay
if (!Settings.flag3.pwm_multi_channels) { // SetOption68 - Enable multi-channels PWM instead of Color PWM
if (g_gotct) {
light_controller.changeCTB(ct, bri);
} else {
light_controller.changeHSB(hue, sat, bri);
}
LightPreparePower();
} else { // SetOption68 On, each channel is a dimmer
LightSetBri(device, bri);
}
if (LST_COLDWARM <= local_light_subtype) {
MqttPublishPrefixTopic_P(RESULT_OR_STAT, PSTR(D_CMND_COLOR));
} else {
MqttPublishPrefixTopic_P(RESULT_OR_STAT, PSTR(D_CMND_DIMMER));
}
XdrvRulesProcess();
}
change = false;
}
response += "]";
if (2 == response.length()) {
response = FPSTR(HUE_ERROR_JSON);
}
}
else {
response = FPSTR(HUE_ERROR_JSON);
}
free(buf);
}
void HueLights(String *path)
@ -490,33 +704,18 @@ void HueLights(String *path)
*/
String response;
int code = 200;
uint16_t tmp = 0;
uint16_t hue = 0;
uint8_t sat = 0;
uint8_t bri = 254;
uint16_t ct = 0;
bool resp = false; // is the response non null (add comma between parameters)
bool on = false;
bool change = false; // need to change a parameter to the light
uint8_t device = 1;
uint8_t local_light_subtype = Light.subtype;
uint32_t device_id; // the raw device_id used by Hue emulation
uint8_t maxhue = (devices_present > MAX_HUE_DEVICES) ? MAX_HUE_DEVICES : devices_present;
path->remove(0,path->indexOf("/lights")); // Remove until /lights
if (path->endsWith("/lights")) { // Got /lights
response = "{";
bool appending = false;
for (uint32_t i = 1; i <= maxhue; i++) {
if (HueActive(i)) {
if (appending) { response += ","; }
response += "\"";
response += EncodeLightId(i);
response += F("\":{\"state\":");
HueLightStatus1(i, &response);
HueLightStatus2(i, &response);
appending = true;
}
}
CheckHue(&response, appending);
// #ifdef USE_ZIGBEE
// ZigbeeCheckHue(&response, appending);
// #endif // USE_ZIGBEE
#ifdef USE_SCRIPT_HUE
Script_Check_Hue(&response);
#endif
@ -525,206 +724,37 @@ void HueLights(String *path)
else if (path->endsWith("/state")) { // Got ID/state
path->remove(0,8); // Remove /lights/
path->remove(path->indexOf("/state")); // Remove /state
device = DecodeLightId(atoi(path->c_str()));
device_id = atoi(path->c_str());
device = DecodeLightId(device_id);
// #ifdef USE_ZIGBEE
// uint16_t shortaddr;
// device = DecodeLightId(device_id, &shortaddr);
// if (shortaddr) {
// return ZigbeeHandleHue(shortaddr, device_id, response);
// }
// #endif // USE_ZIGBEE
#ifdef USE_SCRIPT_HUE
if (device>devices_present) {
if (device > devices_present) {
return Script_Handle_Hue(path);
}
#endif
if ((device < 1) || (device > maxhue)) {
device = 1;
if ((device >= 1) || (device <= maxhue)) {
HueLightsCommand(device, device_id, response);
}
local_light_subtype = getLocalLightSubtype(device); // get the subtype for this device
if (WebServer->args()) {
response = "[";
StaticJsonBuffer<400> jsonBuffer;
JsonObject &hue_json = jsonBuffer.parseObject(WebServer->arg((WebServer->args())-1));
if (hue_json.containsKey("on")) {
response += FPSTR(HUE_LIGHT_RESPONSE_JSON);
response.replace("{id", String(EncodeLightId(device)));
response.replace("{cm", "on");
#ifdef USE_SHUTTER
if (ShutterState(device)) {
if (!change) {
on = hue_json["on"];
bri = on ? 1.0f : 0.0f; // when bri is not part of this request then calculate it
change = true;
}
response.replace("{re", on ? "true" : "false");
} else {
#endif
on = hue_json["on"];
switch(on)
{
case false : ExecuteCommandPower(device, POWER_OFF, SRC_HUE);
response.replace("{re", "false");
break;
case true : ExecuteCommandPower(device, POWER_ON, SRC_HUE);
response.replace("{re", "true");
break;
default : response.replace("{re", (power & (1 << (device-1))) ? "true" : "false");
break;
}
resp = true;
#ifdef USE_SHUTTER
}
#endif // USE_SHUTTER
}
if (light_type && (local_light_subtype >= LST_SINGLE)) {
if (!Settings.flag3.pwm_multi_channels) { // SetOption68 - Enable multi-channels PWM instead of Color PWM
light_state.getHSB(&hue, &sat, nullptr);
bri = light_state.getBri(); // get the combined bri for CT and RGB, not only the RGB one
ct = light_state.getCT();
uint8_t color_mode = light_state.getColorMode();
if (LCM_RGB == color_mode) { g_gotct = false; }
if (LCM_CT == color_mode) { g_gotct = true; }
// If LCM_BOTH == color_mode, leave g_gotct unchanged
} else { // treat each channel as simple dimmer
bri = LightGetBri(device);
}
}
prev_x_str[0] = prev_y_str[0] = 0; // reset xy string
if (hue_json.containsKey("bri")) { // Brightness is a scale from 1 (the minimum the light is capable of) to 254 (the maximum). Note: a brightness of 1 is not off.
tmp = hue_json["bri"];
prev_bri = bri = tmp; // store command value
// extend bri value if set to max
if (254 <= bri) { bri = 255; }
if (resp) { response += ","; }
response += FPSTR(HUE_LIGHT_RESPONSE_JSON);
response.replace("{id", String(device));
response.replace("{cm", "bri");
response.replace("{re", String(tmp));
if (LST_SINGLE <= Light.subtype) {
change = true;
}
resp = true;
}
// handle xy before Hue/Sat
// If the request contains both XY and HS, we wan't to give priority to HS
if (hue_json.containsKey("xy")) { // Saturation of the light. 254 is the most saturated (colored) and 0 is the least saturated (white).
float x, y;
x = hue_json["xy"][0];
y = hue_json["xy"][1];
const String &x_str = hue_json["xy"][0];
const String &y_str = hue_json["xy"][1];
x_str.toCharArray(prev_x_str, sizeof(prev_x_str));
y_str.toCharArray(prev_y_str, sizeof(prev_y_str));
//AddLog_P2(LOG_LEVEL_DEBUG_MORE, "XY (%s %s)", String(prev_x,5).c_str(), String(prev_y,5).c_str());
uint8_t rr,gg,bb;
LightStateClass::XyToRgb(x, y, &rr, &gg, &bb);
LightStateClass::RgbToHsb(rr, gg, bb, &hue, &sat, nullptr);
prev_hue = changeUIntScale(hue, 0, 359, 0, 65535); // calculate back prev_hue
prev_sat = (sat > 254 ? 254 : sat);
//AddLog_P2(LOG_LEVEL_DEBUG_MORE, "XY RGB (%d %d %d) HS (%d %d)", rr,gg,bb,hue,sat);
if (resp) { response += ","; }
response += FPSTR(HUE_LIGHT_RESPONSE_JSON);
response.replace("{id", String(device));
response.replace("{cm", "xy");
response.replace("{re", "[" + x_str + "," + y_str + "]");
g_gotct = false;
resp = true;
change = true;
}
if (hue_json.containsKey("hue")) { // The hue value is a wrapping value between 0 and 65535. Both 0 and 65535 are red, 25500 is green and 46920 is blue.
tmp = hue_json["hue"];
prev_hue = tmp;
// change range from 0..65535 to 0..359
hue = changeUIntScale(tmp, 0, 65535, 0, 359);
if (resp) { response += ","; }
response += FPSTR(HUE_LIGHT_RESPONSE_JSON);
response.replace("{id", String(device));
response.replace("{cm", "hue");
response.replace("{re", String(tmp));
if (LST_RGB <= Light.subtype) {
g_gotct = false;
change = true;
}
resp = true;
}
if (hue_json.containsKey("sat")) { // Saturation of the light. 254 is the most saturated (colored) and 0 is the least saturated (white).
tmp = hue_json["sat"];
prev_sat = sat = tmp; // store command value
// extend sat value if set to max
if (254 <= sat) { sat = 255; }
if (resp) { response += ","; }
response += FPSTR(HUE_LIGHT_RESPONSE_JSON);
response.replace("{id", String(device));
response.replace("{cm", "sat");
response.replace("{re", String(tmp));
if (LST_RGB <= Light.subtype) {
g_gotct = false;
change = true;
}
resp = true;
}
if (hue_json.containsKey("ct")) { // Color temperature 153 (Cold) to 500 (Warm)
ct = hue_json["ct"];
prev_ct = ct; // store commande value
if (resp) { response += ","; }
response += FPSTR(HUE_LIGHT_RESPONSE_JSON);
response.replace("{id", String(device));
response.replace("{cm", "ct");
response.replace("{re", String(ct));
if ((LST_COLDWARM == Light.subtype) || (LST_RGBW <= Light.subtype)) {
g_gotct = true;
change = true;
}
resp = true;
}
if (change) {
#ifdef USE_SHUTTER
if (ShutterState(device)) {
AddLog_P2(LOG_LEVEL_DEBUG, PSTR("Settings.shutter_invert: %d"), Settings.shutter_options[device-1] & 1);
ShutterSetPosition(device, bri * 100.0f );
} else
#endif
if (light_type && (local_light_subtype > LST_NONE)) { // not relay
if (!Settings.flag3.pwm_multi_channels) { // SetOption68 - Enable multi-channels PWM instead of Color PWM
if (g_gotct) {
light_controller.changeCTB(ct, bri);
} else {
light_controller.changeHSB(hue, sat, bri);
}
LightPreparePower();
} else { // SetOption68 On, each channel is a dimmer
LightSetBri(device, bri);
}
if (LST_COLDWARM <= local_light_subtype) {
MqttPublishPrefixTopic_P(RESULT_OR_STAT, PSTR(D_CMND_COLOR));
} else {
MqttPublishPrefixTopic_P(RESULT_OR_STAT, PSTR(D_CMND_DIMMER));
}
XdrvRulesProcess();
}
change = false;
}
response += "]";
if (2 == response.length()) {
response = FPSTR(HUE_ERROR_JSON);
}
}
else {
response = FPSTR(HUE_ERROR_JSON);
}
}
else if(path->indexOf("/lights/") >= 0) { // Got /lights/ID
AddLog_P2(LOG_LEVEL_DEBUG_MORE, "/lights path=%s", path->c_str());
path->remove(0,8); // Remove /lights/
device = DecodeLightId(atoi(path->c_str()));
device_id = atoi(path->c_str());
device = DecodeLightId(device_id);
#ifdef USE_SCRIPT_HUE
if (device>devices_present) {
Script_HueStatus(&response,device-devices_present-1);
if (device > devices_present) {
Script_HueStatus(&response, device-devices_present - 1);
goto exit;
}
}
#endif
if ((device < 1) || (device > maxhue)) {
@ -750,6 +780,7 @@ void HueGroups(String *path)
*/
String response = "{}";
uint8_t maxhue = (devices_present > MAX_HUE_DEVICES) ? MAX_HUE_DEVICES : devices_present;
//AddLog_P2(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_HTTP D_HUE " HueGroups (%s)"), path->c_str());
if (path->endsWith("/0")) {
response = FPSTR(HUE_GROUP0_STATUS_JSON);
@ -759,11 +790,16 @@ void HueGroups(String *path)
lights += EncodeLightId(i);
lights += "\"";
}
// #ifdef USE_ZIGBEE
// ZigbeeHueGroups(&response);
// #endif // USE_ZIGBEE
response.replace("{l1", lights);
HueLightStatus1(1, &response);
response += F("}");
}
AddLog_P2(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_HTTP D_HUE " HueGroups Result (%s)"), path->c_str());
WSSend(200, CT_JSON, response);
}
@ -791,17 +827,17 @@ void HandleHueApi(String *path)
AddLog_P2(LOG_LEVEL_DEBUG_MORE, PSTR(D_LOG_HTTP D_HUE_POST_ARGS " (%s)"), json.c_str()); // HTP: Hue POST args ({"on":false})
}
if (path->endsWith("/invalid/")) {} // Just ignore
if (path->endsWith(F("/invalid/"))) {} // Just ignore
else if (!apilen) HueAuthentication(path); // New HUE App setup
else if (path->endsWith("/")) HueAuthentication(path); // New HUE App setup
else if (path->endsWith("/config")) HueConfig(path);
else if (path->indexOf("/lights") >= 0) HueLights(path);
else if (path->indexOf("/groups") >= 0) HueGroups(path);
else if (path->endsWith("/schedules")) HueNotImplemented(path);
else if (path->endsWith("/sensors")) HueNotImplemented(path);
else if (path->endsWith("/scenes")) HueNotImplemented(path);
else if (path->endsWith("/rules")) HueNotImplemented(path);
else if (path->endsWith("/resourcelinks")) HueNotImplemented(path);
else if (path->endsWith(F("/"))) HueAuthentication(path); // New HUE App setup
else if (path->endsWith(F("/config"))) HueConfig(path);
else if (path->indexOf(F("/lights")) >= 0) HueLights(path);
else if (path->indexOf(F("/groups")) >= 0) HueGroups(path);
else if (path->endsWith(F("/schedules"))) HueNotImplemented(path);
else if (path->endsWith(F("/sensors"))) HueNotImplemented(path);
else if (path->endsWith(F("/scenes"))) HueNotImplemented(path);
else if (path->endsWith(F("/rules"))) HueNotImplemented(path);
else if (path->endsWith(F("/resourcelinks"))) HueNotImplemented(path);
else HueGlobalConfig(path);
}
@ -813,14 +849,14 @@ bool Xdrv20(uint8_t function)
{
bool result = false;
#ifdef USE_SCRIPT_HUE
#if defined(USE_SCRIPT_HUE) || defined(USE_ZIGBEE)
if ((EMUL_HUE == Settings.flag2.emulation)) {
#else
if (devices_present && (EMUL_HUE == Settings.flag2.emulation)) {
#endif
switch (function) {
case FUNC_WEB_ADD_HANDLER:
WebServer->on("/description.xml", HandleUpnpSetupHue);
WebServer->on(F("/description.xml"), HandleUpnpSetupHue);
break;
}
}

View File

@ -1,7 +1,7 @@
/*
xdrv_37_sonoff_d1.ino - sonoff D1 dimmer support for Tasmota
Copyright (C) 2020 Theo Arends and robbz23 (protocol analysis)
Copyright (C) 2020 Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@ -29,83 +29,43 @@
* 64 - Dimmer percentage (01 to 64 = 1 to 100%)
* FF FF FF FF FF FF FF FF - Not used
* 6C - CRC over bytes 2 to F (Addition)
*
* Based on Gravitate1:
* When I switch the light ON via the app, I get:
* AA 55 01 04 00 0A 01 64 FF FF FF FF FF FF FF FF 6C
*
* When I switch it OFF, I get:
* AA 55 01 04 00 0A 00 64 FF FF FF FF FF FF FF FF 6B
*
* When I set it to 1%, I get:
* AA 55 01 04 00 0A FF 01 FF FF FF FF FF FF FF FF 07
* AB 55 FD F7 FF FF F5 01 FF FF FF FF FF FF FF FF 09
*
* When I set it to 6%, I get:
* AA 55 01 04 00 0A FF 06 FF FF FF FF FF FF FF FF 0C
* AB 55 FD F7 FF FF F5 06 FF FF FF FF FF FF FF FF 0E
*
* When I set it to 100%, I get:
* AA 55 01 04 00 0A FF 64 FF FF FF FF FF FF FF FF 6A
* AB 55 FD F7 FF FF F5 64 FF FF FF FF FF FF FF FF 6C
*
* Based on robbz23:
* 00:17:59 CMD: Baudrate 9600
* 00:17:59 SER: Set to 8N1 9600 bit/s
* 00:17:59 RSL: stat/tasmota_D9E56D/RESULT = {"Baudrate":9600}
*
* 00:25:32 CMD: SerialSend5 aa 55 01 04 00 0a 01 22 ffffffffffffffff 29
* 00:25:32 RSL: stat/tasmota_D9E56D/RESULT = {"SerialSend":"Done"}
*
* 00:26:35 CMD: SerialSend5 aa 55 01 04 00 0a 01 22 ffffffffffffffff 2a
* 00:26:35 RSL: stat/tasmota_D9E56D/RESULT = {"SerialSend":"Done"}
* 00:26:35 RSL: tele/tasmota_D9E56D/RESULT = {"SerialReceived":AA 55 01 04 00 00 05}
*
* 00:28:58 CMD: SerialSend5 aa 55 01 04 00 0a 01 01 ffffffffffffffff 09
* 00:28:58 RSL: stat/tasmota_D9E56D/RESULT = {"SerialSend":"Done"}
* 00:28:58 RSL: tele/tasmota_D9E56D/RESULT = {"SerialReceived":AA 55 01 04 00 00 05}
*
* 00:29:12 RSL: tele/tasmota_D9E56D/RESULT = {"SerialReceived":AA 55 01 04 00 0A 01 3C FF FF FF FF FF FF FF FF 44}
* 00:29:43 RSL: tele/tasmota_D9E56D/RESULT = {"SerialReceived":AA 55 01 04 00 0A 01 01 FF FF FF FF FF FF FF FF 09}
* 00:29:53 RSL: tele/tasmota_D9E56D/RESULT = {"SerialReceived":AA 55 01 04 00 0A 01 64 FF FF FF FF FF FF FF FF 6C}
*
* 00:30:02 RSL: tele/tasmota_D9E56D/RESULT = {"SerialReceived":AA 55 01 04 00 0A FF 1E FF FF FF FF FF FF FF FF 24}
\*********************************************************************************************/
#define XDRV_37 37
struct SONOFFD1 {
uint8_t receive_flag = 0;
uint8_t dimmer;
uint8_t receive_len = 0;
uint8_t power = 255; // Not initialized
uint8_t dimmer = 255; // Not initialized
} SnfD1;
/********************************************************************************************/
void SonoffD1Received(void)
{
char svalue[32];
if (serial_in_byte_counter < 8) { return; } // Received ack from Rf chip (aa 55 01 04 00 00 05)
uint8_t action = serial_in_buffer[6] & 1;
if (action != SnfD1.power) {
SnfD1.power = action;
// AddLog_P2(LOG_LEVEL_DEBUG, PSTR("SD1: Remote power (%d, %d)"), SnfD1.power, SnfD1.dimmer);
ExecuteCommandPower(1, action, SRC_SWITCH);
}
uint8_t action = serial_in_buffer[6];
uint8_t dimmer = serial_in_buffer[7];
if (action < 2) {
// AA 55 01 04 00 0A 01 64 FF FF FF FF FF FF FF FF 6C - Power On, Dimmer 100%
// AA 55 01 04 00 0A 00 64 FF FF FF FF FF FF FF FF 6B - Power Off, Dimmer 100%
bool is_switch_change = (action != power);
if (is_switch_change) {
ExecuteCommandPower(1, action, SRC_SWITCH);
}
}
else if (0xFF == action) {
if (dimmer != SnfD1.dimmer) {
SnfD1.dimmer = dimmer;
bool is_brightness_change = SnfD1.dimmer != Settings.light_dimmer;
if (power && (SnfD1.dimmer > 0) && is_brightness_change) {
char scmnd[20];
snprintf_P(scmnd, sizeof(scmnd), PSTR(D_CMND_DIMMER " %d"), SnfD1.dimmer);
ExecuteCommand(scmnd, SRC_SWITCH);
}
// AddLog_P2(LOG_LEVEL_DEBUG, PSTR("SD1: Remote dimmer (%d, %d)"), SnfD1.power, SnfD1.dimmer);
char scmnd[20];
snprintf_P(scmnd, sizeof(scmnd), PSTR(D_CMND_DIMMER " %d"), SnfD1.dimmer);
ExecuteCommand(scmnd, SRC_SWITCH);
}
/*
// Send Acknowledge - Copy first 5 bytes, reset byte 6 and store crc in byte 7
// AA 55 01 04 00 00 05
serial_in_buffer[5] = 0; // Ack
@ -114,41 +74,38 @@ void SonoffD1Received(void)
if ((i > 1) && (i < 6)) { serial_in_buffer[6] += serial_in_buffer[i]; }
Serial.write(serial_in_buffer[i]);
}
*/
}
bool SonoffD1SerialInput(void)
{
uint8_t packet_length = 0;
if (0xAA == serial_in_byte) { // 0xAA - Start of text
serial_in_byte_counter = 0;
SnfD1.receive_flag = true;
SnfD1.receive_len = 7;
}
if (SnfD1.receive_flag) {
if (SnfD1.receive_len) {
serial_in_buffer[serial_in_byte_counter++] = serial_in_byte;
if (serial_in_byte_counter == 6) {
packet_length = 7 + serial_in_byte; // 8 or 17
if (6 == serial_in_byte_counter) {
SnfD1.receive_len += serial_in_byte; // 8 or 17
}
if (serial_in_byte_counter == packet_length) {
if (serial_in_byte_counter == SnfD1.receive_len) {
// Sonoff D1 codes
// AA 55 01 04 00 0A 01 64 FF FF FF FF FF FF FF FF 6C - Power On, Dimmer 100%
// AA 55 01 04 00 0A 00 64 FF FF FF FF FF FF FF FF 6B - Power Off, Dimmer 100%
// AA 55 01 04 00 0A FF 01 FF FF FF FF FF FF FF FF 07 - Power ignore, Dimmer 1%
// AB 55 FD F7 FF FF F5 01 FF FF FF FF FF FF FF FF 09 - Response 2
// AA 55 01 04 00 0A FF 06 FF FF FF FF FF FF FF FF 0C - Power ignore, Dimmer 6%
// AB 55 FD F7 FF FF F5 06 FF FF FF FF FF FF FF FF 0E - Response 2
// AA 55 01 04 00 0A FF 64 FF FF FF FF FF FF FF FF 6A - Power ignore, Dimmer 100%
// AB 55 FD F7 FF FF F5 64 FF FF FF FF FF FF FF FF 6C - Response 2
// aa 55 01 04 00 0a 01 01 ff ff ff ff ff ff ff ff 09 - Power On, Dimmer 1%
// aa 55 01 04 00 0a 01 28 ff ff ff ff ff ff ff ff 30 - Power On, Dimmer 40%
// aa 55 01 04 00 0a 01 3c ff ff ff ff ff ff ff ff 44 - Power On, Dimmer 60%
// aa 55 01 04 00 0a 01 64 ff ff ff ff ff ff ff ff 6c - Power On, Dimmer 100%
// aa 55 01 04 00 0a 00 64 ff ff ff ff ff ff ff ff 6b - Power Off (with last dimmer 100%)
// aa 55 01 04 00 0a 01 64 ff ff ff ff ff ff ff ff 6c - Power On (with last dimmer 100%)
AddLogSerial(LOG_LEVEL_DEBUG);
uint8_t crc = 0;
for (uint32_t i = 2; i < packet_length -1; i++) {
for (uint32_t i = 2; i < SnfD1.receive_len -1; i++) {
crc += serial_in_buffer[i];
}
if (crc == serial_in_buffer[packet_length -1]) {
if (crc == serial_in_buffer[SnfD1.receive_len -1]) {
SonoffD1Received();
SnfD1.receive_flag = false;
SnfD1.receive_len = 0;
return true;
}
}
@ -159,13 +116,13 @@ bool SonoffD1SerialInput(void)
/********************************************************************************************/
void SonoffD1Send(uint8_t lpower, uint8_t dimmer)
void SonoffD1Send()
{
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
uint8_t buffer[17] = { 0xAA,0x55,0x01,0x04,0x00,0x0A,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00 };
buffer[6] = lpower;
buffer[7] = dimmer;
buffer[6] = SnfD1.power;
buffer[7] = SnfD1.dimmer;
for (uint32_t i = 0; i < sizeof(buffer); i++) {
if ((i > 1) && (i < sizeof(buffer) -1)) { buffer[16] += buffer[i]; }
@ -175,17 +132,29 @@ void SonoffD1Send(uint8_t lpower, uint8_t dimmer)
bool SonoffD1SendPower(void)
{
SonoffD1Send(XdrvMailbox.index &1, 0xFF);
uint8_t action = XdrvMailbox.index &1;
if (action != SnfD1.power) {
SnfD1.power = action;
// AddLog_P2(LOG_LEVEL_DEBUG, PSTR("SD1: Tasmota power (%d, %d)"), SnfD1.power, SnfD1.dimmer);
SonoffD1Send();
}
return true;
}
bool SonoffD1SendDimmer(void)
{
uint8_t dimmer = changeUIntScale(((uint16_t *)XdrvMailbox.data)[0], 0, 255, 0, 100);
uint8_t dimmer = LightGetDimmer(1);
dimmer = (dimmer < Settings.dimmer_hw_min) ? Settings.dimmer_hw_min : dimmer;
dimmer = (dimmer > Settings.dimmer_hw_max) ? Settings.dimmer_hw_max : dimmer;
if (dimmer != SnfD1.dimmer) {
SnfD1.dimmer = dimmer;
SonoffD1Send(0xFF, dimmer);
// AddLog_P2(LOG_LEVEL_DEBUG, PSTR("SD1: Tasmota dimmer (%d, %d)"), SnfD1.power, SnfD1.dimmer);
SonoffD1Send();
}
return true;
}

View File

@ -89,6 +89,10 @@ uint8_t OneWireReset(void)
digitalWrite(ds18x20_pin, LOW);
delayMicroseconds(480);
pinMode(ds18x20_pin, Settings.flag3.ds18x20_internal_pullup ? INPUT_PULLUP : INPUT); // SetOption74 - Enable internal pullup for single DS18x20 sensor
delayMicroseconds(70);
uint8_t r = !digitalRead(ds18x20_pin);
delayMicroseconds(410);
return r;
} else {
digitalWrite(ds18x20_pin_out, HIGH);
do {
@ -100,11 +104,11 @@ uint8_t OneWireReset(void)
digitalWrite(ds18x20_pin_out, LOW);
delayMicroseconds(480);
digitalWrite(ds18x20_pin_out, HIGH);
delayMicroseconds(70);
uint8_t r = !digitalRead(ds18x20_pin);
delayMicroseconds(410);
return r;
}
delayMicroseconds(70);
uint8_t r = !digitalRead(ds18x20_pin);
delayMicroseconds(410);
return r;
}
void OneWireWriteBit(uint8_t v)
@ -126,49 +130,23 @@ void OneWireWriteBit(uint8_t v)
delayMicroseconds(delay_high[v]);
}
/*
// Fails for reasons unknown to me
uint8_t OneWireReadBit(void)
{
if (!ds18x20_dual_mode) {
pinMode(ds18x20_pin, OUTPUT);
digitalWrite(ds18x20_pin, LOW);
delayMicroseconds(3);
pinMode(ds18x20_pin, Settings.flag3.ds18x20_internal_pullup ? INPUT_PULLUP : INPUT); // SetOption74 - Enable internal pullup for single DS18x20 sensor
} else {
digitalWrite(ds18x20_pin_out, LOW);
delayMicroseconds(3);
digitalWrite(ds18x20_pin_out, HIGH);
}
delayMicroseconds(10);
uint8_t r = digitalRead(ds18x20_pin);
delayMicroseconds(53);
return r;
}
*/
// Works fine in contrast to above. Why?
void OneWireReadBit1(void)
uint8_t OneWire1ReadBit(void)
{
pinMode(ds18x20_pin, OUTPUT);
digitalWrite(ds18x20_pin, LOW);
delayMicroseconds(3);
pinMode(ds18x20_pin, Settings.flag3.ds18x20_internal_pullup ? INPUT_PULLUP : INPUT); // SetOption74 - Enable internal pullup for single DS18x20 sensor
delayMicroseconds(10);
uint8_t r = digitalRead(ds18x20_pin);
delayMicroseconds(53);
return r;
}
void OneWireReadBit2(void)
uint8_t OneWire2ReadBit(void)
{
digitalWrite(ds18x20_pin_out, LOW);
delayMicroseconds(3);
digitalWrite(ds18x20_pin_out, HIGH);
}
uint8_t OneWireReadBit(void)
{
if (!ds18x20_dual_mode) {
OneWireReadBit1();
} else {
OneWireReadBit2();
}
delayMicroseconds(10);
uint8_t r = digitalRead(ds18x20_pin);
delayMicroseconds(53);
@ -188,9 +166,17 @@ uint8_t OneWireRead(void)
{
uint8_t r = 0;
for (uint8_t bit_mask = 0x01; bit_mask; bit_mask <<= 1) {
if (OneWireReadBit()) {
r |= bit_mask;
if (!ds18x20_dual_mode) {
for (uint8_t bit_mask = 0x01; bit_mask; bit_mask <<= 1) {
if (OneWire1ReadBit()) {
r |= bit_mask;
}
}
} else {
for (uint8_t bit_mask = 0x01; bit_mask; bit_mask <<= 1) {
if (OneWire2ReadBit()) {
r |= bit_mask;
}
}
}
return r;
@ -234,9 +220,13 @@ uint8_t OneWireSearch(uint8_t *newAddr)
}
OneWireWrite(W1_SEARCH_ROM);
do {
id_bit = OneWireReadBit();
cmp_id_bit = OneWireReadBit();
if (!ds18x20_dual_mode) {
id_bit = OneWire1ReadBit();
cmp_id_bit = OneWire1ReadBit();
} else {
id_bit = OneWire2ReadBit();
cmp_id_bit = OneWire2ReadBit();
}
if ((id_bit == 1) && (cmp_id_bit == 1)) {
break;
} else {

View File

@ -1,307 +0,0 @@
/*
xsns_06_dht.ino - DHTxx, AM23xx and SI7021 temperature and humidity sensor support for Tasmota
Copyright (C) 2020 Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_DHT_OLD
/*********************************************************************************************\
* DHT11, AM2301 (DHT21, DHT22, AM2302, AM2321), SI7021 - Temperature and Humidy
*
* Reading temperature or humidity takes about 250 milliseconds!
* Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
* Source: Adafruit Industries https://github.com/adafruit/DHT-sensor-library
\*********************************************************************************************/
#define XSNS_06 6
#define DHT_MAX_SENSORS 4
#define DHT_MAX_RETRY 8
uint32_t dht_max_cycles;
uint8_t dht_data[5];
uint8_t dht_sensors = 0;
uint8_t dht_pin_out = 0; // Shelly GPIO00 output only
bool dht_active = true; // DHT configured
bool dht_dual_mode = false; // Single pin mode
struct DHTSTRUCT {
uint8_t pin;
uint8_t type;
char stype[12];
uint32_t lastreadtime;
uint8_t lastresult;
float t = NAN;
float h = NAN;
} Dht[DHT_MAX_SENSORS];
void DhtReadPrep(void)
{
for (uint32_t i = 0; i < dht_sensors; i++) {
if (!dht_dual_mode) {
digitalWrite(Dht[i].pin, HIGH);
} else {
digitalWrite(dht_pin_out, HIGH);
}
}
}
int32_t DhtExpectPulse(uint8_t sensor, bool level)
{
int32_t count = 0;
while (digitalRead(Dht[sensor].pin) == level) {
if (count++ >= (int32_t)dht_max_cycles) {
return -1; // Timeout
}
}
return count;
}
bool DhtRead(uint8_t sensor)
{
int32_t cycles[80];
uint8_t error = 0;
dht_data[0] = dht_data[1] = dht_data[2] = dht_data[3] = dht_data[4] = 0;
// digitalWrite(Dht[sensor].pin, HIGH);
// delay(250);
if (Dht[sensor].lastresult > DHT_MAX_RETRY) {
Dht[sensor].lastresult = 0;
if (!dht_dual_mode) {
digitalWrite(Dht[sensor].pin, HIGH); // Retry read prep
} else {
digitalWrite(dht_pin_out, HIGH);
}
delay(250);
}
if (!dht_dual_mode) {
pinMode(Dht[sensor].pin, OUTPUT);
digitalWrite(Dht[sensor].pin, LOW);
} else {
digitalWrite(dht_pin_out, LOW);
}
if (GPIO_SI7021 == Dht[sensor].type) {
delayMicroseconds(500);
} else {
delay(20);
}
noInterrupts();
if (!dht_dual_mode) {
digitalWrite(Dht[sensor].pin, HIGH);
delayMicroseconds(40);
pinMode(Dht[sensor].pin, INPUT_PULLUP);
} else {
digitalWrite(dht_pin_out, HIGH);
delayMicroseconds(40);
}
delayMicroseconds(10);
if (-1 == DhtExpectPulse(sensor, LOW)) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_START_SIGNAL_LOW " " D_PULSE));
error = 1;
}
else if (-1 == DhtExpectPulse(sensor, HIGH)) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_START_SIGNAL_HIGH " " D_PULSE));
error = 1;
}
else {
for (uint32_t i = 0; i < 80; i += 2) {
cycles[i] = DhtExpectPulse(sensor, LOW);
cycles[i+1] = DhtExpectPulse(sensor, HIGH);
}
}
interrupts();
if (error) { return false; }
for (uint32_t i = 0; i < 40; ++i) {
int32_t lowCycles = cycles[2*i];
int32_t highCycles = cycles[2*i+1];
if ((-1 == lowCycles) || (-1 == highCycles)) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_PULSE));
return false;
}
dht_data[i/8] <<= 1;
if (highCycles > lowCycles) {
dht_data[i / 8] |= 1;
}
}
uint8_t checksum = (dht_data[0] + dht_data[1] + dht_data[2] + dht_data[3]) & 0xFF;
if (dht_data[4] != checksum) {
char hex_char[15];
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_CHECKSUM_FAILURE " %s =? %02X"),
ToHex_P(dht_data, 5, hex_char, sizeof(hex_char), ' '), checksum);
return false;
}
return true;
}
void DhtReadTempHum(uint8_t sensor)
{
if ((NAN == Dht[sensor].h) || (Dht[sensor].lastresult > DHT_MAX_RETRY)) { // Reset after 8 misses
Dht[sensor].t = NAN;
Dht[sensor].h = NAN;
}
if (DhtRead(sensor)) {
switch (Dht[sensor].type) {
case GPIO_DHT11:
Dht[sensor].h = dht_data[0];
Dht[sensor].t = dht_data[2] + ((float)dht_data[3] * 0.1f); // Issue #3164
break;
case GPIO_DHT22:
case GPIO_SI7021:
Dht[sensor].h = ((dht_data[0] << 8) | dht_data[1]) * 0.1;
Dht[sensor].t = (((dht_data[2] & 0x7F) << 8 ) | dht_data[3]) * 0.1;
if (dht_data[2] & 0x80) {
Dht[sensor].t *= -1;
}
break;
}
Dht[sensor].t = ConvertTemp(Dht[sensor].t);
Dht[sensor].h = ConvertHumidity(Dht[sensor].h);
Dht[sensor].lastresult = 0;
} else {
Dht[sensor].lastresult++;
}
}
/********************************************************************************************/
bool DhtPinState()
{
if ((XdrvMailbox.index >= GPIO_DHT11) && (XdrvMailbox.index <= GPIO_SI7021)) {
if (dht_sensors < DHT_MAX_SENSORS) {
Dht[dht_sensors].pin = XdrvMailbox.payload;
Dht[dht_sensors].type = XdrvMailbox.index;
dht_sensors++;
XdrvMailbox.index = GPIO_DHT11;
} else {
XdrvMailbox.index = 0;
}
return true;
}
return false;
}
void DhtInit(void)
{
if (dht_sensors) {
dht_max_cycles = microsecondsToClockCycles(1000); // 1 millisecond timeout for reading pulses from DHT sensor.
if (pin[GPIO_DHT11_OUT] < 99) {
dht_pin_out = pin[GPIO_DHT11_OUT];
dht_dual_mode = true; // Dual pins mode as used by Shelly
dht_sensors = 1; // We only support one sensor in pseudo mode
pinMode(dht_pin_out, OUTPUT);
}
for (uint32_t i = 0; i < dht_sensors; i++) {
pinMode(Dht[i].pin, INPUT_PULLUP);
Dht[i].lastreadtime = 0;
Dht[i].lastresult = 0;
GetTextIndexed(Dht[i].stype, sizeof(Dht[i].stype), Dht[i].type, kSensorNames);
if (dht_sensors > 1) {
snprintf_P(Dht[i].stype, sizeof(Dht[i].stype), PSTR("%s%c%02d"), Dht[i].stype, IndexSeparator(), Dht[i].pin);
}
}
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_SENSORS_FOUND " %d"), dht_sensors);
} else {
dht_active = false;
}
}
void DhtEverySecond(void)
{
if (uptime &1) {
// <1mS
DhtReadPrep();
} else {
for (uint32_t i = 0; i < dht_sensors; i++) {
// DHT11 and AM2301 25mS per sensor, SI7021 5mS per sensor
DhtReadTempHum(i);
}
}
}
void DhtShow(bool json)
{
for (uint32_t i = 0; i < dht_sensors; i++) {
char temperature[33];
dtostrfd(Dht[i].t, Settings.flag2.temperature_resolution, temperature);
char humidity[33];
dtostrfd(Dht[i].h, Settings.flag2.humidity_resolution, humidity);
if (json) {
ResponseAppend_P(JSON_SNS_TEMPHUM, Dht[i].stype, temperature, humidity);
#ifdef USE_DOMOTICZ
if ((0 == tele_period) && (0 == i)) {
DomoticzTempHumSensor(temperature, humidity);
}
#endif // USE_DOMOTICZ
#ifdef USE_KNX
if ((0 == tele_period) && (0 == i)) {
KnxSensor(KNX_TEMPERATURE, Dht[i].t);
KnxSensor(KNX_HUMIDITY, Dht[i].h);
}
#endif // USE_KNX
#ifdef USE_WEBSERVER
} else {
WSContentSend_PD(HTTP_SNS_TEMP, Dht[i].stype, temperature, TempUnit());
WSContentSend_PD(HTTP_SNS_HUM, Dht[i].stype, humidity);
#endif // USE_WEBSERVER
}
}
}
/*********************************************************************************************\
* Interface
\*********************************************************************************************/
bool Xsns06(uint8_t function)
{
bool result = false;
if (dht_active) {
switch (function) {
case FUNC_EVERY_SECOND:
DhtEverySecond();
break;
case FUNC_JSON_APPEND:
DhtShow(1);
break;
#ifdef USE_WEBSERVER
case FUNC_WEB_SENSOR:
DhtShow(0);
break;
#endif // USE_WEBSERVER
case FUNC_INIT:
DhtInit();
break;
case FUNC_PIN_STATE:
result = DhtPinState();
break;
}
}
return result;
}
#endif // USE_DHT

View File

@ -1,358 +0,0 @@
/*
xsns_06_dht.ino - DHTxx, AM23xx and SI7021 temperature and humidity sensor support for Tasmota
Copyright (C) 2020 Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_DHT_V2
/*********************************************************************************************\
* DHT11, AM2301 (DHT21, DHT22, AM2302, AM2321), SI7021 - Temperature and Humidy
*
* Reading temperature or humidity takes about 250 milliseconds!
* Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
* Source: Adafruit Industries https://github.com/adafruit/DHT-sensor-library
\*********************************************************************************************/
#define XSNS_06 6
#define DHT_MAX_SENSORS 4
#define DHT_MAX_RETRY 8
uint32_t dht_max_cycles;
uint8_t dht_data[5];
uint8_t dht_sensors = 0;
uint8_t dht_pin_out = 0; // Shelly GPIO00 output only
bool dht_active = true; // DHT configured
bool dht_dual_mode = false; // Single pin mode
struct DHTSTRUCT {
uint8_t pin;
uint8_t type;
char stype[12];
uint32_t lastreadtime;
uint8_t lastresult;
float t = NAN;
float h = NAN;
} Dht[DHT_MAX_SENSORS];
void DhtReadPrep(void)
{
for (uint32_t i = 0; i < dht_sensors; i++) {
if (!dht_dual_mode) {
digitalWrite(Dht[i].pin, HIGH);
} else {
digitalWrite(dht_pin_out, HIGH);
}
}
}
int32_t DhtExpectPulse(uint8_t sensor, bool level)
{
int32_t count = 0;
while (digitalRead(Dht[sensor].pin) == level) {
if (count++ >= (int32_t)dht_max_cycles) {
return -1; // Timeout
}
}
return count;
}
bool DhtRead(uint8_t sensor)
{
int32_t cycles[80];
uint8_t error = 0;
dht_data[0] = dht_data[1] = dht_data[2] = dht_data[3] = dht_data[4] = 0;
if (Dht[sensor].lastresult > DHT_MAX_RETRY) {
Dht[sensor].lastresult = 0;
if (!dht_dual_mode) {
digitalWrite(Dht[sensor].pin, HIGH); // Retry read prep
} else {
digitalWrite(dht_pin_out, HIGH);
}
delay(250);
}
// Activate sensor using its protocol
noInterrupts();
if (!dht_dual_mode) {
pinMode(Dht[sensor].pin, OUTPUT);
digitalWrite(Dht[sensor].pin, LOW);
} else {
digitalWrite(dht_pin_out, LOW);
}
switch (Dht[sensor].type) {
case GPIO_SI7021: // Start protocol for iTead SI7021
/*
Protocol:
Reverse-engineered on https://github.com/arendst/Tasmota/issues/735#issuecomment-348718383:
1. MCU PULLS LOW data bus for at 500us to activate sensor
2. MCU PULLS UP data bus for ~40us to ask sensor for response
3. SENSOR starts sending data (LOW 40us then HIGH ~25us for "0" or ~75us for "1")
4. SENSOR sends "1" start bit as a response
5. SENSOR sends 16 bits (2 bytes) of a humidity with one decimal (i.e. 35.6% is sent as 356)
6. SENSOR sends 16 bits (2 bytes) of a temperature with one decimal (i.e. 23.4C is sent as 234)
7. SENSOR sends 8 bits (1 byte) checksum of 4 data bytes
*/
// digitalWrite(Dht[sensor].pin, LOW);
delayMicroseconds(500);
if (!dht_dual_mode) {
digitalWrite(Dht[sensor].pin, HIGH);
} else {
digitalWrite(dht_pin_out, HIGH);
}
delayMicroseconds(40);
break;
case GPIO_DHT22: // Start protocol for DHT21, DHT22, AM2301, AM2302, AM2321
/*
Protocol:
1. MCU PULLS LOW data bus for 1 to 10ms to activate sensor
2. MCU PULLS UP data bus for 20-40us to ask sensor for response
3. SENSOR PULLS LOW data bus for 80us as a response
4. SENSOR PULLS UP data bus for 80us for data sending preparation
5. SENSOR starts sending data (LOW 50us then HIGH 26-28us for "0" or 70us for "1")
*/
// digitalWrite(Dht[sensor].pin, LOW);
delayMicroseconds(1100); // data sheet says "at least 1ms to 10ms"
if (!dht_dual_mode) {
digitalWrite(Dht[sensor].pin, HIGH);
} else {
digitalWrite(dht_pin_out, HIGH);
}
delayMicroseconds(30); // data sheet says "20 to 40us"
break;
case GPIO_DHT11: // Start protocol for DHT11
/*
Protocol:
1. MCU PULLS LOW data bus for at least 18ms to activate sensor
2. MCU PULLS UP data bus for 20-40us to ask sensor for response
3. SENSOR PULLS LOW data bus for 80us as a response
4. SENSOR PULLS UP data bus for 80us for data sending preparation
5. SENSOR starts sending data (LOW 50us then HIGH 26-28us for "0" or 70 us for "1")
*/
default:
// digitalWrite(Dht[sensor].pin, LOW);
delay(20); // data sheet says at least 18ms, 20ms just to be safe
if (!dht_dual_mode) {
digitalWrite(Dht[sensor].pin, HIGH);
} else {
digitalWrite(dht_pin_out, HIGH);
}
delayMicroseconds(30); // data sheet says "20 to 40us"
break;
}
// Listen to the sensor response
pinMode(Dht[sensor].pin, INPUT_PULLUP);
if (-1 == DhtExpectPulse(sensor, LOW)) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_START_SIGNAL_LOW " " D_PULSE));
error = 1;
}
else if (-1 == DhtExpectPulse(sensor, HIGH)) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_START_SIGNAL_HIGH " " D_PULSE));
error = 1;
}
else {
for (uint32_t i = 0; i < 80; i += 2) {
cycles[i] = DhtExpectPulse(sensor, LOW);
cycles[i+1] = DhtExpectPulse(sensor, HIGH);
}
}
interrupts();
if (error) { return false; }
// Decode response
for (uint32_t i = 0; i < 40; ++i) {
int32_t lowCycles = cycles[2*i];
int32_t highCycles = cycles[2*i+1];
if ((-1 == lowCycles) || (-1 == highCycles)) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_PULSE));
return false;
}
dht_data[i/8] <<= 1;
if (highCycles > lowCycles) {
dht_data[i / 8] |= 1;
}
}
// Check response
uint8_t checksum = (dht_data[0] + dht_data[1] + dht_data[2] + dht_data[3]) & 0xFF;
if (dht_data[4] != checksum) {
char hex_char[15];
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_CHECKSUM_FAILURE " %s =? %02X"),
ToHex_P(dht_data, 5, hex_char, sizeof(hex_char), ' '), checksum);
return false;
}
return true;
}
void DhtReadTempHum(uint8_t sensor)
{
if ((NAN == Dht[sensor].h) || (Dht[sensor].lastresult > DHT_MAX_RETRY)) { // Reset after 8 misses
Dht[sensor].t = NAN;
Dht[sensor].h = NAN;
}
if (DhtRead(sensor)) {
switch (Dht[sensor].type) {
case GPIO_DHT11:
Dht[sensor].h = dht_data[0];
Dht[sensor].t = dht_data[2] + ((float)dht_data[3] * 0.1f); // Issue #3164
break;
case GPIO_DHT22:
case GPIO_SI7021:
Dht[sensor].h = ((dht_data[0] << 8) | dht_data[1]) * 0.1;
Dht[sensor].t = (((dht_data[2] & 0x7F) << 8 ) | dht_data[3]) * 0.1;
if (dht_data[2] & 0x80) {
Dht[sensor].t *= -1;
}
break;
}
Dht[sensor].t = ConvertTemp(Dht[sensor].t);
Dht[sensor].h = ConvertHumidity(Dht[sensor].h);
Dht[sensor].lastresult = 0;
} else {
Dht[sensor].lastresult++;
}
}
/********************************************************************************************/
bool DhtPinState()
{
if ((XdrvMailbox.index >= GPIO_DHT11) && (XdrvMailbox.index <= GPIO_SI7021)) {
if (dht_sensors < DHT_MAX_SENSORS) {
Dht[dht_sensors].pin = XdrvMailbox.payload;
Dht[dht_sensors].type = XdrvMailbox.index;
dht_sensors++;
XdrvMailbox.index = GPIO_DHT11;
} else {
XdrvMailbox.index = 0;
}
return true;
}
return false;
}
void DhtInit(void)
{
if (dht_sensors) {
dht_max_cycles = microsecondsToClockCycles(1000); // 1 millisecond timeout for reading pulses from DHT sensor.
if (pin[GPIO_DHT11_OUT] < 99) {
dht_pin_out = pin[GPIO_DHT11_OUT];
dht_dual_mode = true; // Dual pins mode as used by Shelly
dht_sensors = 1; // We only support one sensor in pseudo mode
pinMode(dht_pin_out, OUTPUT);
}
for (uint32_t i = 0; i < dht_sensors; i++) {
pinMode(Dht[i].pin, INPUT_PULLUP);
Dht[i].lastreadtime = 0;
Dht[i].lastresult = 0;
GetTextIndexed(Dht[i].stype, sizeof(Dht[i].stype), Dht[i].type, kSensorNames);
if (dht_sensors > 1) {
snprintf_P(Dht[i].stype, sizeof(Dht[i].stype), PSTR("%s%c%02d"), Dht[i].stype, IndexSeparator(), Dht[i].pin);
}
}
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT "(v2) " D_SENSORS_FOUND " %d"), dht_sensors);
} else {
dht_active = false;
}
}
void DhtEverySecond(void)
{
if (uptime &1) {
// <1mS
DhtReadPrep();
} else {
for (uint32_t i = 0; i < dht_sensors; i++) {
// DHT11 and AM2301 25mS per sensor, SI7021 5mS per sensor
DhtReadTempHum(i);
}
}
}
void DhtShow(bool json)
{
for (uint32_t i = 0; i < dht_sensors; i++) {
char temperature[33];
dtostrfd(Dht[i].t, Settings.flag2.temperature_resolution, temperature);
char humidity[33];
dtostrfd(Dht[i].h, Settings.flag2.humidity_resolution, humidity);
if (json) {
ResponseAppend_P(JSON_SNS_TEMPHUM, Dht[i].stype, temperature, humidity);
#ifdef USE_DOMOTICZ
if ((0 == tele_period) && (0 == i)) {
DomoticzTempHumSensor(temperature, humidity);
}
#endif // USE_DOMOTICZ
#ifdef USE_KNX
if ((0 == tele_period) && (0 == i)) {
KnxSensor(KNX_TEMPERATURE, Dht[i].t);
KnxSensor(KNX_HUMIDITY, Dht[i].h);
}
#endif // USE_KNX
#ifdef USE_WEBSERVER
} else {
WSContentSend_PD(HTTP_SNS_TEMP, Dht[i].stype, temperature, TempUnit());
WSContentSend_PD(HTTP_SNS_HUM, Dht[i].stype, humidity);
#endif // USE_WEBSERVER
}
}
}
/*********************************************************************************************\
* Interface
\*********************************************************************************************/
bool Xsns06(uint8_t function)
{
bool result = false;
if (dht_active) {
switch (function) {
case FUNC_EVERY_SECOND:
DhtEverySecond();
break;
case FUNC_JSON_APPEND:
DhtShow(1);
break;
#ifdef USE_WEBSERVER
case FUNC_WEB_SENSOR:
DhtShow(0);
break;
#endif // USE_WEBSERVER
case FUNC_INIT:
DhtInit();
break;
case FUNC_PIN_STATE:
result = DhtPinState();
break;
}
}
return result;
}
#endif // USE_DHT

View File

@ -1,304 +0,0 @@
/*
xsns_06_dht.ino - DHTxx, AM23xx and SI7021 temperature and humidity sensor support for Tasmota
Copyright (C) 2020 Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_DHT_V3
/*********************************************************************************************\
* DHT11, AM2301 (DHT21, DHT22, AM2302, AM2321), SI7021 - Temperature and Humidy
*
* Reading temperature or humidity takes about 250 milliseconds!
* Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
*
* This version is based on ESPEasy _P005_DHT.ino 20191201
\*********************************************************************************************/
#define XSNS_06 6
#define DHT_MAX_SENSORS 4
#define DHT_MAX_RETRY 8
uint8_t dht_data[5];
uint8_t dht_sensors = 0;
uint8_t dht_pin_out = 0; // Shelly GPIO00 output only
bool dht_active = true; // DHT configured
bool dht_dual_mode = false; // Single pin mode
struct DHTSTRUCT {
uint8_t pin;
uint8_t type;
char stype[12];
uint32_t lastreadtime;
uint8_t lastresult;
float t = NAN;
float h = NAN;
} Dht[DHT_MAX_SENSORS];
bool DhtExpectPulse(uint8_t sensor, int level)
{
unsigned long timeout = micros() + 100;
while (digitalRead(Dht[sensor].pin) != level) {
if (micros() > timeout) { return false; }
delayMicroseconds(1);
}
return true;
}
int DhtReadDat(uint8_t sensor)
{
uint8_t result = 0;
for (uint32_t i = 0; i < 8; i++) {
if (!DhtExpectPulse(sensor, HIGH)) { return -1; }
delayMicroseconds(35); // was 30
if (digitalRead(Dht[sensor].pin)) {
result |= (1 << (7 - i));
}
if (!DhtExpectPulse(sensor, LOW)) { return -1; }
}
return result;
}
bool DhtRead(uint8_t sensor)
{
dht_data[0] = dht_data[1] = dht_data[2] = dht_data[3] = dht_data[4] = 0;
if (!dht_dual_mode) {
pinMode(Dht[sensor].pin, OUTPUT);
digitalWrite(Dht[sensor].pin, LOW);
} else {
digitalWrite(dht_pin_out, LOW);
}
switch (Dht[sensor].type) {
case GPIO_DHT11:
delay(19); // minimum 18ms
break;
case GPIO_DHT22:
delay(2); // minimum 1ms
break;
case GPIO_SI7021:
delayMicroseconds(500);
break;
}
if (!dht_dual_mode) {
pinMode(Dht[sensor].pin, INPUT_PULLUP);
} else {
digitalWrite(dht_pin_out, HIGH);
}
switch (Dht[sensor].type) {
case GPIO_DHT11:
case GPIO_DHT22:
delayMicroseconds(50);
break;
case GPIO_SI7021:
// See: https://github.com/letscontrolit/ESPEasy/issues/1798
delayMicroseconds(20);
break;
}
noInterrupts();
if (!DhtExpectPulse(sensor, LOW)) {
interrupts();
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_START_SIGNAL_LOW " " D_PULSE));
return false;
}
if (!DhtExpectPulse(sensor, HIGH)) {
interrupts();
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_START_SIGNAL_HIGH " " D_PULSE));
return false;
}
if (!DhtExpectPulse(sensor, LOW)) {
interrupts();
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_START_SIGNAL_LOW " " D_PULSE));
return false;
}
int data = 0;
for (uint32_t i = 0; i < 5; i++) {
data = DhtReadDat(sensor);
if (-1 == data) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " " D_PULSE));
break;
}
dht_data[i] = data;
}
interrupts();
if (-1 == data) { return false; }
uint8_t checksum = (dht_data[0] + dht_data[1] + dht_data[2] + dht_data[3]) & 0xFF;
if (dht_data[4] != checksum) {
char hex_char[15];
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_CHECKSUM_FAILURE " %s =? %02X"),
ToHex_P(dht_data, 5, hex_char, sizeof(hex_char), ' '), checksum);
return false;
}
return true;
}
void DhtReadTempHum(uint8_t sensor)
{
if ((NAN == Dht[sensor].h) || (Dht[sensor].lastresult > DHT_MAX_RETRY)) { // Reset after 8 misses
Dht[sensor].t = NAN;
Dht[sensor].h = NAN;
}
if (DhtRead(sensor)) {
switch (Dht[sensor].type) {
case GPIO_DHT11:
Dht[sensor].h = dht_data[0];
Dht[sensor].t = dht_data[2] + ((float)dht_data[3] * 0.1f); // Issue #3164
break;
case GPIO_DHT22:
case GPIO_SI7021:
Dht[sensor].h = ((dht_data[0] << 8) | dht_data[1]) * 0.1;
Dht[sensor].t = (((dht_data[2] & 0x7F) << 8 ) | dht_data[3]) * 0.1;
if (dht_data[2] & 0x80) {
Dht[sensor].t *= -1;
}
break;
}
Dht[sensor].t = ConvertTemp(Dht[sensor].t);
Dht[sensor].h = ConvertHumidity(Dht[sensor].h);
Dht[sensor].lastresult = 0;
} else {
Dht[sensor].lastresult++;
}
}
/********************************************************************************************/
bool DhtPinState()
{
if ((XdrvMailbox.index >= GPIO_DHT11) && (XdrvMailbox.index <= GPIO_SI7021)) {
if (dht_sensors < DHT_MAX_SENSORS) {
Dht[dht_sensors].pin = XdrvMailbox.payload;
Dht[dht_sensors].type = XdrvMailbox.index;
dht_sensors++;
XdrvMailbox.index = GPIO_DHT11;
} else {
XdrvMailbox.index = 0;
}
return true;
}
return false;
}
void DhtInit(void)
{
if (dht_sensors) {
if (pin[GPIO_DHT11_OUT] < 99) {
dht_pin_out = pin[GPIO_DHT11_OUT];
dht_dual_mode = true; // Dual pins mode as used by Shelly
dht_sensors = 1; // We only support one sensor in pseudo mode
pinMode(dht_pin_out, OUTPUT);
}
for (uint32_t i = 0; i < dht_sensors; i++) {
pinMode(Dht[i].pin, INPUT_PULLUP);
Dht[i].lastreadtime = 0;
Dht[i].lastresult = 0;
GetTextIndexed(Dht[i].stype, sizeof(Dht[i].stype), Dht[i].type, kSensorNames);
if (dht_sensors > 1) {
snprintf_P(Dht[i].stype, sizeof(Dht[i].stype), PSTR("%s%c%02d"), Dht[i].stype, IndexSeparator(), Dht[i].pin);
}
}
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT "(v3) " D_SENSORS_FOUND " %d"), dht_sensors);
} else {
dht_active = false;
}
}
void DhtEverySecond(void)
{
if (uptime &1) {
// <1mS
// DhtReadPrep();
} else {
for (uint32_t i = 0; i < dht_sensors; i++) {
// DHT11 and AM2301 25mS per sensor, SI7021 5mS per sensor
DhtReadTempHum(i);
}
}
}
void DhtShow(bool json)
{
for (uint32_t i = 0; i < dht_sensors; i++) {
char temperature[33];
dtostrfd(Dht[i].t, Settings.flag2.temperature_resolution, temperature);
char humidity[33];
dtostrfd(Dht[i].h, Settings.flag2.humidity_resolution, humidity);
if (json) {
ResponseAppend_P(JSON_SNS_TEMPHUM, Dht[i].stype, temperature, humidity);
#ifdef USE_DOMOTICZ
if ((0 == tele_period) && (0 == i)) {
DomoticzTempHumSensor(temperature, humidity);
}
#endif // USE_DOMOTICZ
#ifdef USE_KNX
if ((0 == tele_period) && (0 == i)) {
KnxSensor(KNX_TEMPERATURE, Dht[i].t);
KnxSensor(KNX_HUMIDITY, Dht[i].h);
}
#endif // USE_KNX
#ifdef USE_WEBSERVER
} else {
WSContentSend_PD(HTTP_SNS_TEMP, Dht[i].stype, temperature, TempUnit());
WSContentSend_PD(HTTP_SNS_HUM, Dht[i].stype, humidity);
#endif // USE_WEBSERVER
}
}
}
/*********************************************************************************************\
* Interface
\*********************************************************************************************/
bool Xsns06(uint8_t function)
{
bool result = false;
if (dht_active) {
switch (function) {
case FUNC_EVERY_SECOND:
DhtEverySecond();
break;
case FUNC_JSON_APPEND:
DhtShow(1);
break;
#ifdef USE_WEBSERVER
case FUNC_WEB_SENSOR:
DhtShow(0);
break;
#endif // USE_WEBSERVER
case FUNC_INIT:
DhtInit();
break;
case FUNC_PIN_STATE:
result = DhtPinState();
break;
}
}
return result;
}
#endif // USE_DHT

View File

@ -1,293 +0,0 @@
/*
xsns_06_dht.ino - DHTxx, AM23xx and SI7021 temperature and humidity sensor support for Tasmota
Copyright (C) 2020 Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_DHT_V4
/*********************************************************************************************\
* DHT11, AM2301 (DHT21, DHT22, AM2302, AM2321), SI7021 - Temperature and Humidy
*
* Reading temperature or humidity takes about 250 milliseconds!
* Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
*
* This version is based on ESPEasy _P005_DHT.ino 20191201 and stripped
\*********************************************************************************************/
#define XSNS_06 6
#define DHT_MAX_SENSORS 4
#define DHT_MAX_RETRY 8
uint8_t dht_data[5];
uint8_t dht_sensors = 0;
uint8_t dht_pin_out = 0; // Shelly GPIO00 output only
bool dht_active = true; // DHT configured
bool dht_dual_mode = false; // Single pin mode
struct DHTSTRUCT {
uint8_t pin;
uint8_t type;
char stype[12];
uint32_t lastreadtime;
uint8_t lastresult;
float t = NAN;
float h = NAN;
} Dht[DHT_MAX_SENSORS];
bool DhtExpectPulse(uint32_t sensor, uint32_t level)
{
unsigned long timeout = micros() + 100;
while (digitalRead(Dht[sensor].pin) != level) {
if (micros() > timeout) { return false; }
delayMicroseconds(1);
}
return true;
}
bool DhtRead(uint32_t sensor)
{
dht_data[0] = dht_data[1] = dht_data[2] = dht_data[3] = dht_data[4] = 0;
if (!dht_dual_mode) {
pinMode(Dht[sensor].pin, OUTPUT);
digitalWrite(Dht[sensor].pin, LOW);
} else {
digitalWrite(dht_pin_out, LOW);
}
switch (Dht[sensor].type) {
case GPIO_DHT11: // DHT11
delay(19); // minimum 18ms
break;
case GPIO_DHT22: // DHT21, DHT22, AM2301, AM2302, AM2321
delay(2); // minimum 1ms
break;
case GPIO_SI7021: // iTead SI7021
delayMicroseconds(500);
break;
}
if (!dht_dual_mode) {
pinMode(Dht[sensor].pin, INPUT_PULLUP);
} else {
digitalWrite(dht_pin_out, HIGH);
}
switch (Dht[sensor].type) {
case GPIO_DHT11: // DHT11
case GPIO_DHT22: // DHT21, DHT22, AM2301, AM2302, AM2321
delayMicroseconds(50);
break;
case GPIO_SI7021: // iTead SI7021
delayMicroseconds(20); // See: https://github.com/letscontrolit/ESPEasy/issues/1798
break;
}
uint32_t level = 9;
noInterrupts();
for (uint32_t i = 0; i < 3; i++) {
level = i &1;
if (!DhtExpectPulse(sensor, level)) { break; } // Expect LOW, HIGH, LOW
level = 9;
}
if (9 == level) {
int data = 0;
for (uint32_t i = 0; i < 5; i++) {
data = 0;
for (uint32_t j = 0; j < 8; j++) {
level = 1;
if (!DhtExpectPulse(sensor, level)) { break; } // Expect HIGH
delayMicroseconds(35); // Was 30
if (digitalRead(Dht[sensor].pin)) {
data |= (1 << (7 - j));
}
level = 0;
if (!DhtExpectPulse(sensor, level)) { break; } // Expect LOW
level = 9;
}
if (level < 2) { break; }
dht_data[i] = data;
}
}
interrupts();
if (level < 2) {
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_TIMEOUT_WAITING_FOR " %s " D_PULSE), (0 == level) ? D_START_SIGNAL_LOW : D_START_SIGNAL_HIGH);
return false;
}
uint8_t checksum = (dht_data[0] + dht_data[1] + dht_data[2] + dht_data[3]) & 0xFF;
if (dht_data[4] != checksum) {
char hex_char[15];
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT D_CHECKSUM_FAILURE " %s =? %02X"),
ToHex_P(dht_data, 5, hex_char, sizeof(hex_char), ' '), checksum);
return false;
}
return true;
}
void DhtReadTempHum(uint32_t sensor)
{
if ((NAN == Dht[sensor].h) || (Dht[sensor].lastresult > DHT_MAX_RETRY)) { // Reset after 8 misses
Dht[sensor].t = NAN;
Dht[sensor].h = NAN;
}
if (DhtRead(sensor)) {
switch (Dht[sensor].type) {
case GPIO_DHT11:
Dht[sensor].h = dht_data[0];
Dht[sensor].t = dht_data[2] + ((float)dht_data[3] * 0.1f); // Issue #3164
break;
case GPIO_DHT22:
case GPIO_SI7021:
Dht[sensor].h = ((dht_data[0] << 8) | dht_data[1]) * 0.1;
Dht[sensor].t = (((dht_data[2] & 0x7F) << 8 ) | dht_data[3]) * 0.1;
if (dht_data[2] & 0x80) {
Dht[sensor].t *= -1;
}
break;
}
Dht[sensor].t = ConvertTemp(Dht[sensor].t);
if (Dht[sensor].h > 100) { Dht[sensor].h = 100.0; }
if (Dht[sensor].h < 0) { Dht[sensor].h = 0.0; }
Dht[sensor].h = ConvertHumidity(Dht[sensor].h);
Dht[sensor].lastresult = 0;
} else {
Dht[sensor].lastresult++;
}
}
/********************************************************************************************/
bool DhtPinState()
{
if ((XdrvMailbox.index >= GPIO_DHT11) && (XdrvMailbox.index <= GPIO_SI7021)) {
if (dht_sensors < DHT_MAX_SENSORS) {
Dht[dht_sensors].pin = XdrvMailbox.payload;
Dht[dht_sensors].type = XdrvMailbox.index;
dht_sensors++;
XdrvMailbox.index = GPIO_DHT11;
} else {
XdrvMailbox.index = 0;
}
return true;
}
return false;
}
void DhtInit(void)
{
if (dht_sensors) {
if (pin[GPIO_DHT11_OUT] < 99) {
dht_pin_out = pin[GPIO_DHT11_OUT];
dht_dual_mode = true; // Dual pins mode as used by Shelly
dht_sensors = 1; // We only support one sensor in pseudo mode
pinMode(dht_pin_out, OUTPUT);
}
for (uint32_t i = 0; i < dht_sensors; i++) {
pinMode(Dht[i].pin, INPUT_PULLUP);
Dht[i].lastreadtime = 0;
Dht[i].lastresult = 0;
GetTextIndexed(Dht[i].stype, sizeof(Dht[i].stype), Dht[i].type, kSensorNames);
if (dht_sensors > 1) {
snprintf_P(Dht[i].stype, sizeof(Dht[i].stype), PSTR("%s%c%02d"), Dht[i].stype, IndexSeparator(), Dht[i].pin);
}
}
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_DHT "(v4) " D_SENSORS_FOUND " %d"), dht_sensors);
} else {
dht_active = false;
}
}
void DhtEverySecond(void)
{
if (uptime &1) {
} else {
for (uint32_t i = 0; i < dht_sensors; i++) {
// DHT11 and AM2301 25mS per sensor, SI7021 5mS per sensor
DhtReadTempHum(i);
}
}
}
void DhtShow(bool json)
{
for (uint32_t i = 0; i < dht_sensors; i++) {
char temperature[33];
dtostrfd(Dht[i].t, Settings.flag2.temperature_resolution, temperature);
char humidity[33];
dtostrfd(Dht[i].h, Settings.flag2.humidity_resolution, humidity);
if (json) {
ResponseAppend_P(JSON_SNS_TEMPHUM, Dht[i].stype, temperature, humidity);
#ifdef USE_DOMOTICZ
if ((0 == tele_period) && (0 == i)) {
DomoticzTempHumSensor(temperature, humidity);
}
#endif // USE_DOMOTICZ
#ifdef USE_KNX
if ((0 == tele_period) && (0 == i)) {
KnxSensor(KNX_TEMPERATURE, Dht[i].t);
KnxSensor(KNX_HUMIDITY, Dht[i].h);
}
#endif // USE_KNX
#ifdef USE_WEBSERVER
} else {
WSContentSend_PD(HTTP_SNS_TEMP, Dht[i].stype, temperature, TempUnit());
WSContentSend_PD(HTTP_SNS_HUM, Dht[i].stype, humidity);
#endif // USE_WEBSERVER
}
}
}
/*********************************************************************************************\
* Interface
\*********************************************************************************************/
bool Xsns06(uint8_t function)
{
bool result = false;
if (dht_active) {
switch (function) {
case FUNC_EVERY_SECOND:
DhtEverySecond();
break;
case FUNC_JSON_APPEND:
DhtShow(1);
break;
#ifdef USE_WEBSERVER
case FUNC_WEB_SENSOR:
DhtShow(0);
break;
#endif // USE_WEBSERVER
case FUNC_INIT:
DhtInit();
break;
case FUNC_PIN_STATE:
result = DhtPinState();
break;
}
}
return result;
}
#endif // USE_DHT

View File

@ -15,6 +15,7 @@
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_I2C
@ -23,6 +24,15 @@
* AHT10/15 - Temperature and Humidity
*
* I2C Address: 0x38
*
* Attention: this Sensor is incompatible with other I2C devices on I2C bus.
*
* The Datasheet write:
* "Only a single AHT10 can be connected to the I2C bus and no other I2C
* devices can be connected".
*
* after lot of search and tests, now is confirmed that works only reliable with one sensor
* on I2C Bus
\*********************************************************************************************/
#define XSNS_63 63
@ -31,7 +41,6 @@
#define AHT10_ADDR 0x38
uint8_t eSensorCalibrateCmd[3] = {0xE1, 0x08, 0x00};
uint8_t eSensorNormalCmd[3] = {0xA8, 0x00, 0x00};
uint8_t eSensorMeasureCmd[3] = {0xAC, 0x33, 0x00};
uint8_t eSensorResetCmd = 0xBA;
@ -52,7 +61,7 @@ bool AHT10Read(void)
Wire.beginTransmission(AHT10_ADDR);
Wire.write(eSensorMeasureCmd, 3);
Wire.endTransmission();
delay(100);
delay(80);
Wire.requestFrom(AHT10_ADDR, 6);
for (uint32_t i = 0; Wire.available() > 0; i++) {
@ -80,10 +89,10 @@ bool AHT10Init(void)
{
Wire.begin(AHT10_ADDR);
Wire.beginTransmission(AHT10_ADDR);
Wire.write(eSensorCalibrateCmd, 3);
Wire.write(eSensorCalibrateCmd, 3); // init with internal temp coef.
Wire.endTransmission();
delay(500); // ?!?! too long
delay(40); // after tests, its ok
return (0x08 == (AHT10ReadStatus() & 0x68));
}