From 30523fbe906c1319eb124483f90c9c68ef4981dd Mon Sep 17 00:00:00 2001 From: Tuan PM Date: Fri, 9 Sep 2016 22:37:03 +0700 Subject: [PATCH] -reformat code using space 2 - fix bug connect callback when connection refuse - change INFO to MQTT_INFO to resolve conflic with global INFO define --- .editorconfig | 20 + Makefile | 7 +- README.md | 102 +- SublimeAStyleFormatter.sublime-settings | 381 ++++++++ driver/uart.c | 208 ++-- include/driver/uart.h | 4 +- include/user_config.h | 26 +- include/user_config.sample.h | 67 +- modules/config.c | 110 --- modules/include/config.h | 61 -- modules/include/wifi.h | 2 - modules/wifi.c | 121 +-- mqtt/include/debug.h | 12 +- mqtt/include/mqtt.h | 108 +-- mqtt/include/mqtt_msg.h | 27 +- mqtt/include/proto.h | 20 +- mqtt/include/queue.h | 4 +- mqtt/include/ringbuf.h | 14 +- mqtt/include/typedef.h | 2 +- mqtt/include/utils.h | 2 +- mqtt/mqtt.c | 1173 ++++++++++++----------- mqtt/mqtt_msg.c | 168 ++-- mqtt/proto.c | 192 ++-- mqtt/queue.c | 14 +- mqtt/ringbuf.c | 56 +- mqtt/utils.c | 182 ++-- user/rfinit.c | 152 +-- user/user_main.c | 99 +- 28 files changed, 1697 insertions(+), 1637 deletions(-) create mode 100644 .editorconfig create mode 100644 SublimeAStyleFormatter.sublime-settings delete mode 100644 modules/config.c delete mode 100644 modules/include/config.h diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..3acb9f4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,20 @@ +# EditorConfig helps developers define and maintain consistent +# coding styles between different editors and IDEs +# http://editorconfig.org + +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false + +[*Makefile*] +indent_style = tab +indent_size = 2 diff --git a/Makefile b/Makefile index 1659cbd..af280b2 100644 --- a/Makefile +++ b/Makefile @@ -28,8 +28,8 @@ ESP_MODE = dio ESP_SIZE = 32m -VERBOSE = no -FLAVOR = release +VERBOSE = yes +FLAVOR = debug # name for the target project TARGET ?= esp_mqtt @@ -110,6 +110,7 @@ LDFLAGS = -nostdlib -Wl,--no-check-sections -u call_user_start -Wl,-static ifeq ($(FLAVOR),debug) LDFLAGS += -g -O2 + CFLAGS += -DMQTT_DEBUG_ON -DDEBUG_ON endif ifeq ($(FLAVOR),release) @@ -212,7 +213,7 @@ flash: $(ESPTOOL) $(ESPTOOL_OPTS) $(ESPTOOL_WRITE) fast: all flash openport - + openport: $(vecho) "After flash, terminal will enter serial port screen" $(vecho) "Please exit with command:" diff --git a/README.md b/README.md index e085700..8b10ea9 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ This is MQTT client library for ESP8266, port from: [MQTT client library for Con **Compile:** - Copy file `include/user_config.sample.h` to `include/user_config.local.h` and change settings, included: SSID, PASS, MQTT configurations ... -- When you change settings from `include/user_config.local.h`, you must change value of `CFG_HOLDER` (any value difference last value), new configurations will take effect + Make sure to add PYTHON PATH and compile PATH to Eclipse environment variable if using Eclipse @@ -41,98 +41,9 @@ make ESPPORT=/dev/ttyUSB0 flash ``` **Usage** -```c -#include "ets_sys.h" -#include "driver/uart.h" -#include "osapi.h" -#include "mqtt.h" -#include "wifi.h" -#include "config.h" -#include "debug.h" -#include "gpio.h" -#include "user_interface.h" -#include "mem.h" -MQTT_Client mqttClient; +See file: `user/user_main.c` -void wifiConnectCb(uint8_t status) -{ - if(status == STATION_GOT_IP){ - MQTT_Connect(&mqttClient); - } else { - MQTT_Disconnect(&mqttClient); - } -} -void mqttConnectedCb(uint32_t *args) -{ - MQTT_Client* client = (MQTT_Client*)args; - INFO("MQTT: Connected\r\n"); - MQTT_Subscribe(client, "/mqtt/topic/0", 0); - MQTT_Subscribe(client, "/mqtt/topic/1", 1); - MQTT_Subscribe(client, "/mqtt/topic/2", 2); - - MQTT_Publish(client, "/mqtt/topic/0", "hello0", 6, 0, 0); - MQTT_Publish(client, "/mqtt/topic/1", "hello1", 6, 1, 0); - MQTT_Publish(client, "/mqtt/topic/2", "hello2", 6, 2, 0); - -} - -void mqttDisconnectedCb(uint32_t *args) -{ - MQTT_Client* client = (MQTT_Client*)args; - INFO("MQTT: Disconnected\r\n"); -} - -void mqttPublishedCb(uint32_t *args) -{ - MQTT_Client* client = (MQTT_Client*)args; - INFO("MQTT: Published\r\n"); -} - -void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len) -{ - char *topicBuf = (char*)os_zalloc(topic_len+1), - *dataBuf = (char*)os_zalloc(data_len+1); - - MQTT_Client* client = (MQTT_Client*)args; - - os_memcpy(topicBuf, topic, topic_len); - topicBuf[topic_len] = 0; - - os_memcpy(dataBuf, data, data_len); - dataBuf[data_len] = 0; - - INFO("Receive topic: %s, data: %s \r\n", topicBuf, dataBuf); - os_free(topicBuf); - os_free(dataBuf); -} - - -void user_init(void) -{ - uart_init(BIT_RATE_115200, BIT_RATE_115200); - os_delay_us(1000000); - - CFG_Load(); - - MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, sysCfg.security); - //MQTT_InitConnection(&mqttClient, "192.168.11.122", 1880, 0); - - MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive, 1); - //MQTT_InitClient(&mqttClient, "client_id", "user", "pass", 120, 1); - - MQTT_InitLWT(&mqttClient, "/lwt", "offline", 0, 0); - MQTT_OnConnected(&mqttClient, mqttConnectedCb); - MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb); - MQTT_OnPublished(&mqttClient, mqttPublishedCb); - MQTT_OnData(&mqttClient, mqttDataCb); - - WIFI_Connect(sysCfg.sta_ssid, sysCfg.sta_pwd, wifiConnectCb); - - INFO("\r\nSystem started ...\r\n"); -} - -``` **Publish message and Subscribe** @@ -157,9 +68,7 @@ MQTT_InitLWT(&mqttClient, "/lwt", "offline", 0, 0); See: **include/user_config.sample.h** -If you want to load new default configurations, just change the value of CFG_HOLDER in **include/user_config.h** - -**Define protocol name in include/user_config.h** +**Define protocol name in include/user_config.local.h** ```c #define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/ @@ -221,17 +130,16 @@ function setup() { ``` **Example projects using esp_mqtt:** + - [https://github.com/eadf/esp_mqtt_lcd](https://github.com/eadf/esp_mqtt_lcd) - - [MQTT Broker for test](https://github.com/mcollina/mosca) [MQTT Client for test](https://chrome.google.com/webstore/detail/mqttlens/hemojaaeigabkbcookmlgmdigohjobjm?hl=en) **Contributing:** -***Feel free to contribute to the project in any way you like!*** +Feel free to contribute to the project in any way you like! **Authors:** diff --git a/SublimeAStyleFormatter.sublime-settings b/SublimeAStyleFormatter.sublime-settings new file mode 100644 index 0000000..04235ae --- /dev/null +++ b/SublimeAStyleFormatter.sublime-settings @@ -0,0 +1,381 @@ +{ + // NOTE: You should always edit options in user file, not this file. + + // Print debug message + "debug": false, + + // Auto format on file save + "autoformat_on_save": false, + + // The mapping key is `syntax name`, and the value is `formatting mode`. + // Note that the value for each mapping should be "c", "java" or "cs". + "user_defined_syntax_mode_mapping": { + // For example: + + /* + "arduino": "c", + "pde": "java", + "apex": "java" + */ + }, + + // Please visit http://astyle.sourceforge.net/astyle.html for more information + "options_default": { + // Default bracket style + // Can be one of "allman", "bsd", "break", "java", "attach", "kr", "k&r", + // "k/r" "stroustrup", "whitesmith", "banner", "gnu", "linux", "horstmann", + // "1tbs", "otbs ", "google", "pico", "lisp", "python", "vtk", or null + // for default. + "style": "k&r", + + // Tab options + // "indent": Can be one of "spaces", "tab" "force-tab", "force-tab-x", or null + // "indent-spaces": Can be either null or numbers + // + // While both "indent" or "indent-spaces" are null (default), the indentation options + // will be retrieved from Sublime Text view settings: `tab_size`, `translate_tabs_to_spaces`: + // 1. If `translate_tabs_to_spaces` is true, "indent" will be "spaces", otherwise, "tab"; + // 2. "indent-spaces" will equal to `tab_size`. + "indent": null, + "indent-spaces": null, + + // === Bracket Modify Options === + // Attach brackets to a namespace statement. This is done regardless of + // the bracket style being used. + "attach-namespaces": false, + + // Attach brackets to a class statement. This is done regardless of the + // bracket style being used. + "attach-classes": false, + + // Attach brackets to class and struct inline function definitions. This + // is not done for run-in type brackets (Horstmann and Pico styles). This + // option is effective for C++ files only. + "attach-inlines": false, + + // Attach brackets to a bracketed extern "C" statement. This is done + // regardless of the bracket style being used. This option is effective + // for C++ files only. + // + // An extern "C" statement that is part of a function definition is + // formatted according to the requested bracket style. Bracketed extern + // "C" statements are unaffected by the bracket style and this option is + // the only way to change them. + "attach-extern-c": false, + + // === Indentation Options === + + // Indent 'class' and 'struct' blocks so that the blocks 'public:', + // 'protected:' and 'private:' are indented. The struct blocks are + // indented only if an access modifier is declared somewhere in the + // struct. The entire block is indented. This option is effective for C++ files only. + "indent-classes": false, + + // Indent 'class' and 'struct' access modifiers, 'public:', 'protected:' + // and 'private:', one half indent. The rest of the class is not indented. + // This option is effective for C++ files only. If used with indent‑classes + // this option will be ignored. + "indent-modifiers": false, + + // Indent 'switch' blocks so that the 'case X:' statements are indented + // in the switch block. The entire case block is indented. + "indent-switches": true, + + // Indent 'case X:' blocks from the 'case X:' headers. Case statements + // not enclosed in blocks are NOT indented. + "indent-cases": true, + + // Add extra indentation to namespace blocks. This option has + // no effect on Java files. + "indent-namespaces": false, + + // Add extra indentation to labels so they appear 1 indent less than the + // current indentation, rather than being flushed to the left (the default). + "indent-labels": false, + + // Indent preprocessor blocks at bracket level zero, and immediately within + // a namespace. There are restrictions on what will be indented. Blocks + // within methods, classes, arrays, etc, will not be indented. Blocks + // containing brackets or multi-line define statements will not be indented. + // Without this option the preprocessor block is not indented. + "indent-preproc-block": false, + + // Indent multi-line preprocessor definitions ending with a backslash. + // Should be used with `convert-tabs` for proper results. Does a pretty + // good job, but cannot perform miracles in obfuscated preprocessor + // definitions. Without this option the preprocessor statements remain unchanged. + "indent-preproc-define": false, + + // Indent preprocessor conditional statements to the same level as the + // source code. + "indent-preproc-cond": false, + + // Indent C++ comments beginning in column one. By default C++ comments + // beginning in column one are not indented. This option will allow the + // comments to be indented with the code. + "indent-col1-comments": false, + + // Set the minimal indent that is added when a header is built of multiple + // lines. This indent helps to easily separate the header from the command + // statements that follow. The value for # indicates a number of indents + // and is a minimum value. The indent may be greater to align with the data + // on the previous line. + // The valid values are: + // 0 - no minimal indent. The lines will be aligned with the paren on the + // preceding line. + // 1 - indent at least one additional indent. + // 2 - indent at least two additional indents. + // 3 - indent at least one-half an additional indent. This is intended for + // large indents (e.g. 8). + // The default value is 2, two additional indents. + "min-conditional-indent": 2, + + // Set the maximum spaces to indent a continuation line. + // The maximum spaces indicate a number of columns and + // must not be greater than 120. A maximum of less + // than two indent lengths will be ignored. This option + // will prevent continuation lines from extending too + // far to the right. Setting a larger value will allow + // the code to be extended further to the right. + // + // range: [40, 120] + "max-instatement-indent": 40, + + // === Padding Options === + + // null - Do nothing + // "default" - Pad empty lines around header blocks (e.g. 'if', + // 'for', 'while'...). + // "all" - Pad empty lines around header blocks (e.g. 'if', + // 'for', 'while'...). Treat closing header blocks + // (e.g. 'else', 'catch') as stand-alone blocks. + "break-blocks": null, + + // Insert space padding around operators. Any end of line comments + // will remain in the original column, if possible. Note that there + // is no option to unpad. Once padded, they stay padded. + "pad-oper": true, + + // Insert space padding around parenthesis on both the outside and + // the inside. Any end of line comments will remain in the original + // column, if possible. + "pad-paren": false, + + // Insert space padding around parenthesis on the outside only. Any + // end of line comments will remain in the original column, if possible. + // This can be used with `unpad-paren` below to remove unwanted spaces. + "pad-paren-out": false, + + // Insert space padding around the first parenthesis in a series on the + // outside only. Any end of line comments will remain in the original + // column, if possible. This can be used with unpad-paren below to remove + // unwanted spaces. If used with pad-paren or pad-paren-out, this + // option will be ignored. If used with pad-paren-in, the result will + // be the same as pad-paren. + "pad-first-paren-out": false, + + // Insert space padding around parenthesis on the inside only. Any + // end of line comments will remain in the original column, if possible. + // This can be used with `unpad-paren` below to remove unwanted spaces. + "pad-paren-in": false, + + // Insert space padding after paren headers only (e.g. 'if', 'for', + //'while'...). Any end of line comments will remain in the original + // column, if possible. This can be used with unpad-paren to remove + // unwanted spaces. + "pad-header": true, + + // Remove extra space padding around parenthesis on the inside and outside. + // Any end of line comments will remain in the original column, if possible. + // This option can be used in combination with the paren padding options + // `pad-paren`, `pad-paren-out`, `pad-paren-in`, and `pad-header` above. + // Only padding that has not been requested by other options will be removed. + // For example, if a source has parens padded on both the inside and outside, + // and you want inside only. You need to use unpad-paren to remove the outside + // padding, and pad-paren-in to retain the inside padding. Using only `pad-paren-in` + // would not remove the outside padding. + "unpad-paren": false, + + // Delete empty lines within a function or method. Empty lines outside of functions + // or methods are NOT deleted. If used with break-blocks or break-blocks=all it will + // delete all lines EXCEPT the lines added by the `break-blocks` options. + "delete-empty-lines": false, + + // Fill empty lines with the white space of the previous line. + "fill-empty-lines": false, + + // Attach a pointer or reference operator (* or &) to either the variable type (left) + // or variable name (right), or place it between the type and name (middle). + // The spacing between the type and name will be preserved, if possible. To format + // references separately use the following `align-reference` option. + // can be one of null, "type", "middle" or "name" + "align-pointer": null, + + // This option will align references separate from pointers. Pointers are not changed + // by this option. If pointers and references are to be aligned the same, use the + // previous `align-pointer` option. The option align-reference=none will not change + // the reference alignment. The other options are the same as for `align-pointer`. + // In the case of a reference to a pointer (*&) with conflicting alignments, the + // `align-pointer` value will be used. + // can be one of "none", "type", "middle", "name", or null for default. + "align-reference": null, + + // === Formatting Options === + + // When `style` is "attach", "linux" or "stroustrup", this breaks closing headers + // (e.g. 'else', 'catch', ...) from their immediately preceding closing brackets. + // Closing header brackets are always broken with broken brackets, horstmann + // rackets, indented blocks, and indented brackets. + "break-closing-brackets": false, + + // Break "else if" header combinations into separate lines. This option has no effect + // if keep-one-line-statements is used, the "else if" statements will remain as they are. + // If this option is NOT used, "else if" header combinations will be placed on a single line. + "break-elseifs": false, + + // Add brackets to unbracketed one line conditional statements (e.g. 'if', 'for', 'while'...). + // The statement must be on a single line. The brackets will be added according to the + // currently requested predefined style or bracket type. If no style or bracket type is + // requested the brackets will be attached. If `add-one-line-brackets` is also used the + // result will be one line brackets. + "add-brackets": false, + + // Add one line brackets to unbracketed one line conditional statements + // (e.g. 'if', 'for', 'while'...). The statement must be on a single line. + // The option implies `keep-one-line-blocks` and will not break the one line blocks. + "add-one-line-brackets": false, + + // Remove brackets from conditional statements (e.g. 'if', 'for', 'while'...). + // The statement must be a single statement on a single line. If + // --add-brackets or --add-one-line-brackets is also used the result will + // be to add brackets. Brackets will not be removed from + // "One True Brace Style", --style=1tbs. + "remove-brackets": false, + + // Don't break one-line blocks. + "keep-one-line-blocks": true, + + // Don't break complex statements and multiple statements residing on a single line. + "keep-one-line-statements": true, + + // Closes whitespace in the angle brackets of template definitions. Closing + // the ending angle brackets is now allowed by the C++11 standard. + // Be sure your compiler supports this before making the changes. + "close-templates": false, + + // Remove the preceding '*' in a multi-line comment that begins a line. + // A trailing '*', if present, is also removed. Text that is less than one + // is indent is indented to one indent. Text greater than one indent is + // not changed. Multi-line comments that begin a line but without the + // preceding '*' are indented to one indent for consistency. This can + // slightly modify the indentation of commented out blocks of code. + // Lines containing all '*' are left unchanged. Extra spacing is removed + // from the comment close '*/'. + "remove-comment-prefix": false, + + // The option max-code-length will break a line if the code exceeds # characters. + // The valid values are 50 thru 200. Lines without logical conditionals will + // break on a logical conditional (||, &&, ...), comma, paren, semicolon, or space. + // + // Some code will not be broken, such as comments, quotes, and arrays. + // If used with keep-one-line-blocks or add-one-line-brackets the blocks + // will NOT be broken. If used with keep-one-line-statements the statements + // will be broken at a semicolon if the line goes over the maximum length. + // If there is no available break point within the max code length, the + // line will be broken at the first available break point after the max code length. + // + // By default logical conditionals will be placed first on the new line. + // The option break-after-logical will cause the logical conditionals to be + // placed last on the previous line. This option has no effect without max-code-length. + "max-code-length": -1, + "break-after-logical": false, + + // == Objective-C Options == + // Because of the longer indents sometimes needed for Objective-C, the option + // "max-instatement-indent" may need to be increased. If you are not getting + // the paren and square bracket alignment you want, try increasing this value. + + // Align the colons in Objective-C method declarations. This option is effective + // for Objective-C files only. + "align-method-colon": false, + + // Insert space padding after the '-' or '+' Objective-C method prefix. This will + // add exactly one space. Any additional spaces will be deleted. This option is + // effective for Objective-C files only. + "pad-method-prefix": false, + + // Remove all space padding after the '-' or '+' Objective-C method prefix. + // If used with pad-method-prefix, this option will be ignored. This option + // is effective for Objective-C files only. + "unpad-method-prefix": false, + + // Add or remove space padding before or after the colons in an Objective-C + // method call. These options will pad exactly one space. Any additional + // spaces will be deleted. Colons immediarely preceeding a paren will not + // be padded. This option is effective for Objective-C files only. + // + // Can be one of "none", "all", "after" or "before", or null for default. + "pad-method-colon": null + }, + + // + // Language Specific Options + // + // You can override default options in language-specific options here. + // Addtional options are also provided: + // + // "additional_options": Addtional options following astyle options file style + // (http://astyle.sourceforge.net/astyle.html). + // e.g.: "additional_options": ["--indent=spaces=2", "--convert-tabs"] + // + // "additional_options_file": Addtional options file for astyle (aka astylerc), you must specify + // a full path for that file, environment variable may be included. + // e.g.: "additional_options_file": "%USERPROFILE%/astylerc" // (Windows) + // e.g.: "additional_options_file": "$HOME/.astylerc" // (Linux) + // === Additional variables that you may use === + // $file_path The directory of the current file, e.g., C:\Files. + // $file The full path to the current file, e.g., C:\Files\Chapter1.txt. + // $file_name The name portion of the current file, e.g., Chapter1.txt. + // $file_extension The extension portion of the current file, e.g., txt. + // $file_base_name The name-only portion of the current file, e.g., Document. + // $packages The full path to the Packages folder. + // The following requires "Sublime Text 3" + // $project The full path to the current project file. + // $project_path The directory of the current project file. + // $project_name The name portion of the current project file. + // $project_extension The extension portion of the current project file. + // $project_base_name The name-only portion of the current project file. + // + // "use_only_additional_options": While true, SublimeAStyleFormatter will *only* process + // options in *both* "additional_options" and "additional_options_file". + + + // Language-specific options for C + "options_c": { + "use_only_additional_options": false, + "additional_options_file": "", + "additional_options": [] + }, + + // Language-specific for C++ + "options_c++": { + "use_only_additional_options": false, + "additional_options_file": "", + "additional_options": [] + }, + + // Language-specific for Java + "options_java": { + "style": "java", + "use_only_additional_options": false, + "additional_options_file": "", + "additional_options": [] + }, + + // Language-specific for C# + "options_cs": { + "use_only_additional_options": false, + "additional_options_file": "", + "additional_options": [] + } +} diff --git a/driver/uart.c b/driver/uart.c index 4d74b09..52225e0 100644 --- a/driver/uart.c +++ b/driver/uart.c @@ -14,23 +14,12 @@ #include "driver/uart.h" #include "osapi.h" #include "driver/uart_register.h" -//#include "ssc.h" - - +#include "mem.h" // UartDev is defined and initialized in rom code. extern UartDevice UartDev; -//extern os_event_t at_recvTaskQueue[at_recvTaskQueueLen]; LOCAL void uart0_rx_intr_handler(void *para); -/****************************************************************************** - * FunctionName : uart_config - * Description : Internal used function - * UART0 used for data TX/RX, RX buffer size is 0x100, interrupt enabled - * UART1 just used for debug output - * Parameters : uart_no, use UART0 or UART1 defined ahead - * Returns : NONE -*******************************************************************************/ LOCAL void ICACHE_FLASH_ATTR uart_config(uint8 uart_no) { @@ -58,22 +47,17 @@ uart_config(uint8 uart_no) SET_PERI_REG_MASK(UART_CONF0(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST); CLEAR_PERI_REG_MASK(UART_CONF0(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST); - //set rx fifo trigger -// WRITE_PERI_REG(UART_CONF1(uart_no), -// ((UartDev.rcv_buff.TrigLvl & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | -// ((96 & UART_TXFIFO_EMPTY_THRHD) << UART_TXFIFO_EMPTY_THRHD_S) | -// UART_RX_FLOW_EN); + if (uart_no == UART0) { //set rx fifo trigger WRITE_PERI_REG(UART_CONF1(uart_no), - ((0x10 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | - ((0x10 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) | - UART_RX_FLOW_EN | - (0x02 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S | - UART_RX_TOUT_EN); - SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_TOUT_INT_ENA | - UART_FRM_ERR_INT_ENA); + ((0x7F & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | + //((128 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) | + //UART_RX_FLOW_EN | + ((0x0F & UART_TXFIFO_EMPTY_THRHD) << UART_TXFIFO_EMPTY_THRHD_S)); + //UART_RX_TOUT_EN); + SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_TOUT_INT_ENA | UART_FRM_ERR_INT_ENA); } else { @@ -84,38 +68,23 @@ uart_config(uint8 uart_no) //clear all interrupt WRITE_PERI_REG(UART_INT_CLR(uart_no), 0xffff); //enable rx_interrupt - SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA); + SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_OVF_INT_ENA); } -/****************************************************************************** - * FunctionName : uart1_tx_one_char - * Description : Internal used function - * Use uart1 interface to transfer one char - * Parameters : uint8 TxChar - character to tx - * Returns : OK -*******************************************************************************/ LOCAL STATUS uart_tx_one_char(uint8 uart, uint8 TxChar) { - while (true) - { - uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT<> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) < 126) { - break; - } + while (true) + { + uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT << UART_TXFIFO_CNT_S); + if ((fifo_cnt >> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) < 126) { + break; } - - WRITE_PERI_REG(UART_FIFO(uart) , TxChar); - return OK; + } + WRITE_PERI_REG(UART_FIFO(uart) , TxChar); + return OK; } -/****************************************************************************** - * FunctionName : uart1_write_char - * Description : Internal used function - * Do some special deal while tx char is '\r' or '\n' - * Parameters : char c - character to tx - * Returns : NONE -*******************************************************************************/ void ICACHE_FLASH_ATTR uart1_write_char(char c) { @@ -149,13 +118,7 @@ uart0_write_char(char c) uart_tx_one_char(UART0, c); } } -/****************************************************************************** - * FunctionName : uart0_tx_buffer - * Description : use uart0 to transfer buffer - * Parameters : uint8 *buf - point to send buffer - * uint16 len - buffer len - * Returns : -*******************************************************************************/ + void ICACHE_FLASH_ATTR uart0_tx_buffer(uint8 *buf, uint16 len) { @@ -167,127 +130,70 @@ uart0_tx_buffer(uint8 *buf, uint16 len) } } -/****************************************************************************** - * FunctionName : uart0_sendStr - * Description : use uart0 to transfer buffer - * Parameters : uint8 *buf - point to send buffer - * uint16 len - buffer len - * Returns : -*******************************************************************************/ void ICACHE_FLASH_ATTR uart0_sendStr(const char *str) { - while(*str) - { - uart_tx_one_char(UART0, *str++); - } + while (*str) + { + uart_tx_one_char(UART0, *str++); + } } -/****************************************************************************** - * FunctionName : uart0_rx_intr_handler - * Description : Internal used function - * UART0 interrupt handler, add self handle code inside - * Parameters : void *para - point to ETS_UART_INTR_ATTACH's arg - * Returns : NONE -*******************************************************************************/ -//extern void at_recvTask(void); - LOCAL void uart0_rx_intr_handler(void *para) { - /* uart0 and uart1 intr combine togther, when interrupt occur, see reg 0x3ff20020, bit2, bit0 represents - * uart1 and uart0 respectively - */ -// RcvMsgBuff *pRxBuff = (RcvMsgBuff *)para; uint8 RcvChar; uint8 uart_no = UART0;//UartDev.buff_uart_no; - -// if (UART_RXFIFO_FULL_INT_ST != (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)) -// { -// return; -// } -// if (UART_RXFIFO_FULL_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)) -// { -//// at_recvTask(); -// RcvChar = READ_PERI_REG(UART_FIFO(uart_no)) & 0xFF; -// system_os_post(at_recvTaskPrio, NULL, RcvChar); -// WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_RXFIFO_FULL_INT_CLR); -// } - if(UART_FRM_ERR_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_FRM_ERR_INT_ST)) + /* Is the frame Error interrupt set ? */ + if (UART_FRM_ERR_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_FRM_ERR_INT_ST)) { - os_printf("FRM_ERR\r\n"); + //INFO("FRM_ERR\r\n"); WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_FRM_ERR_INT_CLR); } - - if(UART_RXFIFO_FULL_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)) + else if (UART_RXFIFO_FULL_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)) /*fifo full*/ { -// os_printf("fifo full\r\n"); - ETS_UART_INTR_DISABLE();///////// + CLEAR_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_TOUT_INT_ENA); + WRITE_PERI_REG(UART_INT_CLR(UART0), UART_RXFIFO_FULL_INT_CLR); + //INFO("Fifo full: %d\n", (READ_PERI_REG(UART_STATUS(UART0))>>UART_RXFIFO_CNT_S)&UART_RXFIFO_CNT); + while ((READ_PERI_REG(UART_STATUS(UART0)) >> UART_RXFIFO_CNT_S)&UART_RXFIFO_CNT) + { + //TODO: MCU_Input( READ_PERI_REG(UART_FIFO(UART0)) & 0xFF ); + } + WRITE_PERI_REG(UART_INT_CLR(UART0), UART_RXFIFO_FULL_INT_CLR); - //system_os_post(at_recvTaskPrio, 0, 0); + SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_TOUT_INT_ENA); -// WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_RXFIFO_FULL_INT_CLR); -// while (READ_PERI_REG(UART_STATUS(uart_no)) & (UART_RXFIFO_CNT << UART_RXFIFO_CNT_S)) -// { -//// at_recvTask(); -// RcvChar = READ_PERI_REG(UART_FIFO(uart_no)) & 0xFF; -// system_os_post(at_recvTaskPrio, NULL, RcvChar); -// } } - else if(UART_RXFIFO_TOUT_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_TOUT_INT_ST)) + else if (UART_RXFIFO_TOUT_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_TOUT_INT_ST)) { - ETS_UART_INTR_DISABLE();///////// - //system_os_post(at_recvTaskPrio, 0, 0); + CLEAR_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_TOUT_INT_ENA); + WRITE_PERI_REG(UART_INT_CLR(UART0), UART_RXFIFO_TOUT_INT_CLR); + //INFO("Fifo timeout: %d\n", (READ_PERI_REG(UART_STATUS(UART0))>>UART_RXFIFO_CNT_S)&UART_RXFIFO_CNT); + while ((READ_PERI_REG(UART_STATUS(UART0)) >> UART_RXFIFO_CNT_S)&UART_RXFIFO_CNT) + { + //MCU_Input( READ_PERI_REG(UART_FIFO(UART0)) & 0xFF ); + } + SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_TOUT_INT_ENA); -// WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_RXFIFO_TOUT_INT_CLR); -//// os_printf("rx time over\r\n"); -// while (READ_PERI_REG(UART_STATUS(uart_no)) & (UART_RXFIFO_CNT << UART_RXFIFO_CNT_S)) -// { -//// os_printf("process recv\r\n"); -//// at_recvTask(); -// RcvChar = READ_PERI_REG(UART_FIFO(uart_no)) & 0xFF; -// system_os_post(at_recvTaskPrio, NULL, RcvChar); -// } + } + else if (UART_RXFIFO_OVF_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_OVF_INT_ST)) + { + //INFO("FIFO FULL\n"); + WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_RXFIFO_OVF_INT_CLR); + } + else if (UART_TXFIFO_EMPTY_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_TXFIFO_EMPTY_INT_ST)) { + //INFO("TX EMPTY\n"); + WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_TXFIFO_EMPTY_INT_CLR); + CLEAR_PERI_REG_MASK(UART_INT_ENA(UART0), UART_TXFIFO_EMPTY_INT_ENA); } -// WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_RXFIFO_FULL_INT_CLR); - -// if (READ_PERI_REG(UART_STATUS(uart_no)) & (UART_RXFIFO_CNT << UART_RXFIFO_CNT_S)) -// { -// RcvChar = READ_PERI_REG(UART_FIFO(uart_no)) & 0xFF; -// at_recvTask(); -// *(pRxBuff->pWritePos) = RcvChar; - -// system_os_post(at_recvTaskPrio, NULL, RcvChar); - -// //insert here for get one command line from uart -// if (RcvChar == '\r') -// { -// pRxBuff->BuffState = WRITE_OVER; -// } -// -// pRxBuff->pWritePos++; -// -// if (pRxBuff->pWritePos == (pRxBuff->pRcvMsgBuff + RX_BUFF_SIZE)) -// { -// // overflow ...we may need more error handle here. -// pRxBuff->pWritePos = pRxBuff->pRcvMsgBuff ; -// } -// } + ETS_UART_INTR_ENABLE(); } -/****************************************************************************** - * FunctionName : uart_init - * Description : user interface for init uart - * Parameters : UartBautRate uart0_br - uart0 bautrate - * UartBautRate uart1_br - uart1 bautrate - * Returns : NONE -*******************************************************************************/ void ICACHE_FLASH_ATTR uart_init(UartBautRate uart0_br, UartBautRate uart1_br) { - // rom use 74880 baut_rate, here reinitialize UartDev.baut_rate = uart0_br; uart_config(UART0); UartDev.baut_rate = uart1_br; @@ -301,7 +207,5 @@ uart_init(UartBautRate uart0_br, UartBautRate uart1_br) void ICACHE_FLASH_ATTR uart_reattach() { - uart_init(BIT_RATE_74880, BIT_RATE_74880); -// ETS_UART_INTR_ATTACH(uart_rx_intr_handler_ssc, &(UartDev.rcv_buff)); -// ETS_UART_INTR_ENABLE(); + uart_init(BIT_RATE_115200, BIT_RATE_115200); } diff --git a/include/driver/uart.h b/include/driver/uart.h index 1940dbd..6d73d80 100644 --- a/include/driver/uart.h +++ b/include/driver/uart.h @@ -82,10 +82,10 @@ typedef enum { } RcvMsgState; typedef struct { - UartBautRate baut_rate; + UartBautRate baut_rate; UartBitsNum4Char data_bits; UartExistParity exist_parity; - UartParityMode parity; // chip size in byte + UartParityMode parity; // chip size in byte UartStopBitsNum stop_bits; UartFlowCtrl flow_ctrl; RcvMsgBuff rcv_buff; diff --git a/include/user_config.h b/include/user_config.h index 57840c4..2ab7874 100644 --- a/include/user_config.h +++ b/include/user_config.h @@ -1,13 +1,13 @@ -#ifndef __USER_CONFIG_H__ -#define __USER_CONFIG_H__ - -#define USE_OPTIMIZE_PRINTF - -#ifndef LOCAL_CONFIG_AVAILABLE -#error Please copy user_config.sample.h to user_config.local.h and modify your configurations -#else -#include "user_config.local.h" -#endif - -#endif - +#ifndef __USER_CONFIG_H__ +#define __USER_CONFIG_H__ + +#define USE_OPTIMIZE_PRINTF + +#ifndef LOCAL_CONFIG_AVAILABLE +#error Please copy user_config.sample.h to user_config.local.h and modify your configurations +#else +#include "user_config.local.h" +#endif + +#endif + diff --git a/include/user_config.sample.h b/include/user_config.sample.h index 1818962..4de6ccc 100644 --- a/include/user_config.sample.h +++ b/include/user_config.sample.h @@ -1,31 +1,36 @@ -#ifndef __MQTT_CONFIG_H__ -#define __MQTT_CONFIG_H__ - -#define CFG_HOLDER 0x00FF55A5 /* Change this value to load default configurations */ -#define CFG_LOCATION 0x3C /* Please don't change or if you know what you doing */ -#define MQTT_SSL_ENABLE - -/*DEFAULT CONFIGURATIONS*/ - -#define MQTT_HOST "192.168.1.100" //or "mqtt.yourdomain.com" -#define MQTT_PORT 1883 -#define MQTT_BUF_SIZE 1024 -#define MQTT_KEEPALIVE 120 /*second*/ - -#define MQTT_CLIENT_ID "CLIENT_%08X" -#define MQTT_USER "USER" -#define MQTT_PASS "PASS" - -#define STA_SSID "SSID" -#define STA_PASS "PASSWORD" -#define STA_TYPE AUTH_WPA2_PSK - -#define MQTT_RECONNECT_TIMEOUT 5 /*second*/ - -#define DEFAULT_SECURITY 0 -#define QUEUE_BUFFER_SIZE 2048 - -#define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/ -//PROTOCOL_NAMEv311 /*MQTT version 3.11 compatible with https://eclipse.org/paho/clients/testing/*/ - -#endif // __MQTT_CONFIG_H__ \ No newline at end of file +#ifndef __MQTT_CONFIG_H__ +#define __MQTT_CONFIG_H__ + +#define MQTT_SSL_ENABLE + +/*DEFAULT CONFIGURATIONS*/ + +#define MQTT_HOST "192.168.0.101" //or "mqtt.yourdomain.com" +#define MQTT_PORT 1883 +#define MQTT_BUF_SIZE 1024 +#define MQTT_KEEPALIVE 120 /*second*/ + +#define MQTT_CLIENT_ID "CLIENT_1234" +#define MQTT_USER "USER" +#define MQTT_PASS "PASS" +#define MQTT_CLEAN_SESSION 1 +#define MQTT_KEEPALIVE 120 + +#define STA_SSID "SSID" +#define STA_PASS "PASS" + +#define MQTT_RECONNECT_TIMEOUT 5 /*second*/ + +#define DEFAULT_SECURITY 0 +#define QUEUE_BUFFER_SIZE 2048 + +#define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/ +//PROTOCOL_NAMEv311 /*MQTT version 3.11 compatible with https://eclipse.org/paho/clients/testing/*/ + +#if defined(DEBUG_ON) +#define INFO( format, ... ) os_printf( format, ## __VA_ARGS__ ) +#else +#define INFO( format, ... ) +#endif + +#endif // __MQTT_CONFIG_H__ diff --git a/modules/config.c b/modules/config.c deleted file mode 100644 index fd2c60f..0000000 --- a/modules/config.c +++ /dev/null @@ -1,110 +0,0 @@ -/* -/* config.c -* -* Copyright (c) 2014-2015, Tuan PM -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* -* * Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * Neither the name of Redis nor the names of its contributors may be used -* to endorse or promote products derived from this software without -* specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -*/ -#include "ets_sys.h" -#include "os_type.h" -#include "mem.h" -#include "osapi.h" -#include "user_interface.h" - -#include "mqtt.h" -#include "config.h" -#include "user_config.h" -#include "debug.h" - -SYSCFG sysCfg; -SAVE_FLAG saveFlag; - -void ICACHE_FLASH_ATTR -CFG_Save() -{ - spi_flash_read((CFG_LOCATION + 3) * SPI_FLASH_SEC_SIZE, - (uint32 *)&saveFlag, sizeof(SAVE_FLAG)); - - if (saveFlag.flag == 0) { - spi_flash_erase_sector(CFG_LOCATION + 1); - spi_flash_write((CFG_LOCATION + 1) * SPI_FLASH_SEC_SIZE, - (uint32 *)&sysCfg, sizeof(SYSCFG)); - saveFlag.flag = 1; - spi_flash_erase_sector(CFG_LOCATION + 3); - spi_flash_write((CFG_LOCATION + 3) * SPI_FLASH_SEC_SIZE, - (uint32 *)&saveFlag, sizeof(SAVE_FLAG)); - } else { - spi_flash_erase_sector(CFG_LOCATION + 0); - spi_flash_write((CFG_LOCATION + 0) * SPI_FLASH_SEC_SIZE, - (uint32 *)&sysCfg, sizeof(SYSCFG)); - saveFlag.flag = 0; - spi_flash_erase_sector(CFG_LOCATION + 3); - spi_flash_write((CFG_LOCATION + 3) * SPI_FLASH_SEC_SIZE, - (uint32 *)&saveFlag, sizeof(SAVE_FLAG)); - } -} - -void ICACHE_FLASH_ATTR -CFG_Load() -{ - - INFO("\r\nload ...\r\n"); - spi_flash_read((CFG_LOCATION + 3) * SPI_FLASH_SEC_SIZE, - (uint32 *)&saveFlag, sizeof(SAVE_FLAG)); - if (saveFlag.flag == 0) { - spi_flash_read((CFG_LOCATION + 0) * SPI_FLASH_SEC_SIZE, - (uint32 *)&sysCfg, sizeof(SYSCFG)); - } else { - spi_flash_read((CFG_LOCATION + 1) * SPI_FLASH_SEC_SIZE, - (uint32 *)&sysCfg, sizeof(SYSCFG)); - } - if(sysCfg.cfg_holder != CFG_HOLDER){ - os_memset(&sysCfg, 0x00, sizeof sysCfg); - - - sysCfg.cfg_holder = CFG_HOLDER; - - os_sprintf(sysCfg.device_id, MQTT_CLIENT_ID, system_get_chip_id()); - sysCfg.device_id[sizeof(sysCfg.device_id) - 1] = '\0'; - os_strncpy(sysCfg.sta_ssid, STA_SSID, sizeof(sysCfg.sta_ssid) - 1); - os_strncpy(sysCfg.sta_pwd, STA_PASS, sizeof(sysCfg.sta_pwd) - 1); - sysCfg.sta_type = STA_TYPE; - - os_strncpy(sysCfg.mqtt_host, MQTT_HOST, sizeof(sysCfg.mqtt_host) - 1); - sysCfg.mqtt_port = MQTT_PORT; - os_strncpy(sysCfg.mqtt_user, MQTT_USER, sizeof(sysCfg.mqtt_user) - 1); - os_strncpy(sysCfg.mqtt_pass, MQTT_PASS, sizeof(sysCfg.mqtt_pass) - 1); - - sysCfg.security = DEFAULT_SECURITY; /* default non ssl */ - - sysCfg.mqtt_keepalive = MQTT_KEEPALIVE; - - INFO(" default configuration\r\n"); - - CFG_Save(); - } - -} diff --git a/modules/include/config.h b/modules/include/config.h deleted file mode 100644 index ac84ff2..0000000 --- a/modules/include/config.h +++ /dev/null @@ -1,61 +0,0 @@ -/* config.h -* -* Copyright (c) 2014-2015, Tuan PM -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* -* * Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * Neither the name of Redis nor the names of its contributors may be used -* to endorse or promote products derived from this software without -* specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef USER_CONFIG_H_ -#define USER_CONFIG_H_ -#include "os_type.h" -#include "user_config.h" -typedef struct{ - uint32_t cfg_holder; - uint8_t device_id[32]; - - uint8_t sta_ssid[64]; - uint8_t sta_pwd[64]; - uint32_t sta_type; - - uint8_t mqtt_host[64]; - uint32_t mqtt_port; - uint8_t mqtt_user[32]; - uint8_t mqtt_pass[32]; - uint32_t mqtt_keepalive; - uint8_t security; -} SYSCFG; - -typedef struct { - uint8 flag; - uint8 pad[3]; -} SAVE_FLAG; - -void ICACHE_FLASH_ATTR CFG_Save(); -void ICACHE_FLASH_ATTR CFG_Load(); - -extern SYSCFG sysCfg; - -#endif /* USER_CONFIG_H_ */ diff --git a/modules/include/wifi.h b/modules/include/wifi.h index 64fa4ac..60f93e1 100644 --- a/modules/include/wifi.h +++ b/modules/include/wifi.h @@ -10,6 +10,4 @@ #include "os_type.h" typedef void (*WifiCallback)(uint8_t); void ICACHE_FLASH_ATTR WIFI_Connect(uint8_t* ssid, uint8_t* pass, WifiCallback cb); - - #endif /* USER_WIFI_H_ */ diff --git a/modules/wifi.c b/modules/wifi.c index c7c45fd..8f46908 100644 --- a/modules/wifi.c +++ b/modules/wifi.c @@ -13,88 +13,67 @@ #include "mqtt_msg.h" #include "debug.h" #include "user_config.h" -#include "config.h" static ETSTimer WiFiLinker; WifiCallback wifiCb = NULL; static uint8_t wifiStatus = STATION_IDLE, lastWifiStatus = STATION_IDLE; static void ICACHE_FLASH_ATTR wifi_check_ip(void *arg) { - struct ip_info ipConfig; + struct ip_info ipConfig; + os_timer_disarm(&WiFiLinker); + wifi_get_ip_info(STATION_IF, &ipConfig); + wifiStatus = wifi_station_get_connect_status(); + if (wifiStatus == STATION_GOT_IP && ipConfig.ip.addr != 0) + { + os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL); + os_timer_arm(&WiFiLinker, 2000, 0); + } + else + { + if (wifi_station_get_connect_status() == STATION_WRONG_PASSWORD) + { + INFO("STATION_WRONG_PASSWORD\r\n"); + wifi_station_connect(); + } + else if (wifi_station_get_connect_status() == STATION_NO_AP_FOUND) + { + INFO("STATION_NO_AP_FOUND\r\n"); + wifi_station_connect(); + } + else if (wifi_station_get_connect_status() == STATION_CONNECT_FAIL) + { + INFO("STATION_CONNECT_FAIL\r\n"); + wifi_station_connect(); + } + else + { + INFO("STATION_IDLE\r\n"); + } - os_timer_disarm(&WiFiLinker); - wifi_get_ip_info(STATION_IF, &ipConfig); - wifiStatus = wifi_station_get_connect_status(); - if (wifiStatus == STATION_GOT_IP && ipConfig.ip.addr != 0) - { - - os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL); - os_timer_arm(&WiFiLinker, 2000, 0); - - - } - else - { - if(wifi_station_get_connect_status() == STATION_WRONG_PASSWORD) - { - - INFO("STATION_WRONG_PASSWORD\r\n"); - wifi_station_connect(); - - - } - else if(wifi_station_get_connect_status() == STATION_NO_AP_FOUND) - { - - INFO("STATION_NO_AP_FOUND\r\n"); - wifi_station_connect(); - - - } - else if(wifi_station_get_connect_status() == STATION_CONNECT_FAIL) - { - - INFO("STATION_CONNECT_FAIL\r\n"); - wifi_station_connect(); - - } - else - { - INFO("STATION_IDLE\r\n"); - } - - os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL); - os_timer_arm(&WiFiLinker, 500, 0); - } - if(wifiStatus != lastWifiStatus){ - lastWifiStatus = wifiStatus; - if(wifiCb) - wifiCb(wifiStatus); - } + os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL); + os_timer_arm(&WiFiLinker, 500, 0); + } + if (wifiStatus != lastWifiStatus) { + lastWifiStatus = wifiStatus; + if (wifiCb) + wifiCb(wifiStatus); + } } void ICACHE_FLASH_ATTR WIFI_Connect(uint8_t* ssid, uint8_t* pass, WifiCallback cb) { - struct station_config stationConf; + struct station_config stationConf; - INFO("WIFI_INIT\r\n"); - wifi_set_opmode_current(STATION_MODE); - - //wifi_station_set_auto_connect(FALSE); - wifiCb = cb; - - os_memset(&stationConf, 0, sizeof(struct station_config)); - - os_sprintf(stationConf.ssid, "%s", ssid); - os_sprintf(stationConf.password, "%s", pass); - - wifi_station_set_config_current(&stationConf); - - os_timer_disarm(&WiFiLinker); - os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL); - os_timer_arm(&WiFiLinker, 1000, 0); - - //wifi_station_set_auto_connect(TRUE); - wifi_station_connect(); + INFO("WIFI_INIT\r\n"); + wifi_set_opmode_current(STATION_MODE); + wifiCb = cb; + os_memset(&stationConf, 0, sizeof(struct station_config)); + os_sprintf(stationConf.ssid, "%s", ssid); + os_sprintf(stationConf.password, "%s", pass); + wifi_station_set_config_current(&stationConf); + os_timer_disarm(&WiFiLinker); + os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL); + os_timer_arm(&WiFiLinker, 1000, 0); + wifi_station_connect(); } diff --git a/mqtt/include/debug.h b/mqtt/include/debug.h index 3879573..f45dd6d 100644 --- a/mqtt/include/debug.h +++ b/mqtt/include/debug.h @@ -8,16 +8,12 @@ #ifndef USER_DEBUG_H_ #define USER_DEBUG_H_ -#if defined(GLOBAL_DEBUG_ON) -#define MQTT_DEBUG_ON -#endif + #if defined(MQTT_DEBUG_ON) -#define INFO( format, ... ) os_printf( format, ## __VA_ARGS__ ) +#define MQTT_INFO( format, ... ) os_printf( format, ## __VA_ARGS__ ) #else -#define INFO( format, ... ) +#define MQTT_INFO( format, ... ) #endif -// #ifndef INFO -// #define INFO os_printf -// #endif + #endif /* USER_DEBUG_H_ */ diff --git a/mqtt/include/mqtt.h b/mqtt/include/mqtt.h index 2cdf462..f026319 100644 --- a/mqtt/include/mqtt.h +++ b/mqtt/include/mqtt.h @@ -63,71 +63,71 @@ typedef struct mqtt_state_t } mqtt_state_t; typedef enum { - WIFI_INIT, - WIFI_CONNECTING, - WIFI_CONNECTING_ERROR, - WIFI_CONNECTED, - DNS_RESOLVE, - TCP_DISCONNECTING, - TCP_DISCONNECTED, - TCP_RECONNECT_DISCONNECTING, - TCP_RECONNECT_REQ, - TCP_RECONNECT, - TCP_CONNECTING, - TCP_CONNECTING_ERROR, - TCP_CONNECTED, - MQTT_CONNECT_SEND, - MQTT_CONNECT_SENDING, - MQTT_SUBSCIBE_SEND, - MQTT_SUBSCIBE_SENDING, - MQTT_DATA, - MQTT_KEEPALIVE_SEND, - MQTT_PUBLISH_RECV, - MQTT_PUBLISHING, - MQTT_DELETING, - MQTT_DELETED, + WIFI_INIT, + WIFI_CONNECTING, + WIFI_CONNECTING_ERROR, + WIFI_CONNECTED, + DNS_RESOLVE, + TCP_DISCONNECTING, + TCP_DISCONNECTED, + TCP_RECONNECT_DISCONNECTING, + TCP_RECONNECT_REQ, + TCP_RECONNECT, + TCP_CONNECTING, + TCP_CONNECTING_ERROR, + TCP_CONNECTED, + MQTT_CONNECT_SEND, + MQTT_CONNECT_SENDING, + MQTT_SUBSCIBE_SEND, + MQTT_SUBSCIBE_SENDING, + MQTT_DATA, + MQTT_KEEPALIVE_SEND, + MQTT_PUBLISH_RECV, + MQTT_PUBLISHING, + MQTT_DELETING, + MQTT_DELETED, } tConnState; typedef void (*MqttCallback)(uint32_t *args); typedef void (*MqttDataCallback)(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t lengh); typedef struct { - struct espconn *pCon; - uint8_t security; - uint8_t* host; - uint32_t port; - ip_addr_t ip; - mqtt_state_t mqtt_state; - mqtt_connect_info_t connect_info; - MqttCallback connectedCb; - MqttCallback disconnectedCb; - MqttCallback publishedCb; - MqttCallback timeoutCb; - MqttDataCallback dataCb; - ETSTimer mqttTimer; - uint32_t keepAliveTick; - uint32_t reconnectTick; - uint32_t sendTimeout; - tConnState connState; - QUEUE msgQueue; - void* user_data; + struct espconn *pCon; + uint8_t security; + uint8_t* host; + uint32_t port; + ip_addr_t ip; + mqtt_state_t mqtt_state; + mqtt_connect_info_t connect_info; + MqttCallback connectedCb; + MqttCallback disconnectedCb; + MqttCallback publishedCb; + MqttCallback timeoutCb; + MqttDataCallback dataCb; + ETSTimer mqttTimer; + uint32_t keepAliveTick; + uint32_t reconnectTick; + uint32_t sendTimeout; + tConnState connState; + QUEUE msgQueue; + void* user_data; } MQTT_Client; #define SEC_NONSSL 0 -#define SEC_SSL 1 +#define SEC_SSL 1 -#define MQTT_FLAG_CONNECTED 1 -#define MQTT_FLAG_READY 2 -#define MQTT_FLAG_EXIT 4 +#define MQTT_FLAG_CONNECTED 1 +#define MQTT_FLAG_READY 2 +#define MQTT_FLAG_EXIT 4 -#define MQTT_EVENT_TYPE_NONE 0 -#define MQTT_EVENT_TYPE_CONNECTED 1 -#define MQTT_EVENT_TYPE_DISCONNECTED 2 -#define MQTT_EVENT_TYPE_SUBSCRIBED 3 -#define MQTT_EVENT_TYPE_UNSUBSCRIBED 4 -#define MQTT_EVENT_TYPE_PUBLISH 5 -#define MQTT_EVENT_TYPE_PUBLISHED 6 -#define MQTT_EVENT_TYPE_EXITED 7 +#define MQTT_EVENT_TYPE_NONE 0 +#define MQTT_EVENT_TYPE_CONNECTED 1 +#define MQTT_EVENT_TYPE_DISCONNECTED 2 +#define MQTT_EVENT_TYPE_SUBSCRIBED 3 +#define MQTT_EVENT_TYPE_UNSUBSCRIBED 4 +#define MQTT_EVENT_TYPE_PUBLISH 5 +#define MQTT_EVENT_TYPE_PUBLISHED 6 +#define MQTT_EVENT_TYPE_EXITED 7 #define MQTT_EVENT_TYPE_PUBLISH_CONTINUATION 8 void ICACHE_FLASH_ATTR MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security); diff --git a/mqtt/include/mqtt_msg.h b/mqtt/include/mqtt_msg.h index 7101ffe..5137ecf 100644 --- a/mqtt/include/mqtt_msg.h +++ b/mqtt/include/mqtt_msg.h @@ -1,4 +1,4 @@ -/* +/* * File: mqtt_msg.h * Author: Minh Tuan * @@ -6,10 +6,10 @@ */ #ifndef MQTT_MSG_H -#define MQTT_MSG_H +#define MQTT_MSG_H #include "user_config.h" #include "c_types.h" -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -43,9 +43,9 @@ extern "C" { * POSSIBILITY OF SUCH DAMAGE. * */ -/* 7 6 5 4 3 2 1 0*/ -/*| --- Message Type---- | DUP Flag | QoS Level | Retain | -/* Remaining Length */ +/* 7 6 5 4 3 2 1 0*/ +/*| --- Message Type---- | DUP Flag | QoS Level | Retain | +/* Remaining Length */ enum mqtt_message_type @@ -66,6 +66,16 @@ enum mqtt_message_type MQTT_MSG_TYPE_DISCONNECT = 14 }; +enum mqtt_connect_return_code +{ + CONNECTION_ACCEPTED = 0, + CONNECTION_REFUSE_PROTOCOL, + CONNECTION_REFUSE_ID_REJECTED, + CONNECTION_REFUSE_SERVER_UNAVAILABLE, + CONNECTION_REFUSE_BAD_USERNAME, + CONNECTION_REFUSE_NOT_AUTHORIZED +}; + typedef struct mqtt_message { uint8_t* data; @@ -99,6 +109,7 @@ typedef struct mqtt_connect_info static inline int ICACHE_FLASH_ATTR mqtt_get_type(uint8_t* buffer) { return (buffer[0] & 0xf0) >> 4; } +static inline int ICACHE_FLASH_ATTR mqtt_get_connect_return_code(uint8_t* buffer) { return buffer[3]; } static inline int ICACHE_FLASH_ATTR mqtt_get_dup(uint8_t* buffer) { return (buffer[0] & 0x08) >> 3; } static inline int ICACHE_FLASH_ATTR mqtt_get_qos(uint8_t* buffer) { return (buffer[0] & 0x06) >> 1; } static inline int ICACHE_FLASH_ATTR mqtt_get_retain(uint8_t* buffer) { return (buffer[0] & 0x01); } @@ -122,9 +133,9 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pingresp(mqtt_connection_t* connectio mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_disconnect(mqtt_connection_t* connection); -#ifdef __cplusplus +#ifdef __cplusplus } #endif -#endif /* MQTT_MSG_H */ +#endif /* MQTT_MSG_H */ diff --git a/mqtt/include/proto.h b/mqtt/include/proto.h index 4c452b5..a405bcb 100644 --- a/mqtt/include/proto.h +++ b/mqtt/include/proto.h @@ -1,4 +1,4 @@ -/* +/* * File: proto.h * Author: ThuHien * @@ -6,21 +6,21 @@ */ #ifndef _PROTO_H_ -#define _PROTO_H_ +#define _PROTO_H_ #include #include "typedef.h" #include "ringbuf.h" typedef void(PROTO_PARSE_CALLBACK)(); -typedef struct{ - U8 *buf; - U16 bufSize; - U16 dataLen; - U8 isEsc; - U8 isBegin; - PROTO_PARSE_CALLBACK* callback; -}PROTO_PARSER; +typedef struct { + U8 *buf; + U16 bufSize; + U16 dataLen; + U8 isEsc; + U8 isBegin; + PROTO_PARSE_CALLBACK* callback; +} PROTO_PARSER; I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize); I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len); diff --git a/mqtt/include/queue.h b/mqtt/include/queue.h index 5f277a6..71b324c 100644 --- a/mqtt/include/queue.h +++ b/mqtt/include/queue.h @@ -33,8 +33,8 @@ #include "os_type.h" #include "ringbuf.h" typedef struct { - uint8_t *buf; - RINGBUF rb; + uint8_t *buf; + RINGBUF rb; } QUEUE; void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize); diff --git a/mqtt/include/ringbuf.h b/mqtt/include/ringbuf.h index 6c6d6e6..f1a4f7e 100644 --- a/mqtt/include/ringbuf.h +++ b/mqtt/include/ringbuf.h @@ -5,13 +5,13 @@ #include #include "typedef.h" -typedef struct{ - U8* p_o; /**< Original pointer */ - U8* volatile p_r; /**< Read pointer */ - U8* volatile p_w; /**< Write pointer */ - volatile I32 fill_cnt; /**< Number of filled slots */ - I32 size; /**< Buffer size */ -}RINGBUF; +typedef struct { + U8* p_o; /**< Original pointer */ + U8* volatile p_r; /**< Read pointer */ + U8* volatile p_w; /**< Write pointer */ + volatile I32 fill_cnt; /**< Number of filled slots */ + I32 size; /**< Buffer size */ +} RINGBUF; I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size); I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c); diff --git a/mqtt/include/typedef.h b/mqtt/include/typedef.h index a4c69d6..887001a 100644 --- a/mqtt/include/typedef.h +++ b/mqtt/include/typedef.h @@ -1,6 +1,6 @@ /** * \file -* Standard Types definition +* Standard Types definition */ #ifndef _TYPE_DEF_H_ diff --git a/mqtt/include/utils.h b/mqtt/include/utils.h index 175beff..fe28748 100644 --- a/mqtt/include/utils.h +++ b/mqtt/include/utils.h @@ -1,5 +1,5 @@ #ifndef _UTILS_H_ -#define _UTILS_H_ +#define _UTILS_H_ #include "c_types.h" diff --git a/mqtt/mqtt.c b/mqtt/mqtt.c index 42b6921..3e4c80d 100644 --- a/mqtt/mqtt.c +++ b/mqtt/mqtt.c @@ -40,12 +40,12 @@ #include "mqtt.h" #include "queue.h" -#define MQTT_TASK_PRIO 2 -#define MQTT_TASK_QUEUE_SIZE 1 -#define MQTT_SEND_TIMOUT 5 +#define MQTT_TASK_PRIO 2 +#define MQTT_TASK_QUEUE_SIZE 1 +#define MQTT_SEND_TIMOUT 5 #ifndef QUEUE_BUFFER_SIZE -#define QUEUE_BUFFER_SIZE 2048 +#define QUEUE_BUFFER_SIZE 2048 #endif unsigned char *default_certificate; @@ -58,42 +58,42 @@ os_event_t mqtt_procTaskQueue[MQTT_TASK_QUEUE_SIZE]; LOCAL void ICACHE_FLASH_ATTR mqtt_dns_found(const char *name, ip_addr_t *ipaddr, void *arg) { - struct espconn *pConn = (struct espconn *)arg; - MQTT_Client* client = (MQTT_Client *)pConn->reverse; + struct espconn *pConn = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pConn->reverse; - if (ipaddr == NULL) - { - INFO("DNS: Found, but got no ip, try to reconnect\r\n"); - client->connState = TCP_RECONNECT_REQ; - return; - } + if (ipaddr == NULL) + { + MQTT_INFO("DNS: Found, but got no ip, try to reconnect\r\n"); + client->connState = TCP_RECONNECT_REQ; + return; + } - INFO("DNS: found ip %d.%d.%d.%d\n", - *((uint8 *) &ipaddr->addr), - *((uint8 *) &ipaddr->addr + 1), - *((uint8 *) &ipaddr->addr + 2), - *((uint8 *) &ipaddr->addr + 3)); + MQTT_INFO("DNS: found ip %d.%d.%d.%d\n", + *((uint8 *) &ipaddr->addr), + *((uint8 *) &ipaddr->addr + 1), + *((uint8 *) &ipaddr->addr + 2), + *((uint8 *) &ipaddr->addr + 3)); - if (client->ip.addr == 0 && ipaddr->addr != 0) - { - os_memcpy(client->pCon->proto.tcp->remote_ip, &ipaddr->addr, 4); - if (client->security) { + if (client->ip.addr == 0 && ipaddr->addr != 0) + { + os_memcpy(client->pCon->proto.tcp->remote_ip, &ipaddr->addr, 4); + if (client->security) { #ifdef MQTT_SSL_ENABLE - espconn_secure_connect(client->pCon); + espconn_secure_connect(client->pCon); #else - INFO("TCP: Do not support SSL\r\n"); + MQTT_INFO("TCP: Do not support SSL\r\n"); #endif - } - else { - espconn_connect(client->pCon); - } + } + else { + espconn_connect(client->pCon); + } - client->connState = TCP_CONNECTING; - INFO("TCP: connecting...\r\n"); - } + client->connState = TCP_CONNECTING; + MQTT_INFO("TCP: connecting...\r\n"); + } - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } @@ -101,52 +101,52 @@ mqtt_dns_found(const char *name, ip_addr_t *ipaddr, void *arg) LOCAL void ICACHE_FLASH_ATTR deliver_publish(MQTT_Client* client, uint8_t* message, int length) { - mqtt_event_data_t event_data; + mqtt_event_data_t event_data; - event_data.topic_length = length; - event_data.topic = mqtt_get_publish_topic(message, &event_data.topic_length); - event_data.data_length = length; - event_data.data = mqtt_get_publish_data(message, &event_data.data_length); + event_data.topic_length = length; + event_data.topic = mqtt_get_publish_topic(message, &event_data.topic_length); + event_data.data_length = length; + event_data.data = mqtt_get_publish_data(message, &event_data.data_length); - if (client->dataCb) - client->dataCb((uint32_t*)client, event_data.topic, event_data.topic_length, event_data.data, event_data.data_length); + if (client->dataCb) + client->dataCb((uint32_t*)client, event_data.topic, event_data.topic_length, event_data.data, event_data.data_length); } void ICACHE_FLASH_ATTR mqtt_send_keepalive(MQTT_Client *client) { - INFO("\r\nMQTT: Send keepalive packet to %s:%d!\r\n", client->host, client->port); - client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); - client->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PINGREQ; - client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); - client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + MQTT_INFO("\r\nMQTT: Send keepalive packet to %s:%d!\r\n", client->host, client->port); + client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); + client->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PINGREQ; + client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); + client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); - client->sendTimeout = MQTT_SEND_TIMOUT; - INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); - err_t result = ESPCONN_OK; - if (client->security) { + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + err_t result = ESPCONN_OK; + if (client->security) { #ifdef MQTT_SSL_ENABLE - result = espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + result = espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); #else - INFO("TCP: Do not support SSL\r\n"); + MQTT_INFO("TCP: Do not support SSL\r\n"); #endif - } - else { - result = espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); - } + } + else { + result = espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + } - client->mqtt_state.outbound_message = NULL; - if(ESPCONN_OK == result) { - client->keepAliveTick = 0; - client->connState = MQTT_DATA; - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); - } - else { - client->connState = TCP_RECONNECT_DISCONNECTING; - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); - } + client->mqtt_state.outbound_message = NULL; + if (ESPCONN_OK == result) { + client->keepAliveTick = 0; + client->connState = MQTT_DATA; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } + else { + client->connState = TCP_RECONNECT_DISCONNECTING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } } /** @@ -157,20 +157,20 @@ mqtt_send_keepalive(MQTT_Client *client) void ICACHE_FLASH_ATTR mqtt_tcpclient_delete(MQTT_Client *mqttClient) { - if (mqttClient->pCon != NULL) { - INFO("TCP: Free memory\r\n"); - // Force abort connections - espconn_abort(mqttClient->pCon); - // Delete connections - espconn_delete(mqttClient->pCon); + if (mqttClient->pCon != NULL) { + MQTT_INFO("TCP: Free memory\r\n"); + // Force abort connections + espconn_abort(mqttClient->pCon); + // Delete connections + espconn_delete(mqttClient->pCon); - if (mqttClient->pCon->proto.tcp) { - os_free(mqttClient->pCon->proto.tcp); - mqttClient->pCon->proto.tcp = NULL; - } - os_free(mqttClient->pCon); - mqttClient->pCon = NULL; - } + if (mqttClient->pCon->proto.tcp) { + os_free(mqttClient->pCon->proto.tcp); + mqttClient->pCon->proto.tcp = NULL; + } + os_free(mqttClient->pCon); + mqttClient->pCon = NULL; + } } /** @@ -181,86 +181,86 @@ mqtt_tcpclient_delete(MQTT_Client *mqttClient) void ICACHE_FLASH_ATTR mqtt_client_delete(MQTT_Client *mqttClient) { - if(mqttClient == NULL) - return; + if (mqttClient == NULL) + return; - if (mqttClient->pCon != NULL){ - mqtt_tcpclient_delete(mqttClient); - } + if (mqttClient->pCon != NULL) { + mqtt_tcpclient_delete(mqttClient); + } - if (mqttClient->host != NULL) { - os_free(mqttClient->host); - mqttClient->host = NULL; - } + if (mqttClient->host != NULL) { + os_free(mqttClient->host); + mqttClient->host = NULL; + } - if (mqttClient->user_data != NULL) { - os_free(mqttClient->user_data); - mqttClient->user_data = NULL; - } + if (mqttClient->user_data != NULL) { + os_free(mqttClient->user_data); + mqttClient->user_data = NULL; + } - if(mqttClient->mqtt_state.in_buffer != NULL) { - os_free(mqttClient->mqtt_state.in_buffer); - mqttClient->mqtt_state.in_buffer = NULL; - } + if (mqttClient->mqtt_state.in_buffer != NULL) { + os_free(mqttClient->mqtt_state.in_buffer); + mqttClient->mqtt_state.in_buffer = NULL; + } - if(mqttClient->mqtt_state.out_buffer != NULL) { - os_free(mqttClient->mqtt_state.out_buffer); - mqttClient->mqtt_state.out_buffer = NULL; - } + if (mqttClient->mqtt_state.out_buffer != NULL) { + os_free(mqttClient->mqtt_state.out_buffer); + mqttClient->mqtt_state.out_buffer = NULL; + } - if(mqttClient->mqtt_state.outbound_message != NULL) { - if(mqttClient->mqtt_state.outbound_message->data != NULL) - { - os_free(mqttClient->mqtt_state.outbound_message->data); - mqttClient->mqtt_state.outbound_message->data = NULL; - } - } + if (mqttClient->mqtt_state.outbound_message != NULL) { + if (mqttClient->mqtt_state.outbound_message->data != NULL) + { + os_free(mqttClient->mqtt_state.outbound_message->data); + mqttClient->mqtt_state.outbound_message->data = NULL; + } + } - if(mqttClient->mqtt_state.mqtt_connection.buffer != NULL) { - // Already freed but not NULL - mqttClient->mqtt_state.mqtt_connection.buffer = NULL; - } + if (mqttClient->mqtt_state.mqtt_connection.buffer != NULL) { + // Already freed but not NULL + mqttClient->mqtt_state.mqtt_connection.buffer = NULL; + } - if(mqttClient->connect_info.client_id != NULL) { - os_free(mqttClient->connect_info.client_id); - mqttClient->connect_info.client_id = NULL; - } + if (mqttClient->connect_info.client_id != NULL) { + os_free(mqttClient->connect_info.client_id); + mqttClient->connect_info.client_id = NULL; + } - if(mqttClient->connect_info.username != NULL) { - os_free(mqttClient->connect_info.username); - mqttClient->connect_info.username = NULL; - } + if (mqttClient->connect_info.username != NULL) { + os_free(mqttClient->connect_info.username); + mqttClient->connect_info.username = NULL; + } - if(mqttClient->connect_info.password != NULL) { - os_free(mqttClient->connect_info.password); - mqttClient->connect_info.password = NULL; - } + if (mqttClient->connect_info.password != NULL) { + os_free(mqttClient->connect_info.password); + mqttClient->connect_info.password = NULL; + } - if(mqttClient->connect_info.will_topic != NULL) { - os_free(mqttClient->connect_info.will_topic); - mqttClient->connect_info.will_topic = NULL; - } + if (mqttClient->connect_info.will_topic != NULL) { + os_free(mqttClient->connect_info.will_topic); + mqttClient->connect_info.will_topic = NULL; + } - if(mqttClient->connect_info.will_message != NULL) { - os_free(mqttClient->connect_info.will_message); - mqttClient->connect_info.will_message = NULL; - } + if (mqttClient->connect_info.will_message != NULL) { + os_free(mqttClient->connect_info.will_message); + mqttClient->connect_info.will_message = NULL; + } - if (mqttClient->msgQueue.buf != NULL) { - os_free(mqttClient->msgQueue.buf); - mqttClient->msgQueue.buf = NULL; - } + if (mqttClient->msgQueue.buf != NULL) { + os_free(mqttClient->msgQueue.buf); + mqttClient->msgQueue.buf = NULL; + } - // Initialize state - mqttClient->connState = WIFI_INIT; - // Clear callback functions to avoid abnormal callback - mqttClient->connectedCb = NULL; - mqttClient->disconnectedCb = NULL; - mqttClient->publishedCb = NULL; - mqttClient->timeoutCb = NULL; - mqttClient->dataCb = NULL; + // Initialize state + mqttClient->connState = WIFI_INIT; + // Clear callback functions to avoid abnormal callback + mqttClient->connectedCb = NULL; + mqttClient->disconnectedCb = NULL; + mqttClient->publishedCb = NULL; + mqttClient->timeoutCb = NULL; + mqttClient->dataCb = NULL; - INFO("MQTT: client already deleted\r\n"); + MQTT_INFO("MQTT: client already deleted\r\n"); } @@ -274,136 +274,160 @@ mqtt_client_delete(MQTT_Client *mqttClient) void ICACHE_FLASH_ATTR mqtt_tcpclient_recv(void *arg, char *pdata, unsigned short len) { - uint8_t msg_type; - uint8_t msg_qos; - uint16_t msg_id; + uint8_t msg_type; + uint8_t msg_qos; + uint16_t msg_id; + uint8_t msg_conn_ret; - struct espconn *pCon = (struct espconn*)arg; - MQTT_Client *client = (MQTT_Client *)pCon->reverse; + struct espconn *pCon = (struct espconn*)arg; + MQTT_Client *client = (MQTT_Client *)pCon->reverse; - client->keepAliveTick = 0; + client->keepAliveTick = 0; READPACKET: - INFO("TCP: data received %d bytes\r\n", len); - // INFO("STATE: %d\r\n", client->connState); - if (len < MQTT_BUF_SIZE && len > 0) { - os_memcpy(client->mqtt_state.in_buffer, pdata, len); + MQTT_INFO("TCP: data received %d bytes\r\n", len); + // MQTT_INFO("STATE: %d\r\n", client->connState); + if (len < MQTT_BUF_SIZE && len > 0) { + os_memcpy(client->mqtt_state.in_buffer, pdata, len); - msg_type = mqtt_get_type(client->mqtt_state.in_buffer); - msg_qos = mqtt_get_qos(client->mqtt_state.in_buffer); - msg_id = mqtt_get_id(client->mqtt_state.in_buffer, client->mqtt_state.in_buffer_length); - switch (client->connState) { - case MQTT_CONNECT_SENDING: - if (msg_type == MQTT_MSG_TYPE_CONNACK) { - if (client->mqtt_state.pending_msg_type != MQTT_MSG_TYPE_CONNECT) { - INFO("MQTT: Invalid packet\r\n"); - if (client->security) { + msg_type = mqtt_get_type(client->mqtt_state.in_buffer); + msg_qos = mqtt_get_qos(client->mqtt_state.in_buffer); + msg_id = mqtt_get_id(client->mqtt_state.in_buffer, client->mqtt_state.in_buffer_length); + switch (client->connState) { + case MQTT_CONNECT_SENDING: + if (msg_type == MQTT_MSG_TYPE_CONNACK) { + if (client->mqtt_state.pending_msg_type != MQTT_MSG_TYPE_CONNECT) { + MQTT_INFO("MQTT: Invalid packet\r\n"); + if (client->security) { #ifdef MQTT_SSL_ENABLE - espconn_secure_disconnect(client->pCon); + espconn_secure_disconnect(client->pCon); #else - INFO("TCP: Do not support SSL\r\n"); + MQTT_INFO("TCP: Do not support SSL\r\n"); #endif - } - else { - espconn_disconnect(client->pCon); - } - } else { - INFO("MQTT: Connected to %s:%d\r\n", client->host, client->port); - client->connState = MQTT_DATA; - if (client->connectedCb) - client->connectedCb((uint32_t*)client); - } + } + else { + espconn_disconnect(client->pCon); + } + } else { + msg_conn_ret = mqtt_get_connect_return_code(client->mqtt_state.in_buffer); + switch (msg_conn_ret) { + case CONNECTION_ACCEPTED: + MQTT_INFO("MQTT: Connected to %s:%d\r\n", client->host, client->port); + client->connState = MQTT_DATA; + if (client->connectedCb) + client->connectedCb((uint32_t*)client); + break; + case CONNECTION_REFUSE_PROTOCOL: + case CONNECTION_REFUSE_SERVER_UNAVAILABLE: + case CONNECTION_REFUSE_BAD_USERNAME: + case CONNECTION_REFUSE_NOT_AUTHORIZED: + MQTT_INFO("MQTT: Connection refuse, reason code: %d\r\n", msg_conn_ret); + default: + if (client->security) { +#ifdef MQTT_SSL_ENABLE + espconn_secure_disconnect(client->pCon); +#else + MQTT_INFO("TCP: Do not support SSL\r\n"); +#endif + } + else { + espconn_disconnect(client->pCon); + } - } - break; - case MQTT_DATA: - case MQTT_KEEPALIVE_SEND: - client->mqtt_state.message_length_read = len; - client->mqtt_state.message_length = mqtt_get_total_length(client->mqtt_state.in_buffer, client->mqtt_state.message_length_read); + } + + } + + } + break; + case MQTT_DATA: + case MQTT_KEEPALIVE_SEND: + client->mqtt_state.message_length_read = len; + client->mqtt_state.message_length = mqtt_get_total_length(client->mqtt_state.in_buffer, client->mqtt_state.message_length_read); - switch (msg_type) - { + switch (msg_type) + { - case MQTT_MSG_TYPE_SUBACK: - if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_SUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id) - INFO("MQTT: Subscribe successful\r\n"); - break; - case MQTT_MSG_TYPE_UNSUBACK: - if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id) - INFO("MQTT: UnSubscribe successful\r\n"); - break; - case MQTT_MSG_TYPE_PUBLISH: - if (msg_qos == 1) - client->mqtt_state.outbound_message = mqtt_msg_puback(&client->mqtt_state.mqtt_connection, msg_id); - else if (msg_qos == 2) - client->mqtt_state.outbound_message = mqtt_msg_pubrec(&client->mqtt_state.mqtt_connection, msg_id); - if (msg_qos == 1 || msg_qos == 2) { - INFO("MQTT: Queue response QoS: %d\r\n", msg_qos); - if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { - INFO("MQTT: Queue full\r\n"); - } - } + case MQTT_MSG_TYPE_SUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_SUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id) + MQTT_INFO("MQTT: Subscribe successful\r\n"); + break; + case MQTT_MSG_TYPE_UNSUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && client->mqtt_state.pending_msg_id == msg_id) + MQTT_INFO("MQTT: UnSubscribe successful\r\n"); + break; + case MQTT_MSG_TYPE_PUBLISH: + if (msg_qos == 1) + client->mqtt_state.outbound_message = mqtt_msg_puback(&client->mqtt_state.mqtt_connection, msg_id); + else if (msg_qos == 2) + client->mqtt_state.outbound_message = mqtt_msg_pubrec(&client->mqtt_state.mqtt_connection, msg_id); + if (msg_qos == 1 || msg_qos == 2) { + MQTT_INFO("MQTT: Queue response QoS: %d\r\n", msg_qos); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + } - deliver_publish(client, client->mqtt_state.in_buffer, client->mqtt_state.message_length_read); - break; - case MQTT_MSG_TYPE_PUBACK: - if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) { - INFO("MQTT: received MQTT_MSG_TYPE_PUBACK, finish QoS1 publish\r\n"); - } + deliver_publish(client, client->mqtt_state.in_buffer, client->mqtt_state.message_length_read); + break; + case MQTT_MSG_TYPE_PUBACK: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) { + MQTT_INFO("MQTT: received MQTT_MSG_TYPE_PUBACK, finish QoS1 publish\r\n"); + } - break; - case MQTT_MSG_TYPE_PUBREC: - client->mqtt_state.outbound_message = mqtt_msg_pubrel(&client->mqtt_state.mqtt_connection, msg_id); - if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { - INFO("MQTT: Queue full\r\n"); - } - break; - case MQTT_MSG_TYPE_PUBREL: - client->mqtt_state.outbound_message = mqtt_msg_pubcomp(&client->mqtt_state.mqtt_connection, msg_id); - if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { - INFO("MQTT: Queue full\r\n"); - } - break; - case MQTT_MSG_TYPE_PUBCOMP: - if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) { - INFO("MQTT: receive MQTT_MSG_TYPE_PUBCOMP, finish QoS2 publish\r\n"); - } - break; - case MQTT_MSG_TYPE_PINGREQ: - client->mqtt_state.outbound_message = mqtt_msg_pingresp(&client->mqtt_state.mqtt_connection); - if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { - INFO("MQTT: Queue full\r\n"); - } - break; - case MQTT_MSG_TYPE_PINGRESP: - // Ignore - break; - } - // NOTE: this is done down here and not in the switch case above - // because the PSOCK_READBUF_LEN() won't work inside a switch - // statement due to the way protothreads resume. - if (msg_type == MQTT_MSG_TYPE_PUBLISH) - { - len = client->mqtt_state.message_length_read; + break; + case MQTT_MSG_TYPE_PUBREC: + client->mqtt_state.outbound_message = mqtt_msg_pubrel(&client->mqtt_state.mqtt_connection, msg_id); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PUBREL: + client->mqtt_state.outbound_message = mqtt_msg_pubcomp(&client->mqtt_state.mqtt_connection, msg_id); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PUBCOMP: + if (client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && client->mqtt_state.pending_msg_id == msg_id) { + MQTT_INFO("MQTT: receive MQTT_MSG_TYPE_PUBCOMP, finish QoS2 publish\r\n"); + } + break; + case MQTT_MSG_TYPE_PINGREQ: + client->mqtt_state.outbound_message = mqtt_msg_pingresp(&client->mqtt_state.mqtt_connection); + if (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + } + break; + case MQTT_MSG_TYPE_PINGRESP: + // Ignore + break; + } + // NOTE: this is done down here and not in the switch case above + // because the PSOCK_READBUF_LEN() won't work inside a switch + // statement due to the way protothreads resume. + if (msg_type == MQTT_MSG_TYPE_PUBLISH) + { + len = client->mqtt_state.message_length_read; - if (client->mqtt_state.message_length < client->mqtt_state.message_length_read) - { - //client->connState = MQTT_PUBLISH_RECV; - //Not Implement yet - len -= client->mqtt_state.message_length; - pdata += client->mqtt_state.message_length; + if (client->mqtt_state.message_length < client->mqtt_state.message_length_read) + { + //client->connState = MQTT_PUBLISH_RECV; + //Not Implement yet + len -= client->mqtt_state.message_length; + pdata += client->mqtt_state.message_length; - INFO("Get another published message\r\n"); - goto READPACKET; - } + MQTT_INFO("Get another published message\r\n"); + goto READPACKET; + } - } - break; - } - } else { - INFO("ERROR: Message too long\r\n"); - } - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } + break; + } + } else { + MQTT_INFO("ERROR: Message too long\r\n"); + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } /** @@ -414,65 +438,65 @@ READPACKET: void ICACHE_FLASH_ATTR mqtt_tcpclient_sent_cb(void *arg) { - struct espconn *pCon = (struct espconn *)arg; - MQTT_Client* client = (MQTT_Client *)pCon->reverse; - INFO("TCP: Sent\r\n"); - client->sendTimeout = 0; - client->keepAliveTick =0; + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; + MQTT_INFO("TCP: Sent\r\n"); + client->sendTimeout = 0; + client->keepAliveTick = 0; - if ((client->connState == MQTT_DATA || client->connState == MQTT_KEEPALIVE_SEND) - && client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH) { - if (client->publishedCb) - client->publishedCb((uint32_t*)client); - } - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + if ((client->connState == MQTT_DATA || client->connState == MQTT_KEEPALIVE_SEND) + && client->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH) { + if (client->publishedCb) + client->publishedCb((uint32_t*)client); + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } void ICACHE_FLASH_ATTR mqtt_timer(void *arg) { - MQTT_Client* client = (MQTT_Client*)arg; + MQTT_Client* client = (MQTT_Client*)arg; - if (client->connState == MQTT_DATA) { - client->keepAliveTick ++; - if (client->keepAliveTick > (client->mqtt_state.connect_info->keepalive / 2)) { - client->connState = MQTT_KEEPALIVE_SEND; - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); - } + if (client->connState == MQTT_DATA) { + client->keepAliveTick ++; + if (client->keepAliveTick > (client->mqtt_state.connect_info->keepalive / 2)) { + client->connState = MQTT_KEEPALIVE_SEND; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + } - } else if (client->connState == TCP_RECONNECT_REQ) { - client->reconnectTick ++; - if (client->reconnectTick > MQTT_RECONNECT_TIMEOUT) { - client->reconnectTick = 0; - client->connState = TCP_RECONNECT; - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); - if (client->timeoutCb) - client->timeoutCb((uint32_t*)client); - } - } - if (client->sendTimeout > 0) - client->sendTimeout --; + } else if (client->connState == TCP_RECONNECT_REQ) { + client->reconnectTick ++; + if (client->reconnectTick > MQTT_RECONNECT_TIMEOUT) { + client->reconnectTick = 0; + client->connState = TCP_RECONNECT; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + if (client->timeoutCb) + client->timeoutCb((uint32_t*)client); + } + } + if (client->sendTimeout > 0) + client->sendTimeout --; } void ICACHE_FLASH_ATTR mqtt_tcpclient_discon_cb(void *arg) { - struct espconn *pespconn = (struct espconn *)arg; - MQTT_Client* client = (MQTT_Client *)pespconn->reverse; - INFO("TCP: Disconnected callback\r\n"); - if(TCP_DISCONNECTING == client->connState) { - client->connState = TCP_DISCONNECTED; - } - else if(MQTT_DELETING == client->connState) { - client->connState = MQTT_DELETED; - } - else { - client->connState = TCP_RECONNECT_REQ; - } - if (client->disconnectedCb) - client->disconnectedCb((uint32_t*)client); + struct espconn *pespconn = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pespconn->reverse; + MQTT_INFO("TCP: Disconnected callback\r\n"); + if (TCP_DISCONNECTING == client->connState) { + client->connState = TCP_DISCONNECTED; + } + else if (MQTT_DELETING == client->connState) { + client->connState = MQTT_DELETED; + } + else { + client->connState = TCP_RECONNECT_REQ; + } + if (client->disconnectedCb) + client->disconnectedCb((uint32_t*)client); - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } @@ -485,36 +509,36 @@ mqtt_tcpclient_discon_cb(void *arg) void ICACHE_FLASH_ATTR mqtt_tcpclient_connect_cb(void *arg) { - struct espconn *pCon = (struct espconn *)arg; - MQTT_Client* client = (MQTT_Client *)pCon->reverse; + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; - espconn_regist_disconcb(client->pCon, mqtt_tcpclient_discon_cb); - espconn_regist_recvcb(client->pCon, mqtt_tcpclient_recv);//////// - espconn_regist_sentcb(client->pCon, mqtt_tcpclient_sent_cb);/////// - INFO("MQTT: Connected to broker %s:%d\r\n", client->host, client->port); + espconn_regist_disconcb(client->pCon, mqtt_tcpclient_discon_cb); + espconn_regist_recvcb(client->pCon, mqtt_tcpclient_recv);//////// + espconn_regist_sentcb(client->pCon, mqtt_tcpclient_sent_cb);/////// + MQTT_INFO("MQTT: Connected to broker %s:%d\r\n", client->host, client->port); - mqtt_msg_init(&client->mqtt_state.mqtt_connection, client->mqtt_state.out_buffer, client->mqtt_state.out_buffer_length); - client->mqtt_state.outbound_message = mqtt_msg_connect(&client->mqtt_state.mqtt_connection, client->mqtt_state.connect_info); - client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); - client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + mqtt_msg_init(&client->mqtt_state.mqtt_connection, client->mqtt_state.out_buffer, client->mqtt_state.out_buffer_length); + client->mqtt_state.outbound_message = mqtt_msg_connect(&client->mqtt_state.mqtt_connection, client->mqtt_state.connect_info); + client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); + client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); - client->sendTimeout = MQTT_SEND_TIMOUT; - INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); - if (client->security) { + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + if (client->security) { #ifdef MQTT_SSL_ENABLE - espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); #else - INFO("TCP: Do not support SSL\r\n"); + MQTT_INFO("TCP: Do not support SSL\r\n"); #endif - } - else { - espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); - } + } + else { + espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); + } - client->mqtt_state.outbound_message = NULL; - client->connState = MQTT_CONNECT_SENDING; - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + client->mqtt_state.outbound_message = NULL; + client->connState = MQTT_CONNECT_SENDING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } /** @@ -525,232 +549,233 @@ mqtt_tcpclient_connect_cb(void *arg) void ICACHE_FLASH_ATTR mqtt_tcpclient_recon_cb(void *arg, sint8 errType) { - struct espconn *pCon = (struct espconn *)arg; - MQTT_Client* client = (MQTT_Client *)pCon->reverse; + struct espconn *pCon = (struct espconn *)arg; + MQTT_Client* client = (MQTT_Client *)pCon->reverse; - INFO("TCP: Reconnect to %s:%d\r\n", client->host, client->port); + MQTT_INFO("TCP: Reconnect to %s:%d\r\n", client->host, client->port); - client->connState = TCP_RECONNECT_REQ; + client->connState = TCP_RECONNECT_REQ; - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } /** * @brief MQTT publish function. - * @param client: MQTT_Client reference - * @param topic: string topic will publish to - * @param data: buffer data send point to + * @param client: MQTT_Client reference + * @param topic: string topic will publish to + * @param data: buffer data send point to * @param data_length: length of data - * @param qos: qos - * @param retain: retain + * @param qos: qos + * @param retain: retain * @retval TRUE if success queue */ BOOL ICACHE_FLASH_ATTR MQTT_Publish(MQTT_Client *client, const char* topic, const char* data, int data_length, int qos, int retain) { - uint8_t dataBuffer[MQTT_BUF_SIZE]; - uint16_t dataLen; - client->mqtt_state.outbound_message = mqtt_msg_publish(&client->mqtt_state.mqtt_connection, - topic, data, data_length, - qos, retain, - &client->mqtt_state.pending_msg_id); - if (client->mqtt_state.outbound_message->length == 0) { - INFO("MQTT: Queuing publish failed\r\n"); - return FALSE; - } - INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size); - while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { - INFO("MQTT: Queue full\r\n"); - if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { - INFO("MQTT: Serious buffer error\r\n"); - return FALSE; - } - } - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); - return TRUE; + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_publish(&client->mqtt_state.mqtt_connection, + topic, data, data_length, + qos, retain, + &client->mqtt_state.pending_msg_id); + if (client->mqtt_state.outbound_message->length == 0) { + MQTT_INFO("MQTT: Queuing publish failed\r\n"); + return FALSE; + } + MQTT_INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; } /** * @brief MQTT subscibe function. - * @param client: MQTT_Client reference - * @param topic: string topic will subscribe - * @param qos: qos + * @param client: MQTT_Client reference + * @param topic: string topic will subscribe + * @param qos: qos * @retval TRUE if success queue */ BOOL ICACHE_FLASH_ATTR MQTT_Subscribe(MQTT_Client *client, char* topic, uint8_t qos) { - uint8_t dataBuffer[MQTT_BUF_SIZE]; - uint16_t dataLen; + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; - client->mqtt_state.outbound_message = mqtt_msg_subscribe(&client->mqtt_state.mqtt_connection, - topic, qos, - &client->mqtt_state.pending_msg_id); - INFO("MQTT: queue subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id); - while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { - INFO("MQTT: Queue full\r\n"); - if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { - INFO("MQTT: Serious buffer error\r\n"); - return FALSE; - } - } - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); - return TRUE; + client->mqtt_state.outbound_message = mqtt_msg_subscribe(&client->mqtt_state.mqtt_connection, + topic, qos, + &client->mqtt_state.pending_msg_id); + MQTT_INFO("MQTT: queue subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + + return TRUE; } /** * @brief MQTT un-subscibe function. - * @param client: MQTT_Client reference + * @param client: MQTT_Client reference * @param topic: String topic will un-subscribe * @retval TRUE if success queue */ BOOL ICACHE_FLASH_ATTR MQTT_UnSubscribe(MQTT_Client *client, char* topic) { - uint8_t dataBuffer[MQTT_BUF_SIZE]; - uint16_t dataLen; - client->mqtt_state.outbound_message = mqtt_msg_unsubscribe(&client->mqtt_state.mqtt_connection, - topic, - &client->mqtt_state.pending_msg_id); - INFO("MQTT: queue un-subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id); - while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { - INFO("MQTT: Queue full\r\n"); - if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { - INFO("MQTT: Serious buffer error\r\n"); - return FALSE; - } - } - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); - return TRUE; + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_unsubscribe(&client->mqtt_state.mqtt_connection, + topic, + &client->mqtt_state.pending_msg_id); + MQTT_INFO("MQTT: queue un-subscribe, topic\"%s\", id: %d\r\n", topic, client->mqtt_state.pending_msg_id); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; } /** * @brief MQTT ping function. - * @param client: MQTT_Client reference + * @param client: MQTT_Client reference * @retval TRUE if success queue */ BOOL ICACHE_FLASH_ATTR MQTT_Ping(MQTT_Client *client) { - uint8_t dataBuffer[MQTT_BUF_SIZE]; - uint16_t dataLen; - client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); - if(client->mqtt_state.outbound_message->length == 0){ - INFO("MQTT: Queuing publish failed\r\n"); - return FALSE; - } - INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size); - while(QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1){ - INFO("MQTT: Queue full\r\n"); - if(QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { - INFO("MQTT: Serious buffer error\r\n"); - return FALSE; - } - } - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); - return TRUE; + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); + if (client->mqtt_state.outbound_message->length == 0) { + MQTT_INFO("MQTT: Queuing publish failed\r\n"); + return FALSE; + } + MQTT_INFO("MQTT: queuing publish, length: %d, queue size(%d/%d)\r\n", client->mqtt_state.outbound_message->length, client->msgQueue.rb.fill_cnt, client->msgQueue.rb.size); + while (QUEUE_Puts(&client->msgQueue, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length) == -1) { + MQTT_INFO("MQTT: Queue full\r\n"); + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) { + MQTT_INFO("MQTT: Serious buffer error\r\n"); + return FALSE; + } + } + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); + return TRUE; } void ICACHE_FLASH_ATTR MQTT_Task(os_event_t *e) { - MQTT_Client* client = (MQTT_Client*)e->par; - uint8_t dataBuffer[MQTT_BUF_SIZE]; - uint16_t dataLen; - if (e->par == 0) - return; - switch (client->connState) { + MQTT_Client* client = (MQTT_Client*)e->par; + uint8_t dataBuffer[MQTT_BUF_SIZE]; + uint16_t dataLen; + if (e->par == 0) + return; + switch (client->connState) { - case TCP_RECONNECT_REQ: - break; - case TCP_RECONNECT: - mqtt_tcpclient_delete(client); - MQTT_Connect(client); - INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port); - client->connState = TCP_CONNECTING; - break; - case MQTT_DELETING: - case TCP_DISCONNECTING: - case TCP_RECONNECT_DISCONNECTING: - if (client->security) { + case TCP_RECONNECT_REQ: + break; + case TCP_RECONNECT: + mqtt_tcpclient_delete(client); + MQTT_Connect(client); + MQTT_INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port); + client->connState = TCP_CONNECTING; + break; + case MQTT_DELETING: + case TCP_DISCONNECTING: + case TCP_RECONNECT_DISCONNECTING: + if (client->security) { #ifdef MQTT_SSL_ENABLE - espconn_secure_disconnect(client->pCon); + espconn_secure_disconnect(client->pCon); #else - INFO("TCP: Do not support SSL\r\n"); + MQTT_INFO("TCP: Do not support SSL\r\n"); #endif - } - else { - espconn_disconnect(client->pCon); - } - break; - case TCP_DISCONNECTED: - INFO("MQTT: Disconnected\r\n"); - mqtt_tcpclient_delete(client); - break; - case MQTT_DELETED: - INFO("MQTT: Deleted client\r\n"); - mqtt_client_delete(client); - break; - case MQTT_KEEPALIVE_SEND: - mqtt_send_keepalive(client); - break; - case MQTT_DATA: - if (QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) { - break; - } - if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0) { - client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer); - client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen); + } + else { + espconn_disconnect(client->pCon); + } + break; + case TCP_DISCONNECTED: + MQTT_INFO("MQTT: Disconnected\r\n"); + mqtt_tcpclient_delete(client); + break; + case MQTT_DELETED: + MQTT_INFO("MQTT: Deleted client\r\n"); + mqtt_client_delete(client); + break; + case MQTT_KEEPALIVE_SEND: + mqtt_send_keepalive(client); + break; + case MQTT_DATA: + if (QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) { + break; + } + if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0) { + client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer); + client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen); - client->sendTimeout = MQTT_SEND_TIMOUT; - INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); - if (client->security) { + client->sendTimeout = MQTT_SEND_TIMOUT; + MQTT_INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); + if (client->security) { #ifdef MQTT_SSL_ENABLE - espconn_secure_send(client->pCon, dataBuffer, dataLen); + espconn_secure_send(client->pCon, dataBuffer, dataLen); #else - INFO("TCP: Do not support SSL\r\n"); + MQTT_INFO("TCP: Do not support SSL\r\n"); #endif - } - else { - espconn_send(client->pCon, dataBuffer, dataLen); - } + } + else { + espconn_send(client->pCon, dataBuffer, dataLen); + } - client->mqtt_state.outbound_message = NULL; - break; - } - break; - } + client->mqtt_state.outbound_message = NULL; + break; + } + break; + } } /** * @brief MQTT initialization connection function - * @param client: MQTT_Client reference - * @param host: Domain or IP string - * @param port: Port to connect - * @param security: 1 for ssl, 0 for none + * @param client: MQTT_Client reference + * @param host: Domain or IP string + * @param port: Port to connect + * @param security: 1 for ssl, 0 for none * @retval None */ void ICACHE_FLASH_ATTR MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security) { - uint32_t temp; - INFO("MQTT:InitConnection\r\n"); - os_memset(mqttClient, 0, sizeof(MQTT_Client)); - temp = os_strlen(host); - mqttClient->host = (uint8_t*)os_zalloc(temp + 1); - os_strcpy(mqttClient->host, host); - mqttClient->host[temp] = 0; - mqttClient->port = port; - mqttClient->security = security; + uint32_t temp; + MQTT_INFO("MQTT:InitConnection\r\n"); + os_memset(mqttClient, 0, sizeof(MQTT_Client)); + temp = os_strlen(host); + mqttClient->host = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->host, host); + mqttClient->host[temp] = 0; + mqttClient->port = port; + mqttClient->security = security; } /** * @brief MQTT initialization mqtt client function - * @param client: MQTT_Client reference - * @param clientid: MQTT client id + * @param client: MQTT_Client reference + * @param clientid: MQTT client id * @param client_user:MQTT client user * @param client_pass:MQTT client password * @param client_pass:MQTT keep alive timer, in second @@ -759,66 +784,66 @@ MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8 void ICACHE_FLASH_ATTR MQTT_InitClient(MQTT_Client *mqttClient, uint8_t* client_id, uint8_t* client_user, uint8_t* client_pass, uint32_t keepAliveTime, uint8_t cleanSession) { - uint32_t temp; - INFO("MQTT:InitClient\r\n"); + uint32_t temp; + MQTT_INFO("MQTT:InitClient\r\n"); - os_memset(&mqttClient->connect_info, 0, sizeof(mqtt_connect_info_t)); + os_memset(&mqttClient->connect_info, 0, sizeof(mqtt_connect_info_t)); - temp = os_strlen(client_id); - mqttClient->connect_info.client_id = (uint8_t*)os_zalloc(temp + 1); - os_strcpy(mqttClient->connect_info.client_id, client_id); - mqttClient->connect_info.client_id[temp] = 0; + temp = os_strlen(client_id); + mqttClient->connect_info.client_id = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.client_id, client_id); + mqttClient->connect_info.client_id[temp] = 0; - if (client_user) - { - temp = os_strlen(client_user); - mqttClient->connect_info.username = (uint8_t*)os_zalloc(temp + 1); - os_strcpy(mqttClient->connect_info.username, client_user); - mqttClient->connect_info.username[temp] = 0; - } + if (client_user) + { + temp = os_strlen(client_user); + mqttClient->connect_info.username = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.username, client_user); + mqttClient->connect_info.username[temp] = 0; + } - if (client_pass) - { - temp = os_strlen(client_pass); - mqttClient->connect_info.password = (uint8_t*)os_zalloc(temp + 1); - os_strcpy(mqttClient->connect_info.password, client_pass); - mqttClient->connect_info.password[temp] = 0; - } + if (client_pass) + { + temp = os_strlen(client_pass); + mqttClient->connect_info.password = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.password, client_pass); + mqttClient->connect_info.password[temp] = 0; + } - mqttClient->connect_info.keepalive = keepAliveTime; - mqttClient->connect_info.clean_session = cleanSession; + mqttClient->connect_info.keepalive = keepAliveTime; + mqttClient->connect_info.clean_session = cleanSession; - mqttClient->mqtt_state.in_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE); - mqttClient->mqtt_state.in_buffer_length = MQTT_BUF_SIZE; - mqttClient->mqtt_state.out_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE); - mqttClient->mqtt_state.out_buffer_length = MQTT_BUF_SIZE; - mqttClient->mqtt_state.connect_info = &mqttClient->connect_info; + mqttClient->mqtt_state.in_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE); + mqttClient->mqtt_state.in_buffer_length = MQTT_BUF_SIZE; + mqttClient->mqtt_state.out_buffer = (uint8_t *)os_zalloc(MQTT_BUF_SIZE); + mqttClient->mqtt_state.out_buffer_length = MQTT_BUF_SIZE; + mqttClient->mqtt_state.connect_info = &mqttClient->connect_info; - mqtt_msg_init(&mqttClient->mqtt_state.mqtt_connection, mqttClient->mqtt_state.out_buffer, mqttClient->mqtt_state.out_buffer_length); + mqtt_msg_init(&mqttClient->mqtt_state.mqtt_connection, mqttClient->mqtt_state.out_buffer, mqttClient->mqtt_state.out_buffer_length); - QUEUE_Init(&mqttClient->msgQueue, QUEUE_BUFFER_SIZE); + QUEUE_Init(&mqttClient->msgQueue, QUEUE_BUFFER_SIZE); - system_os_task(MQTT_Task, MQTT_TASK_PRIO, mqtt_procTaskQueue, MQTT_TASK_QUEUE_SIZE); - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + system_os_task(MQTT_Task, MQTT_TASK_PRIO, mqtt_procTaskQueue, MQTT_TASK_QUEUE_SIZE); + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); } void ICACHE_FLASH_ATTR MQTT_InitLWT(MQTT_Client *mqttClient, uint8_t* will_topic, uint8_t* will_msg, uint8_t will_qos, uint8_t will_retain) { - uint32_t temp; - temp = os_strlen(will_topic); - mqttClient->connect_info.will_topic = (uint8_t*)os_zalloc(temp + 1); - os_strcpy(mqttClient->connect_info.will_topic, will_topic); - mqttClient->connect_info.will_topic[temp] = 0; + uint32_t temp; + temp = os_strlen(will_topic); + mqttClient->connect_info.will_topic = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.will_topic, will_topic); + mqttClient->connect_info.will_topic[temp] = 0; - temp = os_strlen(will_msg); - mqttClient->connect_info.will_message = (uint8_t*)os_zalloc(temp + 1); - os_strcpy(mqttClient->connect_info.will_message, will_msg); - mqttClient->connect_info.will_message[temp] = 0; + temp = os_strlen(will_msg); + mqttClient->connect_info.will_message = (uint8_t*)os_zalloc(temp + 1); + os_strcpy(mqttClient->connect_info.will_message, will_msg); + mqttClient->connect_info.will_message[temp] = 0; - mqttClient->connect_info.will_qos = will_qos; - mqttClient->connect_info.will_retain = will_retain; + mqttClient->connect_info.will_qos = will_qos; + mqttClient->connect_info.will_retain = will_retain; } /** * @brief Begin connect to MQTT broker @@ -828,103 +853,103 @@ MQTT_InitLWT(MQTT_Client *mqttClient, uint8_t* will_topic, uint8_t* will_msg, ui void ICACHE_FLASH_ATTR MQTT_Connect(MQTT_Client *mqttClient) { - if (mqttClient->pCon) { - // Clean up the old connection forcefully - using MQTT_Disconnect - // does not actually release the old connection until the - // disconnection callback is invoked. - mqtt_tcpclient_delete(mqttClient); - } - mqttClient->pCon = (struct espconn *)os_zalloc(sizeof(struct espconn)); - mqttClient->pCon->type = ESPCONN_TCP; - mqttClient->pCon->state = ESPCONN_NONE; - mqttClient->pCon->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp)); - mqttClient->pCon->proto.tcp->local_port = espconn_port(); - mqttClient->pCon->proto.tcp->remote_port = mqttClient->port; - mqttClient->pCon->reverse = mqttClient; - espconn_regist_connectcb(mqttClient->pCon, mqtt_tcpclient_connect_cb); - espconn_regist_reconcb(mqttClient->pCon, mqtt_tcpclient_recon_cb); + if (mqttClient->pCon) { + // Clean up the old connection forcefully - using MQTT_Disconnect + // does not actually release the old connection until the + // disconnection callback is invoked. + mqtt_tcpclient_delete(mqttClient); + } + mqttClient->pCon = (struct espconn *)os_zalloc(sizeof(struct espconn)); + mqttClient->pCon->type = ESPCONN_TCP; + mqttClient->pCon->state = ESPCONN_NONE; + mqttClient->pCon->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp)); + mqttClient->pCon->proto.tcp->local_port = espconn_port(); + mqttClient->pCon->proto.tcp->remote_port = mqttClient->port; + mqttClient->pCon->reverse = mqttClient; + espconn_regist_connectcb(mqttClient->pCon, mqtt_tcpclient_connect_cb); + espconn_regist_reconcb(mqttClient->pCon, mqtt_tcpclient_recon_cb); - mqttClient->keepAliveTick = 0; - mqttClient->reconnectTick = 0; + mqttClient->keepAliveTick = 0; + mqttClient->reconnectTick = 0; - os_timer_disarm(&mqttClient->mqttTimer); - os_timer_setfn(&mqttClient->mqttTimer, (os_timer_func_t *)mqtt_timer, mqttClient); - os_timer_arm(&mqttClient->mqttTimer, 1000, 1); + os_timer_disarm(&mqttClient->mqttTimer); + os_timer_setfn(&mqttClient->mqttTimer, (os_timer_func_t *)mqtt_timer, mqttClient); + os_timer_arm(&mqttClient->mqttTimer, 1000, 1); - if (UTILS_StrToIP(mqttClient->host, &mqttClient->pCon->proto.tcp->remote_ip)) { - INFO("TCP: Connect to ip %s:%d\r\n", mqttClient->host, mqttClient->port); - if (mqttClient->security) - { + if (UTILS_StrToIP(mqttClient->host, &mqttClient->pCon->proto.tcp->remote_ip)) { + MQTT_INFO("TCP: Connect to ip %s:%d\r\n", mqttClient->host, mqttClient->port); + if (mqttClient->security) + { #ifdef MQTT_SSL_ENABLE - espconn_secure_connect(mqttClient->pCon); + espconn_secure_connect(mqttClient->pCon); #else - INFO("TCP: Do not support SSL\r\n"); + MQTT_INFO("TCP: Do not support SSL\r\n"); #endif - } - else - { - espconn_connect(mqttClient->pCon); - } - } - else { - INFO("TCP: Connect to domain %s:%d\r\n", mqttClient->host, mqttClient->port); - espconn_gethostbyname(mqttClient->pCon, mqttClient->host, &mqttClient->ip, mqtt_dns_found); - } - mqttClient->connState = TCP_CONNECTING; + } + else + { + espconn_connect(mqttClient->pCon); + } + } + else { + MQTT_INFO("TCP: Connect to domain %s:%d\r\n", mqttClient->host, mqttClient->port); + espconn_gethostbyname(mqttClient->pCon, mqttClient->host, &mqttClient->ip, mqtt_dns_found); + } + mqttClient->connState = TCP_CONNECTING; } void ICACHE_FLASH_ATTR MQTT_Disconnect(MQTT_Client *mqttClient) { - mqttClient->connState = TCP_DISCONNECTING; - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); - os_timer_disarm(&mqttClient->mqttTimer); + mqttClient->connState = TCP_DISCONNECTING; + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + os_timer_disarm(&mqttClient->mqttTimer); } void ICACHE_FLASH_ATTR MQTT_DeleteClient(MQTT_Client *mqttClient) { - if(NULL == mqttClient) - return; + if (NULL == mqttClient) + return; - mqttClient->connState = MQTT_DELETED; - // if(TCP_DISCONNECTED == mqttClient->connState) { - // mqttClient->connState = MQTT_DELETED; - // } else if(MQTT_DELETED != mqttClient->connState) { - // mqttClient->connState = MQTT_DELETING; - // } + mqttClient->connState = MQTT_DELETED; + // if(TCP_DISCONNECTED == mqttClient->connState) { + // mqttClient->connState = MQTT_DELETED; + // } else if(MQTT_DELETED != mqttClient->connState) { + // mqttClient->connState = MQTT_DELETING; + // } - system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); - os_timer_disarm(&mqttClient->mqttTimer); + system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)mqttClient); + os_timer_disarm(&mqttClient->mqttTimer); } void ICACHE_FLASH_ATTR MQTT_OnConnected(MQTT_Client *mqttClient, MqttCallback connectedCb) { - mqttClient->connectedCb = connectedCb; + mqttClient->connectedCb = connectedCb; } void ICACHE_FLASH_ATTR MQTT_OnDisconnected(MQTT_Client *mqttClient, MqttCallback disconnectedCb) { - mqttClient->disconnectedCb = disconnectedCb; + mqttClient->disconnectedCb = disconnectedCb; } void ICACHE_FLASH_ATTR MQTT_OnData(MQTT_Client *mqttClient, MqttDataCallback dataCb) { - mqttClient->dataCb = dataCb; + mqttClient->dataCb = dataCb; } void ICACHE_FLASH_ATTR MQTT_OnPublished(MQTT_Client *mqttClient, MqttCallback publishedCb) { - mqttClient->publishedCb = publishedCb; + mqttClient->publishedCb = publishedCb; } void ICACHE_FLASH_ATTR MQTT_OnTimeout(MQTT_Client *mqttClient, MqttCallback timeoutCb) { - mqttClient->timeoutCb = timeoutCb; + mqttClient->timeoutCb = timeoutCb; } diff --git a/mqtt/mqtt_msg.c b/mqtt/mqtt_msg.c index b6c78e5..565322a 100644 --- a/mqtt/mqtt_msg.c +++ b/mqtt/mqtt_msg.c @@ -62,7 +62,7 @@ struct __attribute((__packed__)) mqtt_connect_variable_header static int ICACHE_FLASH_ATTR append_string(mqtt_connection_t* connection, const char* string, int len) { - if(connection->message.length + len + 2 > connection->buffer_length) + if (connection->message.length + len + 2 > connection->buffer_length) return -1; connection->buffer[connection->message.length++] = len >> 8; @@ -77,10 +77,10 @@ static uint16_t ICACHE_FLASH_ATTR append_message_id(mqtt_connection_t* connectio { // If message_id is zero then we should assign one, otherwise // we'll use the one supplied by the caller - while(message_id == 0) + while (message_id == 0) message_id = ++connection->message_id; - if(connection->message.length + 2 > connection->buffer_length) + if (connection->message.length + 2 > connection->buffer_length) return 0; connection->buffer[connection->message.length++] = message_id >> 8; @@ -106,7 +106,7 @@ static mqtt_message_t* ICACHE_FLASH_ATTR fini_message(mqtt_connection_t* connect { int remaining_length = connection->message.length - MQTT_MAX_FIXED_HEADER_SIZE; - if(remaining_length > 127) + if (remaining_length > 127) { connection->buffer[0] = ((type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1); connection->buffer[1] = 0x80 | (remaining_length % 128); @@ -137,10 +137,10 @@ int ICACHE_FLASH_ATTR mqtt_get_total_length(uint8_t* buffer, uint16_t length) int i; int totlen = 0; - for(i = 1; i < length; ++i) + for (i = 1; i < length; ++i) { totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); - if((buffer[i] & 0x80) == 0) + if ((buffer[i] & 0x80) == 0) { ++i; break; @@ -157,10 +157,10 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t* int totlen = 0; int topiclen; - for(i = 1; i < *length; ++i) + for (i = 1; i < *length; ++i) { - totlen += (buffer[i] & 0x7f) << (7 * (i -1)); - if((buffer[i] & 0x80) == 0) + totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); + if ((buffer[i] & 0x80) == 0) { ++i; break; @@ -168,12 +168,12 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t* } totlen += i; - if(i + 2 >= *length) + if (i + 2 >= *length) return NULL; topiclen = buffer[i++] << 8; topiclen |= buffer[i++]; - if(i + topiclen > *length) + if (i + topiclen > *length) return NULL; *length = topiclen; @@ -188,10 +188,10 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* l int blength = *length; *length = 0; - for(i = 1; i < blength; ++i) + for (i = 1; i < blength; ++i) { totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); - if((buffer[i] & 0x80) == 0) + if ((buffer[i] & 0x80) == 0) { ++i; break; @@ -199,27 +199,27 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* l } totlen += i; - if(i + 2 >= blength) + if (i + 2 >= blength) return NULL; topiclen = buffer[i++] << 8; topiclen |= buffer[i++]; - if(i + topiclen >= blength) + if (i + topiclen >= blength) return NULL; i += topiclen; - if(mqtt_get_qos(buffer) > 0) + if (mqtt_get_qos(buffer) > 0) { - if(i + 2 >= blength) + if (i + 2 >= blength) return NULL; i += 2; } - if(totlen < i) + if (totlen < i) return NULL; - if(totlen <= blength) + if (totlen <= blength) *length = totlen - i; else *length = blength - i; @@ -228,45 +228,45 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* l uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length) { - if(length < 1) + if (length < 1) return 0; - switch(mqtt_get_type(buffer)) + switch (mqtt_get_type(buffer)) { case MQTT_MSG_TYPE_PUBLISH: - { - int i; - int topiclen; - - for(i = 1; i < length; ++i) { - if((buffer[i] & 0x80) == 0) + int i; + int topiclen; + + for (i = 1; i < length; ++i) { - ++i; - break; + if ((buffer[i] & 0x80) == 0) + { + ++i; + break; + } } - } - if(i + 2 >= length) - return 0; - topiclen = buffer[i++] << 8; - topiclen |= buffer[i++]; - - if(i + topiclen >= length) - return 0; - i += topiclen; - - if(mqtt_get_qos(buffer) > 0) - { - if(i + 2 >= length) + if (i + 2 >= length) return 0; - //i += 2; - } else { - return 0; - } + topiclen = buffer[i++] << 8; + topiclen |= buffer[i++]; - return (buffer[i] << 8) | buffer[i + 1]; - } + if (i + topiclen >= length) + return 0; + i += topiclen; + + if (mqtt_get_qos(buffer) > 0) + { + if (i + 2 >= length) + return 0; + //i += 2; + } else { + return 0; + } + + return (buffer[i] << 8) | buffer[i + 1]; + } case MQTT_MSG_TYPE_PUBACK: case MQTT_MSG_TYPE_PUBREC: case MQTT_MSG_TYPE_PUBREL: @@ -274,14 +274,14 @@ uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length) case MQTT_MSG_TYPE_SUBACK: case MQTT_MSG_TYPE_UNSUBACK: case MQTT_MSG_TYPE_SUBSCRIBE: - { - // This requires the remaining length to be encoded in 1 byte, - // which it should be. - if(length >= 4 && (buffer[1] & 0x80) == 0) - return (buffer[2] << 8) | buffer[3]; - else - return 0; - } + { + // This requires the remaining length to be encoded in 1 byte, + // which it should be. + if (length >= 4 && (buffer[1] & 0x80) == 0) + return (buffer[2] << 8) | buffer[3]; + else + return 0; + } default: return 0; @@ -294,7 +294,7 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection init_message(connection); - if(connection->message.length + sizeof(*variable_header) > connection->buffer_length) + if (connection->message.length + sizeof(*variable_header) > connection->buffer_length) return fail_message(connection); variable_header = (void*)(connection->buffer + connection->message.length); connection->message.length += sizeof(*variable_header); @@ -316,42 +316,42 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection variable_header->keepaliveMsb = info->keepalive >> 8; variable_header->keepaliveLsb = info->keepalive & 0xff; - if(info->clean_session) + if (info->clean_session) variable_header->flags |= MQTT_CONNECT_FLAG_CLEAN_SESSION; - if(info->client_id != NULL && info->client_id[0] != '\0') + if (info->client_id != NULL && info->client_id[0] != '\0') { - if(append_string(connection, info->client_id, strlen(info->client_id)) < 0) + if (append_string(connection, info->client_id, strlen(info->client_id)) < 0) return fail_message(connection); } else return fail_message(connection); - if(info->will_topic != NULL && info->will_topic[0] != '\0') + if (info->will_topic != NULL && info->will_topic[0] != '\0') { - if(append_string(connection, info->will_topic, strlen(info->will_topic)) < 0) + if (append_string(connection, info->will_topic, strlen(info->will_topic)) < 0) return fail_message(connection); - if(append_string(connection, info->will_message, strlen(info->will_message)) < 0) + if (append_string(connection, info->will_message, strlen(info->will_message)) < 0) return fail_message(connection); variable_header->flags |= MQTT_CONNECT_FLAG_WILL; - if(info->will_retain) + if (info->will_retain) variable_header->flags |= MQTT_CONNECT_FLAG_WILL_RETAIN; variable_header->flags |= (info->will_qos & 3) << 3; } - if(info->username != NULL && info->username[0] != '\0') + if (info->username != NULL && info->username[0] != '\0') { - if(append_string(connection, info->username, strlen(info->username)) < 0) + if (append_string(connection, info->username, strlen(info->username)) < 0) return fail_message(connection); variable_header->flags |= MQTT_CONNECT_FLAG_USERNAME; } - if(info->password != NULL && info->password[0] != '\0') + if (info->password != NULL && info->password[0] != '\0') { - if(append_string(connection, info->password, strlen(info->password)) < 0) + if (append_string(connection, info->password, strlen(info->password)) < 0) return fail_message(connection); variable_header->flags |= MQTT_CONNECT_FLAG_PASSWORD; @@ -364,21 +364,21 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_publish(mqtt_connection_t* connection { init_message(connection); - if(topic == NULL || topic[0] == '\0') + if (topic == NULL || topic[0] == '\0') return fail_message(connection); - if(append_string(connection, topic, strlen(topic)) < 0) + if (append_string(connection, topic, strlen(topic)) < 0) return fail_message(connection); - if(qos > 0) + if (qos > 0) { - if((*message_id = append_message_id(connection, 0)) == 0) + if ((*message_id = append_message_id(connection, 0)) == 0) return fail_message(connection); } else *message_id = 0; - if(connection->message.length + data_length > connection->buffer_length) + if (connection->message.length + data_length > connection->buffer_length) return fail_message(connection); memcpy(connection->buffer + connection->message.length, data, data_length); connection->message.length += data_length; @@ -389,7 +389,7 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_publish(mqtt_connection_t* connection mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, uint16_t message_id) { init_message(connection); - if(append_message_id(connection, message_id) == 0) + if (append_message_id(connection, message_id) == 0) return fail_message(connection); return fini_message(connection, MQTT_MSG_TYPE_PUBACK, 0, 0, 0); } @@ -397,7 +397,7 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, uint16_t message_id) { init_message(connection); - if(append_message_id(connection, message_id) == 0) + if (append_message_id(connection, message_id) == 0) return fail_message(connection); return fini_message(connection, MQTT_MSG_TYPE_PUBREC, 0, 0, 0); } @@ -405,7 +405,7 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, uint16_t message_id) { init_message(connection); - if(append_message_id(connection, message_id) == 0) + if (append_message_id(connection, message_id) == 0) return fail_message(connection); return fini_message(connection, MQTT_MSG_TYPE_PUBREL, 0, 1, 0); } @@ -413,7 +413,7 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubcomp(mqtt_connection_t* connection, uint16_t message_id) { init_message(connection); - if(append_message_id(connection, message_id) == 0) + if (append_message_id(connection, message_id) == 0) return fail_message(connection); return fini_message(connection, MQTT_MSG_TYPE_PUBCOMP, 0, 0, 0); } @@ -422,16 +422,16 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_subscribe(mqtt_connection_t* connecti { init_message(connection); - if(topic == NULL || topic[0] == '\0') + if (topic == NULL || topic[0] == '\0') return fail_message(connection); - if((*message_id = append_message_id(connection, 0)) == 0) + if ((*message_id = append_message_id(connection, 0)) == 0) return fail_message(connection); - if(append_string(connection, topic, strlen(topic)) < 0) + if (append_string(connection, topic, strlen(topic)) < 0) return fail_message(connection); - if(connection->message.length + 1 > connection->buffer_length) + if (connection->message.length + 1 > connection->buffer_length) return fail_message(connection); connection->buffer[connection->message.length++] = qos; @@ -442,13 +442,13 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_unsubscribe(mqtt_connection_t* connec { init_message(connection); - if(topic == NULL || topic[0] == '\0') + if (topic == NULL || topic[0] == '\0') return fail_message(connection); - if((*message_id = append_message_id(connection, 0)) == 0) + if ((*message_id = append_message_id(connection, 0)) == 0) return fail_message(connection); - if(append_string(connection, topic, strlen(topic)) < 0) + if (append_string(connection, topic, strlen(topic)) < 0) return fail_message(connection); return fini_message(connection, MQTT_MSG_TYPE_UNSUBSCRIBE, 0, 1, 0); diff --git a/mqtt/proto.c b/mqtt/proto.c index d3e2292..84078b2 100644 --- a/mqtt/proto.c +++ b/mqtt/proto.c @@ -2,128 +2,128 @@ #include "ringbuf.h" I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize) { - parser->buf = buf; - parser->bufSize = bufSize; - parser->dataLen = 0; - parser->callback = completeCallback; - parser->isEsc = 0; - return 0; + parser->buf = buf; + parser->bufSize = bufSize; + parser->dataLen = 0; + parser->callback = completeCallback; + parser->isEsc = 0; + return 0; } I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value) -{ - switch(value){ - case 0x7D: - parser->isEsc = 1; - break; - - case 0x7E: - parser->dataLen = 0; - parser->isEsc = 0; - parser->isBegin = 1; - break; - - case 0x7F: - if (parser->callback != NULL) - parser->callback(); - parser->isBegin = 0; - return 0; - break; - - default: - if(parser->isBegin == 0) break; - - if(parser->isEsc){ - value ^= 0x20; - parser->isEsc = 0; - } - - if(parser->dataLen < parser->bufSize) - parser->buf[parser->dataLen++] = value; - - break; - } - return -1; +{ + switch (value) { + case 0x7D: + parser->isEsc = 1; + break; + + case 0x7E: + parser->dataLen = 0; + parser->isEsc = 0; + parser->isBegin = 1; + break; + + case 0x7F: + if (parser->callback != NULL) + parser->callback(); + parser->isBegin = 0; + return 0; + break; + + default: + if (parser->isBegin == 0) break; + + if (parser->isEsc) { + value ^= 0x20; + parser->isEsc = 0; + } + + if (parser->dataLen < parser->bufSize) + parser->buf[parser->dataLen++] = value; + + break; + } + return -1; } I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len) { - while(len--) - PROTO_ParseByte(parser, *buf++); + while (len--) + PROTO_ParseByte(parser, *buf++); - return 0; + return 0; } I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF* rb, U8 *bufOut, U16* len, U16 maxBufLen) { - U8 c; + U8 c; - PROTO_PARSER proto; - PROTO_Init(&proto, NULL, bufOut, maxBufLen); - while(RINGBUF_Get(rb, &c) == 0){ - if(PROTO_ParseByte(&proto, c) == 0){ - *len = proto.dataLen; - return 0; - } - } - return -1; + PROTO_PARSER proto; + PROTO_Init(&proto, NULL, bufOut, maxBufLen); + while (RINGBUF_Get(rb, &c) == 0) { + if (PROTO_ParseByte(&proto, c) == 0) { + *len = proto.dataLen; + return 0; + } + } + return -1; } I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize) { - U16 i = 2; - U16 len = *(U16*) packet; + U16 i = 2; + U16 len = *(U16*) packet; - if (bufSize < 1) return -1; + if (bufSize < 1) return -1; - *buf++ = 0x7E; - bufSize--; + *buf++ = 0x7E; + bufSize--; - while (len--) { - switch (*packet) { - case 0x7D: - case 0x7E: - case 0x7F: - if (bufSize < 2) return -1; - *buf++ = 0x7D; - *buf++ = *packet++ ^ 0x20; - i += 2; - bufSize -= 2; - break; - default: - if (bufSize < 1) return -1; - *buf++ = *packet++; - i++; - bufSize--; - break; - } + while (len--) { + switch (*packet) { + case 0x7D: + case 0x7E: + case 0x7F: + if (bufSize < 2) return -1; + *buf++ = 0x7D; + *buf++ = *packet++ ^ 0x20; + i += 2; + bufSize -= 2; + break; + default: + if (bufSize < 1) return -1; + *buf++ = *packet++; + i++; + bufSize--; + break; } + } - if (bufSize < 1) return -1; - *buf++ = 0x7F; + if (bufSize < 1) return -1; + *buf++ = 0x7F; - return i; + return i; } I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len) { - U16 i = 2; - if(RINGBUF_Put(rb, 0x7E) == -1) return -1; - while (len--) { - switch (*packet) { - case 0x7D: - case 0x7E: - case 0x7F: - if(RINGBUF_Put(rb, 0x7D) == -1) return -1; - if(RINGBUF_Put(rb, *packet++ ^ 0x20) == -1) return -1; - i += 2; - break; - default: - if(RINGBUF_Put(rb, *packet++) == -1) return -1; - i++; - break; - } + U16 i = 2; + if (RINGBUF_Put(rb, 0x7E) == -1) return -1; + while (len--) { + switch (*packet) { + case 0x7D: + case 0x7E: + case 0x7F: + if (RINGBUF_Put(rb, 0x7D) == -1) return -1; + if (RINGBUF_Put(rb, *packet++ ^ 0x20) == -1) return -1; + i += 2; + break; + default: + if (RINGBUF_Put(rb, *packet++) == -1) return -1; + i++; + break; } - if(RINGBUF_Put(rb, 0x7F) == -1) return -1; + } + if (RINGBUF_Put(rb, 0x7F) == -1) return -1; - return i; + return i; } diff --git a/mqtt/queue.c b/mqtt/queue.c index b6add16..7fa50aa 100644 --- a/mqtt/queue.c +++ b/mqtt/queue.c @@ -36,22 +36,22 @@ #include "proto.h" void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize) { - queue->buf = (uint8_t*)os_zalloc(bufferSize); - RINGBUF_Init(&queue->rb, queue->buf, bufferSize); + queue->buf = (uint8_t*)os_zalloc(bufferSize); + RINGBUF_Init(&queue->rb, queue->buf, bufferSize); } int32_t ICACHE_FLASH_ATTR QUEUE_Puts(QUEUE *queue, uint8_t* buffer, uint16_t len) { - return PROTO_AddRb(&queue->rb, buffer, len); + return PROTO_AddRb(&queue->rb, buffer, len); } int32_t ICACHE_FLASH_ATTR QUEUE_Gets(QUEUE *queue, uint8_t* buffer, uint16_t* len, uint16_t maxLen) { - return PROTO_ParseRb(&queue->rb, buffer, len, maxLen); + return PROTO_ParseRb(&queue->rb, buffer, len, maxLen); } BOOL ICACHE_FLASH_ATTR QUEUE_IsEmpty(QUEUE *queue) { - if(queue->rb.fill_cnt<=0) - return TRUE; - return FALSE; + if (queue->rb.fill_cnt <= 0) + return TRUE; + return FALSE; } diff --git a/mqtt/ringbuf.c b/mqtt/ringbuf.c index 5ac3d07..fc882fd 100644 --- a/mqtt/ringbuf.c +++ b/mqtt/ringbuf.c @@ -1,6 +1,6 @@ /** * \file -* Ring Buffer library +* Ring Buffer library */ #include "ringbuf.h" @@ -15,13 +15,13 @@ */ I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size) { - if(r == NULL || buf == NULL || size < 2) return -1; - - r->p_o = r->p_r = r->p_w = buf; - r->fill_cnt = 0; - r->size = size; - - return 0; + if (r == NULL || buf == NULL || size < 2) return -1; + + r->p_o = r->p_r = r->p_w = buf; + r->fill_cnt = 0; + r->size = size; + + return 0; } /** * \brief put a character into ring buffer @@ -31,18 +31,18 @@ I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size) */ I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c) { - if(r->fill_cnt>=r->size)return -1; // ring buffer is full, this should be atomic operation - + if (r->fill_cnt >= r->size)return -1; // ring buffer is full, this should be atomic operation - r->fill_cnt++; // increase filled slots count, this should be atomic operation - - *r->p_w++ = c; // put character into buffer - - if(r->p_w >= r->p_o + r->size) // rollback if write pointer go pass - r->p_w = r->p_o; // the physical boundary - - return 0; + r->fill_cnt++; // increase filled slots count, this should be atomic operation + + + *r->p_w++ = c; // put character into buffer + + if (r->p_w >= r->p_o + r->size) // rollback if write pointer go pass + r->p_w = r->p_o; // the physical boundary + + return 0; } /** * \brief get a character from ring buffer @@ -52,16 +52,16 @@ I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c) */ I16 ICACHE_FLASH_ATTR RINGBUF_Get(RINGBUF *r, U8* c) { - if(r->fill_cnt<=0)return -1; // ring buffer is empty, this should be atomic operation - + if (r->fill_cnt <= 0)return -1; // ring buffer is empty, this should be atomic operation - r->fill_cnt--; // decrease filled slots count - - *c = *r->p_r++; // get the character out - - if(r->p_r >= r->p_o + r->size) // rollback if write pointer go pass - r->p_r = r->p_o; // the physical boundary - - return 0; + r->fill_cnt--; // decrease filled slots count + + + *c = *r->p_r++; // get the character out + + if (r->p_r >= r->p_o + r->size) // rollback if write pointer go pass + r->p_r = r->p_o; // the physical boundary + + return 0; } diff --git a/mqtt/utils.c b/mqtt/utils.c index 3ed7e50..ac4c927 100644 --- a/mqtt/utils.c +++ b/mqtt/utils.c @@ -40,110 +40,110 @@ uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str) { - uint8_t segs = 0; /* Segment count. */ - uint8_t chcnt = 0; /* Character count within segment. */ - uint8_t accum = 0; /* Accumulator for segment. */ - /* Catch NULL pointer. */ - if (str == 0) + uint8_t segs = 0; /* Segment count. */ + uint8_t chcnt = 0; /* Character count within segment. */ + uint8_t accum = 0; /* Accumulator for segment. */ + /* Catch NULL pointer. */ + if (str == 0) + return 0; + /* Process every character in string. */ + + while (*str != '\0') { + /* Segment changeover. */ + + if (*str == '.') { + /* Must have some digits in segment. */ + if (chcnt == 0) return 0; - /* Process every character in string. */ - - while (*str != '\0') { - /* Segment changeover. */ - - if (*str == '.') { - /* Must have some digits in segment. */ - if (chcnt == 0) - return 0; - /* Limit number of segments. */ - if (++segs == 4) - return 0; - /* Reset segment values and restart loop. */ - chcnt = accum = 0; - str++; - continue; - } - - /* Check numeric. */ - if ((*str < '0') || (*str > '9')) - return 0; - - /* Accumulate and check segment. */ - - if ((accum = accum * 10 + *str - '0') > 255) - return 0; - /* Advance other segment specific stuff and continue loop. */ - - chcnt++; - str++; + /* Limit number of segments. */ + if (++segs == 4) + return 0; + /* Reset segment values and restart loop. */ + chcnt = accum = 0; + str++; + continue; } - /* Check enough segments and enough characters in last segment. */ + /* Check numeric. */ + if ((*str < '0') || (*str > '9')) + return 0; - if (segs != 3) - return 0; - if (chcnt == 0) - return 0; - /* Address okay. */ + /* Accumulate and check segment. */ - return 1; + if ((accum = accum * 10 + *str - '0') > 255) + return 0; + /* Advance other segment specific stuff and continue loop. */ + + chcnt++; + str++; + } + + /* Check enough segments and enough characters in last segment. */ + + if (segs != 3) + return 0; + if (chcnt == 0) + return 0; + /* Address okay. */ + + return 1; } uint8_t ICACHE_FLASH_ATTR UTILS_StrToIP(const int8_t* str, void *ip) { - /* The count of the number of bytes processed. */ - int i; - /* A pointer to the next digit to process. */ - const char * start; + /* The count of the number of bytes processed. */ + int i; + /* A pointer to the next digit to process. */ + const char * start; - start = str; - for (i = 0; i < 4; i++) { - /* The digit being processed. */ - char c; - /* The value of this byte. */ - int n = 0; - while (1) { - c = * start; - start++; - if (c >= '0' && c <= '9') { - n *= 10; - n += c - '0'; - } - /* We insist on stopping at "." if we are still parsing - the first, second, or third numbers. If we have reached - the end of the numbers, we will allow any character. */ - else if ((i < 3 && c == '.') || i == 3) { - break; - } - else { - return 0; - } - } - if (n >= 256) { - return 0; - } - ((uint8_t*)ip)[i] = n; - } - return 1; + start = str; + for (i = 0; i < 4; i++) { + /* The digit being processed. */ + char c; + /* The value of this byte. */ + int n = 0; + while (1) { + c = * start; + start++; + if (c >= '0' && c <= '9') { + n *= 10; + n += c - '0'; + } + /* We insist on stopping at "." if we are still parsing + the first, second, or third numbers. If we have reached + the end of the numbers, we will allow any character. */ + else if ((i < 3 && c == '.') || i == 3) { + break; + } + else { + return 0; + } + } + if (n >= 256) { + return 0; + } + ((uint8_t*)ip)[i] = n; + } + return 1; } uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s) { - uint32_t value = 0, digit; - int8_t c; - - while((c = *s++)){ - if('0' <= c && c <= '9') - digit = c - '0'; - else if('A' <= c && c <= 'F') - digit = c - 'A' + 10; - else if('a' <= c && c<= 'f') - digit = c - 'a' + 10; - else break; - - value = (value << 4) | digit; - } - - return value; + uint32_t value = 0, digit; + int8_t c; + + while ((c = *s++)) { + if ('0' <= c && c <= '9') + digit = c - '0'; + else if ('A' <= c && c <= 'F') + digit = c - 'A' + 10; + else if ('a' <= c && c <= 'f') + digit = c - 'a' + 10; + else break; + + value = (value << 4) | digit; + } + + return value; } diff --git a/user/rfinit.c b/user/rfinit.c index 3f342ac..64aabf2 100644 --- a/user/rfinit.c +++ b/user/rfinit.c @@ -1,76 +1,76 @@ -/****************************************************************************** - * Copyright 2016 Vowstar - * - * FileName: init.c - * - * Description: System and user APP initialization. - * - * Modification history: - * 2016/03/24, v1.0 create this file. -*******************************************************************************/ - -#include "ets_sys.h" -#include "osapi.h" -#include "user_interface.h" - - /****************************************************************************** - * FunctionName : user_rf_cal_sector_set - * Description : SDK just reversed 4 sectors, used for rf init data and paramters. - * We add this function to force users to set rf cal sector, since - * we don't know which sector is free in user's application. - * sector map for last several sectors : ABCCC - * A : rf cal - * B : rf init data - * C : sdk parameters - * Parameters : none - * Returns : rf cal sector -*******************************************************************************/ -uint32 ICACHE_FLASH_ATTR __attribute__((weak)) -user_rf_cal_sector_set(void) -{ - enum flash_size_map size_map = system_get_flash_size_map(); - uint32 rf_cal_sec = 0; - - switch (size_map) { - case FLASH_SIZE_4M_MAP_256_256: - rf_cal_sec = 128 - 5; - break; - - case FLASH_SIZE_8M_MAP_512_512: - rf_cal_sec = 256 - 5; - break; - - case FLASH_SIZE_16M_MAP_512_512: - case FLASH_SIZE_16M_MAP_1024_1024: - rf_cal_sec = 512 - 5; - break; - - case FLASH_SIZE_32M_MAP_512_512: - case FLASH_SIZE_32M_MAP_1024_1024: - rf_cal_sec = 1024 - 5; - break; - - default: - rf_cal_sec = 0; - break; - } - - return rf_cal_sec; -} - -void __attribute__((weak)) -user_rf_pre_init(void) -{ - // Warning: IF YOU DON'T KNOW WHAT YOU ARE DOING, DON'T TOUCH THESE CODE - - // Control RF_CAL by esp_init_data_default.bin(0~127byte) 108 byte when wakeup - // Will low current - // system_phy_set_rfoption(0); - - // Process RF_CAL when wakeup. - // Will high current - system_phy_set_rfoption(1); - - // Set Wi-Fi Tx Power, Unit: 0.25dBm, Range: [0, 82] - system_phy_set_max_tpw(82); -} +/****************************************************************************** + * Copyright 2016 Vowstar + * + * FileName: init.c + * + * Description: System and user APP initialization. + * + * Modification history: + * 2016/03/24, v1.0 create this file. +*******************************************************************************/ + +#include "ets_sys.h" +#include "osapi.h" +#include "user_interface.h" + +/****************************************************************************** +* FunctionName : user_rf_cal_sector_set +* Description : SDK just reversed 4 sectors, used for rf init data and paramters. +* We add this function to force users to set rf cal sector, since +* we don't know which sector is free in user's application. +* sector map for last several sectors : ABCCC +* A : rf cal +* B : rf init data +* C : sdk parameters +* Parameters : none +* Returns : rf cal sector +*******************************************************************************/ +uint32 ICACHE_FLASH_ATTR __attribute__((weak)) +user_rf_cal_sector_set(void) +{ + enum flash_size_map size_map = system_get_flash_size_map(); + uint32 rf_cal_sec = 0; + + switch (size_map) { + case FLASH_SIZE_4M_MAP_256_256: + rf_cal_sec = 128 - 5; + break; + + case FLASH_SIZE_8M_MAP_512_512: + rf_cal_sec = 256 - 5; + break; + + case FLASH_SIZE_16M_MAP_512_512: + case FLASH_SIZE_16M_MAP_1024_1024: + rf_cal_sec = 512 - 5; + break; + + case FLASH_SIZE_32M_MAP_512_512: + case FLASH_SIZE_32M_MAP_1024_1024: + rf_cal_sec = 1024 - 5; + break; + + default: + rf_cal_sec = 0; + break; + } + + return rf_cal_sec; +} + +void __attribute__((weak)) +user_rf_pre_init(void) +{ + // Warning: IF YOU DON'T KNOW WHAT YOU ARE DOING, DON'T TOUCH THESE CODE + + // Control RF_CAL by esp_init_data_default.bin(0~127byte) 108 byte when wakeup + // Will low current + // system_phy_set_rfoption(0); + + // Process RF_CAL when wakeup. + // Will high current + system_phy_set_rfoption(1); + + // Set Wi-Fi Tx Power, Unit: 0.25dBm, Range: [0, 82] + system_phy_set_max_tpw(82); +} diff --git a/user/user_main.c b/user/user_main.c index 0f10655..8436b6a 100644 --- a/user/user_main.c +++ b/user/user_main.c @@ -36,87 +36,90 @@ #include "gpio.h" #include "user_interface.h" #include "mem.h" -#include "config.h" MQTT_Client mqttClient; - static void ICACHE_FLASH_ATTR wifiConnectCb(uint8_t status) { - if(status == STATION_GOT_IP){ - MQTT_Connect(&mqttClient); - } else { - MQTT_Disconnect(&mqttClient); - } + if (status == STATION_GOT_IP) { + MQTT_Connect(&mqttClient); + } else { + MQTT_Disconnect(&mqttClient); + } } static void ICACHE_FLASH_ATTR mqttConnectedCb(uint32_t *args) { - MQTT_Client* client = (MQTT_Client*)args; - INFO("MQTT: Connected\r\n"); - MQTT_Subscribe(client, "/mqtt/topic/0", 0); - MQTT_Subscribe(client, "/mqtt/topic/1", 1); - MQTT_Subscribe(client, "/mqtt/topic/2", 2); + MQTT_Client* client = (MQTT_Client*)args; + INFO("MQTT: Connected\r\n"); + MQTT_Subscribe(client, "/mqtt/topic/0", 0); + MQTT_Subscribe(client, "/mqtt/topic/1", 1); + MQTT_Subscribe(client, "/mqtt/topic/2", 2); - MQTT_Publish(client, "/mqtt/topic/0", "hello0", 6, 0, 0); - MQTT_Publish(client, "/mqtt/topic/1", "hello1", 6, 1, 0); - MQTT_Publish(client, "/mqtt/topic/2", "hello2", 6, 2, 0); + MQTT_Publish(client, "/mqtt/topic/0", "hello0", 6, 0, 0); + MQTT_Publish(client, "/mqtt/topic/1", "hello1", 6, 1, 0); + MQTT_Publish(client, "/mqtt/topic/2", "hello2", 6, 2, 0); } static void ICACHE_FLASH_ATTR mqttDisconnectedCb(uint32_t *args) { - MQTT_Client* client = (MQTT_Client*)args; - INFO("MQTT: Disconnected\r\n"); + MQTT_Client* client = (MQTT_Client*)args; + INFO("MQTT: Disconnected\r\n"); } static void ICACHE_FLASH_ATTR mqttPublishedCb(uint32_t *args) { - MQTT_Client* client = (MQTT_Client*)args; - INFO("MQTT: Published\r\n"); + MQTT_Client* client = (MQTT_Client*)args; + INFO("MQTT: Published\r\n"); } static void ICACHE_FLASH_ATTR mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len) { - char *topicBuf = (char*)os_zalloc(topic_len+1), - *dataBuf = (char*)os_zalloc(data_len+1); + char *topicBuf = (char*)os_zalloc(topic_len + 1), + *dataBuf = (char*)os_zalloc(data_len + 1); - MQTT_Client* client = (MQTT_Client*)args; + MQTT_Client* client = (MQTT_Client*)args; + os_memcpy(topicBuf, topic, topic_len); + topicBuf[topic_len] = 0; + os_memcpy(dataBuf, data, data_len); + dataBuf[data_len] = 0; + INFO("Receive topic: %s, data: %s \r\n", topicBuf, dataBuf); + os_free(topicBuf); + os_free(dataBuf); +} - os_memcpy(topicBuf, topic, topic_len); - topicBuf[topic_len] = 0; +void ICACHE_FLASH_ATTR print_info() +{ + INFO("\r\n\r\n[INFO] BOOTUP...\r\n"); + INFO("[INFO] SDK: %s\r\n", system_get_sdk_version()); + INFO("[INFO] Chip ID: %08X\r\n", system_get_chip_id()); + INFO("[INFO] Memory info:\r\n"); + system_print_meminfo(); - os_memcpy(dataBuf, data, data_len); - dataBuf[data_len] = 0; + INFO("[INFO] -------------------------------------------\n"); + INFO("[INFO] Build time: %s\n", BUID_TIME); + INFO("[INFO] -------------------------------------------\n"); - INFO("Receive topic: %s, data: %s \r\n", topicBuf, dataBuf); - os_free(topicBuf); - os_free(dataBuf); } static void ICACHE_FLASH_ATTR app_init(void) { - uart_init(BIT_RATE_115200, BIT_RATE_115200); - // os_delay_us(1000000); + uart_init(BIT_RATE_115200, BIT_RATE_115200); + print_info(); + MQTT_InitConnection(&mqttClient, MQTT_HOST, MQTT_PORT, DEFAULT_SECURITY); + //MQTT_InitConnection(&mqttClient, "192.168.11.122", 1880, 0); - CFG_Load(); + MQTT_InitClient(&mqttClient, MQTT_CLIENT_ID, MQTT_USER, MQTT_PASS, MQTT_KEEPALIVE, MQTT_CLEAN_SESSION); + //MQTT_InitClient(&mqttClient, "client_id", "user", "pass", 120, 1); + MQTT_InitLWT(&mqttClient, "/lwt", "offline", 0, 0); + MQTT_OnConnected(&mqttClient, mqttConnectedCb); + MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb); + MQTT_OnPublished(&mqttClient, mqttPublishedCb); + MQTT_OnData(&mqttClient, mqttDataCb); - MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, sysCfg.security); - //MQTT_InitConnection(&mqttClient, "192.168.11.122", 1880, 0); - - MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive, 1); - //MQTT_InitClient(&mqttClient, "client_id", "user", "pass", 120, 1); - - MQTT_InitLWT(&mqttClient, "/lwt", "offline", 0, 0); - MQTT_OnConnected(&mqttClient, mqttConnectedCb); - MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb); - MQTT_OnPublished(&mqttClient, mqttPublishedCb); - MQTT_OnData(&mqttClient, mqttDataCb); - - WIFI_Connect(sysCfg.sta_ssid, sysCfg.sta_pwd, wifiConnectCb); - - INFO("\r\nSystem started ...\r\n"); + WIFI_Connect(STA_SSID, STA_PASS, wifiConnectCb); } void user_init(void) { - system_init_done_cb(app_init); + system_init_done_cb(app_init); }