nodemcu-firmware/app/modules/somfy.c

248 lines
8.7 KiB
C
Raw Normal View History

Next 1.5.4.1 master drop (#1627) * add u8g.fb_rle display * move comm drivers to u8g_glue.c * disable fb_rle per default * implement file.size for spiffs (#1516) Another bug squashed! * Fix start-up race between UART & start_lua. (#1522) Input during startup (especially while doing initial filesystem format) ran the risk of filling up the task queue, preventing the start_lua task from being queued, and hence NodeMCU would not start up that time. * Reimplemented esp_init_data_default. To work around the pesky "rf_cal[0] !=0x05" hang when booting on a chip which doesn't have esp_init_data written to it. It is no longer possible to do the writing of the esp_init_data_default from within nodemcu_init(), as the SDK now hangs long before it gets there. As such, I've had to reimplement this in our user_start_trampoline and get it all done before the SDK has a chance to look for the init data. It's unfortunate that we have to spend IRAM on this, but I see no better alternative at this point. * Replace hardcoded init data with generated data from SDK The esp_init_data_default.bin is now extracted from the SDK (and its patch file, if present), and the contents are automatically embedded into user_main.o. * Rework flashing instructions Clarifies issues around SDK init data and hopefully clears up some confusion, when paired with the esp_init_data_default changes in NodeMCU. * Fix typo * Fixes the gpio.serout problem from #1534 (#1535) * Fix some issues in gpio.serout * Minor cleanup * fix dereferencing NULL pointer in vfs_errno() (#1539) * add map ids for flash sizes 32m-c2, 64m, 128m in user_rf_cal_sector_set() (#1529) * Somfy/TELIS driver (#1521) * Reduced LUAL_BUFFERSIZE to 256. Should free up some stack (#1530) * avoid task queue overrun for serial input (#1540) Thank you. * Increase irom0_0_seg size for PR build * Improve reliability of FS detection. (#1528) * Version to make filesystem detection more reliable * Improve bad fs detection * Version of printf that doesn't suffer from buffer overflows (#1564) * Small improvement to http client (#1558) * Remove luaL_buffer from file_g_read() (#1541) * remove luaL_buffer from file_g_read() - avoid memory leak when function gets terminated by lua_error - skip scanning for end_char when reading until EOF * attempt to free memory in any case * Change HTTP failures from debug to error messages (#1568) * Change HTTP failures from debug to error messages * Add tag to HTTP error messages * Create macro for error msg and improve dbg msg * Add ssd1306_128x32 for U8G (#1571) * Update CONTRIBUTING.md * Add support to mix ws2812.buffer objects. (#1575) * Add load/dump/mix/power operations on the buffer object * Calculate the pixel value in mix and then clip to the range. * Fixed the two wrong userdata types * Added a couple more useful methods * Add support for shifting a piece of the buffer. * Fix a minor bug with offset shifts * Update to the wifi module (#1497) * Removed inline documentation for several functions and update comments Since documentation is now part of the repository, the inline documentation just adds to the already huge wifi.c * Wifi module: add new functionality, update documentation Functions Added: wifi.getdefaultmode(): returns default wifi opmode wifi.sta.apchange(): select alternate cached AP wifi.sta.apinfo(): get cached AP list wifi.sta.aplimit(): set cached AP limit wifi.sta.getapindex(): get index of currently configured AP wifi.sta.getdefaultconfig(): get default station configuration wifi.ap.getdefaultconfig(): get default AP configuration functions modified: wifi.setmode: saving mode to flash is now optional wifi.sta.config: now accepts table as an argument and save config to flash is now optional wifi.sta.getconfig: added option to return table wifi.ap.config: save config to flash is now optional wifi.ap.getconfig: added option to return table Documentation changes: - Modified documentation to reflect above changes - Removed unnecessary inline documentation from `wifi.c` - Updated documentation for `wifi.sta.disconnect`to address issue #1480 - Fixed inaccurate documentation for function `wifi.sleeptype` - Added more details to `wifi.nullmodesleep()` * Move function `wifi.sleeptype()` to `wifi.sta.sleeptype()` * Fixed problem where wifi.x.getconfig() returned invalid strings when ssid or password were set to maximum length. * fix error in documentation for `wifi.sta.getapindex` * Renamed some wifi functions wifi.sta.apinfo -> getapinfo wifi.sta.aplimit -> setaplimit wifi.sta.apchange -> changeap also organized the wifi_station_map array * Make the MQTT PING functionality work better. (#1557) Deal with flow control stopped case * Implement object model for files (#1532) * Eus channelfix (#1583) Squashed commits included: Bug fixes and final implementation - Added Content-Length: 0 to all headers - Endpoint name checks not using trailing space so cache-busting techniques can be used (i.e., append a nonce to the URL) - Track when connecting so APList scan doesn't take place during (which changes the channel) - More debugging output added to assist in tracking down some issues Added /status.json endpoint for phone apps/XHR to get JSON response Station Status caching for wifi channel workaround + AJAX/CORS - During checkstation poll, cache the last station status - Shut down the station if status = 2,3,4 and channel is different than SoftAP - Add Access-Control-Allow-Origin: * to endpoint responses used by a service - Add a /setwifi GET endpoint for phone apps/XHR to use (same parameters as /update endpoint). Returns a JSON response containing chip id and status code. - Add handler for OPTIONS verb (needed for CORS support) Wi-Fi Channel Issue Workaround - Do a site survey upon startup, set SoftAP channel to the strongest rssi's channel - Compare successful station connect channel to SoftAP's. If different, then defer the Lua success callback to the end. Shut down Station and start the SoftAP back up with original channel. - After the 10 second shutdown timer fires, check to see if success callback was already called. If not, then call it while starting the Station back up. HTTP Response and DNS enhancements - If DNS's UDP buffer fills up, keep going as non-fatal. It's UDP and not guaranteed anyways. I've seen this occur when connecting a PC to the SoftAP and every open program tries to phone home at the same time, overwhelming the EUS DNS server. - Support for detecting/handling pre-gzipped `enduser_setup.html` (and `http_html_backup`) payload. Nice for keeping the size of the `state->http_payload_data` as small as possible (also makes minimization not as critical) - Corrected misuse of HTTP 401 response status (changed one occurrence to 400/Bad Request, and changed another to 405/Method Not Allowed) * Normalized formatting (tabs-to-spaces) * Added documentation * Corrected misuse of strlen for binary (gzip) data. * Added NULL check after malloc * fix vfs_lseek() result checking in enduser_setup and clarify SPIFFS_lseek() return value (#1570) * Fix link * Overhaul flashing docs once again (#1587) * Add chapter about determine flash size plus small fixes * Rewrite esptool.py chapter, move flash size chapter to end * i2c - allow slave stretching SCL (just loop and check) (#1589) * Add note on dev board usage of SPI bus 0 (#1591) * Turn SPI busses note to admonition note * support for custom websocket headers (#1573) Looks good to me. Thank you. Also: - allow for '\0's in received messages * add client:config for setting websocket headers Also: - headers are case-insensitive now * fix docs * fix typo * remove unnecessary luaL_argcheck calls * replace os_sprintf with simple string copy * Handle error condition in file.read() (#1599) * handle error condition in file.read() * simplify loop initialization * Fix macro as suggested in #1548 * Extract and hoist net receive callbacks This is done to avoid the accidental upval binding * Fix typo at rtctime.md rtctime.dsleep -> rtctime.dsleep_aligned
2016-12-01 21:37:24 +01:00
// ***************************************************************************
// Somfy module for ESP8266 with NodeMCU
//
// Written by Lukas Voborsky, @voborsky
// based on https://github.com/Nickduino/Somfy_Remote
// Somfy protocol description: https://pushstack.wordpress.com/somfy-rts-protocol/
// and discussion: https://forum.arduino.cc/index.php?topic=208346.0
//
// MIT license, http://opensource.org/licenses/MIT
// ***************************************************************************
//#define NODE_DEBUG
#include "os_type.h"
#include "osapi.h"
#include "sections.h"
#include "module.h"
#include "lauxlib.h"
#include "lmem.h"
#include "platform.h"
#include "hw_timer.h"
#include "user_interface.h"
#define SYMBOL 640 // symbol width in microseconds
#define SOMFY_UP 0x2
#define SOMFY_STOP 0x1
#define SOMFY_DOWN 0x4
#define SOMFY_PROG 0x8
#define DIRECT_WRITE_LOW(pin) (GPIO_OUTPUT_SET(GPIO_ID_PIN(pin_num[pin]), 0))
#define DIRECT_WRITE_HIGH(pin) (GPIO_OUTPUT_SET(GPIO_ID_PIN(pin_num[pin]), 1))
static const os_param_t TIMER_OWNER = 0x736f6d66; // "somf"
static task_handle_t done_taskid;
static uint8_t pin;
static uint8_t frame[7];
static uint8_t sync;
static uint8_t repeat;
//static uint32_t delay[10] = {9415, 89565, 4*SYMBOL, 4*SYMBOL, 4*SYMBOL, 4550, SYMBOL, SYMBOL, SYMBOL, 30415}; // in us
// the `delay` array of constants must be in RAM as it is accessed from the timer interrupt
static const RAM_CONST_SECTION_ATTR uint32_t delay[10] = {US_TO_RTC_TIMER_TICKS(9415), US_TO_RTC_TIMER_TICKS(89565), US_TO_RTC_TIMER_TICKS(4*SYMBOL), US_TO_RTC_TIMER_TICKS(4*SYMBOL), US_TO_RTC_TIMER_TICKS(4*SYMBOL), US_TO_RTC_TIMER_TICKS(4550), US_TO_RTC_TIMER_TICKS(SYMBOL), US_TO_RTC_TIMER_TICKS(SYMBOL), US_TO_RTC_TIMER_TICKS(SYMBOL), US_TO_RTC_TIMER_TICKS(30415)}; // in ticks (no need to recalculate)
static uint8_t repeatindex;
static uint8_t signalindex;
static uint8_t subindex;
static uint8_t bitcondition;
int lua_done_ref; // callback when transmission is done
void buildFrame(uint8_t *frame, uint64_t remote, uint8_t button, uint16_t code) {
// NODE_DBG("remote: %x\n", remote);
// NODE_DBG("button: %x\n", button);
// NODE_DBG("rolling code: %x\n", code);
frame[0] = 0xA7; // Encryption key. Doesn't matter much
frame[1] = button << 4; // Which button did you press? The 4 LSB will be the checksum
frame[2] = code >> 8; // Rolling code (big endian)
frame[3] = code; // Rolling code
frame[4] = remote >> 16; // Remote address
frame[5] = remote >> 8; // Remote address
frame[6] = remote; // Remote address
// frame[7] = 0x80;
// frame[8] = 0x0;
// frame[9] = 0x0;
// NODE_DBG("Frame:\t\t\t%02x %02x %02x %02x %02x %02x %02x\n", frame[0], frame[1], frame[2], frame[3], frame[4], frame[5], frame[6]);
// Checksum calculation: a XOR of all the nibbles
uint8_t checksum = 0;
for(uint8_t i = 0; i < 7; i++) {
checksum = checksum ^ frame[i] ^ (frame[i] >> 4);
}
checksum &= 0b1111; // We keep the last 4 bits only
//Checksum integration
frame[1] |= checksum; // If a XOR of all the nibbles is equal to 0, the blinds will consider the checksum ok.
// NODE_DBG("With checksum:\t%02x %02x %02x %02x %02x %02x %02x\n", frame[0], frame[1], frame[2], frame[3], frame[4], frame[5], frame[6]);
// Obfuscation: a XOR of all the uint8_ts
for(uint8_t i = 1; i < 7; i++) {
frame[i] ^= frame[i-1];
}
// NODE_DBG("Obfuscated:\t\t%02x %02x %02x %02x %02x %02x %02x\n", frame[0], frame[1], frame[2], frame[3], frame[4], frame[5], frame[6]);
}
static void somfy_transmissionDone (task_param_t arg)
{
lua_State *L = lua_getstate();
lua_rawgeti (L, LUA_REGISTRYINDEX, lua_done_ref);
luaL_unref (L, LUA_REGISTRYINDEX, lua_done_ref);
lua_done_ref = LUA_NOREF;
lua_call (L, 0, 0);
}
static void ICACHE_RAM_ATTR sendCommand(os_param_t p) {
(void) p;
// NODE_DBG("%d\t%d\n", signalindex, subindex);
switch (signalindex) {
case 0:
subindex = 0;
if(sync == 2) { // Only with the first frame.
//Wake-up pulse & Silence
DIRECT_WRITE_HIGH(pin);
signalindex++;
// delayMicroseconds(9415);
break;
} else {
signalindex++; signalindex++; //no break means: go directly to step 3
}
case 1:
//Wake-up pulse & Silence
DIRECT_WRITE_LOW(pin);
signalindex++;
// delayMicroseconds(89565);
break;
case 2:
signalindex++;
// no break means go directly to step 3
// a "useless" step to allow repeating the hardware sync w/o the silence after wake-up pulse
case 3:
// Hardware sync: two sync for the first frame, seven for the following ones.
DIRECT_WRITE_HIGH(pin);
signalindex++;
// delayMicroseconds(4*SYMBOL);
break;
case 4:
DIRECT_WRITE_LOW(pin);
subindex++;
if (subindex < sync) {signalindex--;} else {signalindex++;}
// delayMicroseconds(4*SYMBOL);
break;
case 5:
// Software sync
DIRECT_WRITE_HIGH(pin);
signalindex++;
// delayMicroseconds(4550);
break;
case 6:
DIRECT_WRITE_LOW(pin);
signalindex++;
subindex=0;
// delayMicroseconds(SYMBOL);
break;
case 7:
//Data: bits are sent one by one, starting with the MSB.
bitcondition = ((frame[subindex/8] >> (7 - (subindex%8))) & 1) == 1;
if(bitcondition) {
DIRECT_WRITE_LOW(pin);
}
else {
DIRECT_WRITE_HIGH(pin);
}
signalindex++;
// delayMicroseconds(SYMBOL);
break;
case 8:
//Data: bits are sent one by one, starting with the MSB.
if(bitcondition) {
DIRECT_WRITE_HIGH(pin);
}
else {
DIRECT_WRITE_LOW(pin);
}
if (subindex<56) {
subindex++;
signalindex--;
}
else {
signalindex++;
}
// delayMicroseconds(SYMBOL);
break;
case 9:
DIRECT_WRITE_LOW(pin);
signalindex++;
// delayMicroseconds(30415); // Inter-frame silence
break;
case 10:
repeatindex++;
if (repeatindex<repeat) {
DIRECT_WRITE_HIGH(pin); //start repeat from step 3, but don't wait as after step 1
signalindex=4; subindex=0; sync=7;
} else {
platform_hw_timer_close(TIMER_OWNER);
if (lua_done_ref != LUA_NOREF) {
task_post_low (done_taskid, (task_param_t)0);
}
}
break;
}
if (signalindex<10) {
platform_hw_timer_arm_ticks(TIMER_OWNER, delay[signalindex-1]);
}
}
static int somfy_lua_sendcommand(lua_State* L) { // pin, remote, command, rolling_code, num_repeat, callback
if (!lua_isnumber(L, 4)) {
return luaL_error(L, "wrong arg range");
}
pin = luaL_checkinteger(L, 1);
uint64_t remote = luaL_checkinteger(L, 2);
uint8_t cmd = luaL_checkinteger(L, 3);
uint16_t code = luaL_checkinteger(L, 4);
repeat=luaL_optint( L, 5, 2 );
luaL_argcheck(L, platform_gpio_exists(pin), 1, "Invalid pin");
luaL_unref(L, LUA_REGISTRYINDEX, lua_done_ref);
if (!lua_isnoneornil(L, 6)) {
lua_pushvalue(L, 6);
lua_done_ref = luaL_ref(L, LUA_REGISTRYINDEX);
} else {
lua_done_ref = LUA_NOREF;
}
MOD_CHECK_ID(gpio, pin);
platform_gpio_mode(pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_PULLUP);
buildFrame(frame, remote, cmd, code);
if (!platform_hw_timer_init(TIMER_OWNER, FRC1_SOURCE, TRUE)) {
// Failed to init the timer
luaL_error(L, "Unable to initialize timer");
}
platform_hw_timer_set_func(TIMER_OWNER, sendCommand, 0);
sync=2;
signalindex=0; repeatindex=0;
sendCommand(0);
return 0;
}
static const LUA_REG_TYPE somfy_map[] = {
{ LSTRKEY( "UP" ), LNUMVAL( SOMFY_UP ) },
{ LSTRKEY( "DOWN" ), LNUMVAL( SOMFY_DOWN ) },
{ LSTRKEY( "PROG" ), LNUMVAL( SOMFY_PROG ) },
{ LSTRKEY( "STOP" ), LNUMVAL( SOMFY_STOP ) },
{ LSTRKEY( "sendcommand" ), LFUNCVAL(somfy_lua_sendcommand)},
{ LNILKEY, LNILVAL}
};
int luaopen_somfy( lua_State *L ) {
done_taskid = task_get_id((task_callback_t) somfy_transmissionDone);
return 0;
}
NODEMCU_MODULE(SOMFY, "somfy", somfy_map, luaopen_somfy);