-reformat code using space 2

- fix bug connect callback when connection refuse
- change INFO to MQTT_INFO to resolve conflic with global INFO define
develop
Tuan PM 2016-09-09 22:37:03 +07:00
rodzic 4acdfe0a5d
commit 30523fbe90
28 zmienionych plików z 1697 dodań i 1637 usunięć

20
.editorconfig 100644
Wyświetl plik

@ -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

Wyświetl plik

@ -28,8 +28,8 @@ ESP_MODE = dio
ESP_SIZE = 32m ESP_SIZE = 32m
VERBOSE = no VERBOSE = yes
FLAVOR = release FLAVOR = debug
# name for the target project # name for the target project
TARGET ?= esp_mqtt TARGET ?= esp_mqtt
@ -110,6 +110,7 @@ LDFLAGS = -nostdlib -Wl,--no-check-sections -u call_user_start -Wl,-static
ifeq ($(FLAVOR),debug) ifeq ($(FLAVOR),debug)
LDFLAGS += -g -O2 LDFLAGS += -g -O2
CFLAGS += -DMQTT_DEBUG_ON -DDEBUG_ON
endif endif
ifeq ($(FLAVOR),release) ifeq ($(FLAVOR),release)
@ -212,7 +213,7 @@ flash:
$(ESPTOOL) $(ESPTOOL_OPTS) $(ESPTOOL_WRITE) $(ESPTOOL) $(ESPTOOL_OPTS) $(ESPTOOL_WRITE)
fast: all flash openport fast: all flash openport
openport: openport:
$(vecho) "After flash, terminal will enter serial port screen" $(vecho) "After flash, terminal will enter serial port screen"
$(vecho) "Please exit with command:" $(vecho) "Please exit with command:"

102
README.md
Wyświetl plik

@ -24,7 +24,7 @@ This is MQTT client library for ESP8266, port from: [MQTT client library for Con
**Compile:** **Compile:**
- Copy file `include/user_config.sample.h` to `include/user_config.local.h` and change settings, included: SSID, PASS, MQTT configurations ... - 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 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** **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** **Publish message and Subscribe**
@ -157,9 +68,7 @@ MQTT_InitLWT(&mqttClient, "/lwt", "offline", 0, 0);
See: **include/user_config.sample.h** 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.local.h**
**Define protocol name in include/user_config.h**
```c ```c
#define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/ #define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/
@ -221,17 +130,16 @@ function setup() {
``` ```
**Example projects using esp_mqtt:** **Example projects using esp_mqtt:**
- [https://github.com/eadf/esp_mqtt_lcd](https://github.com/eadf/esp_mqtt_lcd) - [https://github.com/eadf/esp_mqtt_lcd](https://github.com/eadf/esp_mqtt_lcd)
[MQTT Broker for test](https://github.com/mcollina/mosca) [MQTT Broker for test](https://github.com/mcollina/mosca)
[MQTT Client for test](https://chrome.google.com/webstore/detail/mqttlens/hemojaaeigabkbcookmlgmdigohjobjm?hl=en) [MQTT Client for test](https://chrome.google.com/webstore/detail/mqttlens/hemojaaeigabkbcookmlgmdigohjobjm?hl=en)
**Contributing:** **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:** **Authors:**

Wyświetl plik

@ -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 indentclasses
// 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": []
}
}

Wyświetl plik

@ -14,23 +14,12 @@
#include "driver/uart.h" #include "driver/uart.h"
#include "osapi.h" #include "osapi.h"
#include "driver/uart_register.h" #include "driver/uart_register.h"
//#include "ssc.h" #include "mem.h"
// UartDev is defined and initialized in rom code. // UartDev is defined and initialized in rom code.
extern UartDevice UartDev; extern UartDevice UartDev;
//extern os_event_t at_recvTaskQueue[at_recvTaskQueueLen];
LOCAL void uart0_rx_intr_handler(void *para); 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 LOCAL void ICACHE_FLASH_ATTR
uart_config(uint8 uart_no) 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); 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); 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) if (uart_no == UART0)
{ {
//set rx fifo trigger //set rx fifo trigger
WRITE_PERI_REG(UART_CONF1(uart_no), WRITE_PERI_REG(UART_CONF1(uart_no),
((0x10 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | ((0x7F & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) |
((0x10 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) | //((128 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) |
UART_RX_FLOW_EN | //UART_RX_FLOW_EN |
(0x02 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S | ((0x0F & UART_TXFIFO_EMPTY_THRHD) << UART_TXFIFO_EMPTY_THRHD_S));
UART_RX_TOUT_EN); //UART_RX_TOUT_EN);
SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_TOUT_INT_ENA | SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_TOUT_INT_ENA | UART_FRM_ERR_INT_ENA);
UART_FRM_ERR_INT_ENA);
} }
else else
{ {
@ -84,38 +68,23 @@ uart_config(uint8 uart_no)
//clear all interrupt //clear all interrupt
WRITE_PERI_REG(UART_INT_CLR(uart_no), 0xffff); WRITE_PERI_REG(UART_INT_CLR(uart_no), 0xffff);
//enable rx_interrupt //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 LOCAL STATUS
uart_tx_one_char(uint8 uart, uint8 TxChar) uart_tx_one_char(uint8 uart, uint8 TxChar)
{ {
while (true) while (true)
{ {
uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT<<UART_TXFIFO_CNT_S); 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) { if ((fifo_cnt >> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) < 126) {
break; break;
}
} }
}
WRITE_PERI_REG(UART_FIFO(uart) , TxChar); WRITE_PERI_REG(UART_FIFO(uart) , TxChar);
return OK; 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 void ICACHE_FLASH_ATTR
uart1_write_char(char c) uart1_write_char(char c)
{ {
@ -149,13 +118,7 @@ uart0_write_char(char c)
uart_tx_one_char(UART0, 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 void ICACHE_FLASH_ATTR
uart0_tx_buffer(uint8 *buf, uint16 len) 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 void ICACHE_FLASH_ATTR
uart0_sendStr(const char *str) uart0_sendStr(const char *str)
{ {
while(*str) while (*str)
{ {
uart_tx_one_char(UART0, *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 LOCAL void
uart0_rx_intr_handler(void *para) 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 RcvChar;
uint8 uart_no = UART0;//UartDev.buff_uart_no; uint8 uart_no = UART0;//UartDev.buff_uart_no;
/* Is the frame Error interrupt set ? */
// if (UART_RXFIFO_FULL_INT_ST != (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)) if (UART_FRM_ERR_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_FRM_ERR_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))
{ {
os_printf("FRM_ERR\r\n"); //INFO("FRM_ERR\r\n");
WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_FRM_ERR_INT_CLR); WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_FRM_ERR_INT_CLR);
} }
else if (UART_RXFIFO_FULL_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)) /*fifo full*/
if(UART_RXFIFO_FULL_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST))
{ {
// os_printf("fifo full\r\n"); CLEAR_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA | UART_RXFIFO_TOUT_INT_ENA);
ETS_UART_INTR_DISABLE();///////// 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"); else if (UART_RXFIFO_OVF_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_OVF_INT_ST))
// while (READ_PERI_REG(UART_STATUS(uart_no)) & (UART_RXFIFO_CNT << UART_RXFIFO_CNT_S)) {
// { //INFO("FIFO FULL\n");
//// os_printf("process recv\r\n"); WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_RXFIFO_OVF_INT_CLR);
//// at_recvTask(); }
// RcvChar = READ_PERI_REG(UART_FIFO(uart_no)) & 0xFF; else if (UART_TXFIFO_EMPTY_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_TXFIFO_EMPTY_INT_ST)) {
// system_os_post(at_recvTaskPrio, NULL, RcvChar); //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); ETS_UART_INTR_ENABLE();
// 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 ;
// }
// }
} }
/******************************************************************************
* 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 void ICACHE_FLASH_ATTR
uart_init(UartBautRate uart0_br, UartBautRate uart1_br) uart_init(UartBautRate uart0_br, UartBautRate uart1_br)
{ {
// rom use 74880 baut_rate, here reinitialize
UartDev.baut_rate = uart0_br; UartDev.baut_rate = uart0_br;
uart_config(UART0); uart_config(UART0);
UartDev.baut_rate = uart1_br; UartDev.baut_rate = uart1_br;
@ -301,7 +207,5 @@ uart_init(UartBautRate uart0_br, UartBautRate uart1_br)
void ICACHE_FLASH_ATTR void ICACHE_FLASH_ATTR
uart_reattach() uart_reattach()
{ {
uart_init(BIT_RATE_74880, BIT_RATE_74880); uart_init(BIT_RATE_115200, BIT_RATE_115200);
// ETS_UART_INTR_ATTACH(uart_rx_intr_handler_ssc, &(UartDev.rcv_buff));
// ETS_UART_INTR_ENABLE();
} }

Wyświetl plik

@ -82,10 +82,10 @@ typedef enum {
} RcvMsgState; } RcvMsgState;
typedef struct { typedef struct {
UartBautRate baut_rate; UartBautRate baut_rate;
UartBitsNum4Char data_bits; UartBitsNum4Char data_bits;
UartExistParity exist_parity; UartExistParity exist_parity;
UartParityMode parity; // chip size in byte UartParityMode parity; // chip size in byte
UartStopBitsNum stop_bits; UartStopBitsNum stop_bits;
UartFlowCtrl flow_ctrl; UartFlowCtrl flow_ctrl;
RcvMsgBuff rcv_buff; RcvMsgBuff rcv_buff;

Wyświetl plik

@ -1,13 +1,13 @@
#ifndef __USER_CONFIG_H__ #ifndef __USER_CONFIG_H__
#define __USER_CONFIG_H__ #define __USER_CONFIG_H__
#define USE_OPTIMIZE_PRINTF #define USE_OPTIMIZE_PRINTF
#ifndef LOCAL_CONFIG_AVAILABLE #ifndef LOCAL_CONFIG_AVAILABLE
#error Please copy user_config.sample.h to user_config.local.h and modify your configurations #error Please copy user_config.sample.h to user_config.local.h and modify your configurations
#else #else
#include "user_config.local.h" #include "user_config.local.h"
#endif #endif
#endif #endif

Wyświetl plik

@ -1,31 +1,36 @@
#ifndef __MQTT_CONFIG_H__ #ifndef __MQTT_CONFIG_H__
#define __MQTT_CONFIG_H__ #define __MQTT_CONFIG_H__
#define CFG_HOLDER 0x00FF55A5 /* Change this value to load default configurations */ #define MQTT_SSL_ENABLE
#define CFG_LOCATION 0x3C /* Please don't change or if you know what you doing */
#define MQTT_SSL_ENABLE /*DEFAULT CONFIGURATIONS*/
/*DEFAULT CONFIGURATIONS*/ #define MQTT_HOST "192.168.0.101" //or "mqtt.yourdomain.com"
#define MQTT_PORT 1883
#define MQTT_HOST "192.168.1.100" //or "mqtt.yourdomain.com" #define MQTT_BUF_SIZE 1024
#define MQTT_PORT 1883 #define MQTT_KEEPALIVE 120 /*second*/
#define MQTT_BUF_SIZE 1024
#define MQTT_KEEPALIVE 120 /*second*/ #define MQTT_CLIENT_ID "CLIENT_1234"
#define MQTT_USER "USER"
#define MQTT_CLIENT_ID "CLIENT_%08X" #define MQTT_PASS "PASS"
#define MQTT_USER "USER" #define MQTT_CLEAN_SESSION 1
#define MQTT_PASS "PASS" #define MQTT_KEEPALIVE 120
#define STA_SSID "SSID" #define STA_SSID "SSID"
#define STA_PASS "PASSWORD" #define STA_PASS "PASS"
#define STA_TYPE AUTH_WPA2_PSK
#define MQTT_RECONNECT_TIMEOUT 5 /*second*/
#define MQTT_RECONNECT_TIMEOUT 5 /*second*/
#define DEFAULT_SECURITY 0
#define DEFAULT_SECURITY 0 #define QUEUE_BUFFER_SIZE 2048
#define QUEUE_BUFFER_SIZE 2048
#define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/
#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/*/
//PROTOCOL_NAMEv311 /*MQTT version 3.11 compatible with https://eclipse.org/paho/clients/testing/*/
#if defined(DEBUG_ON)
#endif // __MQTT_CONFIG_H__ #define INFO( format, ... ) os_printf( format, ## __VA_ARGS__ )
#else
#define INFO( format, ... )
#endif
#endif // __MQTT_CONFIG_H__

Wyświetl plik

@ -1,110 +0,0 @@
/*
/* config.c
*
* Copyright (c) 2014-2015, Tuan PM <tuanpm at live dot com>
* 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();
}
}

Wyświetl plik

@ -1,61 +0,0 @@
/* config.h
*
* Copyright (c) 2014-2015, Tuan PM <tuanpm at live dot com>
* 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_ */

Wyświetl plik

@ -10,6 +10,4 @@
#include "os_type.h" #include "os_type.h"
typedef void (*WifiCallback)(uint8_t); typedef void (*WifiCallback)(uint8_t);
void ICACHE_FLASH_ATTR WIFI_Connect(uint8_t* ssid, uint8_t* pass, WifiCallback cb); void ICACHE_FLASH_ATTR WIFI_Connect(uint8_t* ssid, uint8_t* pass, WifiCallback cb);
#endif /* USER_WIFI_H_ */ #endif /* USER_WIFI_H_ */

Wyświetl plik

@ -13,88 +13,67 @@
#include "mqtt_msg.h" #include "mqtt_msg.h"
#include "debug.h" #include "debug.h"
#include "user_config.h" #include "user_config.h"
#include "config.h"
static ETSTimer WiFiLinker; static ETSTimer WiFiLinker;
WifiCallback wifiCb = NULL; WifiCallback wifiCb = NULL;
static uint8_t wifiStatus = STATION_IDLE, lastWifiStatus = STATION_IDLE; static uint8_t wifiStatus = STATION_IDLE, lastWifiStatus = STATION_IDLE;
static void ICACHE_FLASH_ATTR wifi_check_ip(void *arg) 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); os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL);
wifi_get_ip_info(STATION_IF, &ipConfig); os_timer_arm(&WiFiLinker, 500, 0);
wifiStatus = wifi_station_get_connect_status(); }
if (wifiStatus == STATION_GOT_IP && ipConfig.ip.addr != 0) if (wifiStatus != lastWifiStatus) {
{ lastWifiStatus = wifiStatus;
if (wifiCb)
os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL); wifiCb(wifiStatus);
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);
}
} }
void ICACHE_FLASH_ATTR WIFI_Connect(uint8_t* ssid, uint8_t* pass, WifiCallback cb) 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"); INFO("WIFI_INIT\r\n");
wifi_set_opmode_current(STATION_MODE); wifi_set_opmode_current(STATION_MODE);
wifiCb = cb;
//wifi_station_set_auto_connect(FALSE); os_memset(&stationConf, 0, sizeof(struct station_config));
wifiCb = cb; os_sprintf(stationConf.ssid, "%s", ssid);
os_sprintf(stationConf.password, "%s", pass);
os_memset(&stationConf, 0, sizeof(struct station_config)); wifi_station_set_config_current(&stationConf);
os_timer_disarm(&WiFiLinker);
os_sprintf(stationConf.ssid, "%s", ssid); os_timer_setfn(&WiFiLinker, (os_timer_func_t *)wifi_check_ip, NULL);
os_sprintf(stationConf.password, "%s", pass); os_timer_arm(&WiFiLinker, 1000, 0);
wifi_station_connect();
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();
} }

Wyświetl plik

@ -8,16 +8,12 @@
#ifndef USER_DEBUG_H_ #ifndef USER_DEBUG_H_
#define USER_DEBUG_H_ #define USER_DEBUG_H_
#if defined(GLOBAL_DEBUG_ON)
#define MQTT_DEBUG_ON
#endif
#if defined(MQTT_DEBUG_ON) #if defined(MQTT_DEBUG_ON)
#define INFO( format, ... ) os_printf( format, ## __VA_ARGS__ ) #define MQTT_INFO( format, ... ) os_printf( format, ## __VA_ARGS__ )
#else #else
#define INFO( format, ... ) #define MQTT_INFO( format, ... )
#endif #endif
// #ifndef INFO
// #define INFO os_printf
// #endif
#endif /* USER_DEBUG_H_ */ #endif /* USER_DEBUG_H_ */

Wyświetl plik

@ -63,71 +63,71 @@ typedef struct mqtt_state_t
} mqtt_state_t; } mqtt_state_t;
typedef enum { typedef enum {
WIFI_INIT, WIFI_INIT,
WIFI_CONNECTING, WIFI_CONNECTING,
WIFI_CONNECTING_ERROR, WIFI_CONNECTING_ERROR,
WIFI_CONNECTED, WIFI_CONNECTED,
DNS_RESOLVE, DNS_RESOLVE,
TCP_DISCONNECTING, TCP_DISCONNECTING,
TCP_DISCONNECTED, TCP_DISCONNECTED,
TCP_RECONNECT_DISCONNECTING, TCP_RECONNECT_DISCONNECTING,
TCP_RECONNECT_REQ, TCP_RECONNECT_REQ,
TCP_RECONNECT, TCP_RECONNECT,
TCP_CONNECTING, TCP_CONNECTING,
TCP_CONNECTING_ERROR, TCP_CONNECTING_ERROR,
TCP_CONNECTED, TCP_CONNECTED,
MQTT_CONNECT_SEND, MQTT_CONNECT_SEND,
MQTT_CONNECT_SENDING, MQTT_CONNECT_SENDING,
MQTT_SUBSCIBE_SEND, MQTT_SUBSCIBE_SEND,
MQTT_SUBSCIBE_SENDING, MQTT_SUBSCIBE_SENDING,
MQTT_DATA, MQTT_DATA,
MQTT_KEEPALIVE_SEND, MQTT_KEEPALIVE_SEND,
MQTT_PUBLISH_RECV, MQTT_PUBLISH_RECV,
MQTT_PUBLISHING, MQTT_PUBLISHING,
MQTT_DELETING, MQTT_DELETING,
MQTT_DELETED, MQTT_DELETED,
} tConnState; } tConnState;
typedef void (*MqttCallback)(uint32_t *args); 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 void (*MqttDataCallback)(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t lengh);
typedef struct { typedef struct {
struct espconn *pCon; struct espconn *pCon;
uint8_t security; uint8_t security;
uint8_t* host; uint8_t* host;
uint32_t port; uint32_t port;
ip_addr_t ip; ip_addr_t ip;
mqtt_state_t mqtt_state; mqtt_state_t mqtt_state;
mqtt_connect_info_t connect_info; mqtt_connect_info_t connect_info;
MqttCallback connectedCb; MqttCallback connectedCb;
MqttCallback disconnectedCb; MqttCallback disconnectedCb;
MqttCallback publishedCb; MqttCallback publishedCb;
MqttCallback timeoutCb; MqttCallback timeoutCb;
MqttDataCallback dataCb; MqttDataCallback dataCb;
ETSTimer mqttTimer; ETSTimer mqttTimer;
uint32_t keepAliveTick; uint32_t keepAliveTick;
uint32_t reconnectTick; uint32_t reconnectTick;
uint32_t sendTimeout; uint32_t sendTimeout;
tConnState connState; tConnState connState;
QUEUE msgQueue; QUEUE msgQueue;
void* user_data; void* user_data;
} MQTT_Client; } MQTT_Client;
#define SEC_NONSSL 0 #define SEC_NONSSL 0
#define SEC_SSL 1 #define SEC_SSL 1
#define MQTT_FLAG_CONNECTED 1 #define MQTT_FLAG_CONNECTED 1
#define MQTT_FLAG_READY 2 #define MQTT_FLAG_READY 2
#define MQTT_FLAG_EXIT 4 #define MQTT_FLAG_EXIT 4
#define MQTT_EVENT_TYPE_NONE 0 #define MQTT_EVENT_TYPE_NONE 0
#define MQTT_EVENT_TYPE_CONNECTED 1 #define MQTT_EVENT_TYPE_CONNECTED 1
#define MQTT_EVENT_TYPE_DISCONNECTED 2 #define MQTT_EVENT_TYPE_DISCONNECTED 2
#define MQTT_EVENT_TYPE_SUBSCRIBED 3 #define MQTT_EVENT_TYPE_SUBSCRIBED 3
#define MQTT_EVENT_TYPE_UNSUBSCRIBED 4 #define MQTT_EVENT_TYPE_UNSUBSCRIBED 4
#define MQTT_EVENT_TYPE_PUBLISH 5 #define MQTT_EVENT_TYPE_PUBLISH 5
#define MQTT_EVENT_TYPE_PUBLISHED 6 #define MQTT_EVENT_TYPE_PUBLISHED 6
#define MQTT_EVENT_TYPE_EXITED 7 #define MQTT_EVENT_TYPE_EXITED 7
#define MQTT_EVENT_TYPE_PUBLISH_CONTINUATION 8 #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); void ICACHE_FLASH_ATTR MQTT_InitConnection(MQTT_Client *mqttClient, uint8_t* host, uint32_t port, uint8_t security);

Wyświetl plik

@ -1,4 +1,4 @@
/* /*
* File: mqtt_msg.h * File: mqtt_msg.h
* Author: Minh Tuan * Author: Minh Tuan
* *
@ -6,10 +6,10 @@
*/ */
#ifndef MQTT_MSG_H #ifndef MQTT_MSG_H
#define MQTT_MSG_H #define MQTT_MSG_H
#include "user_config.h" #include "user_config.h"
#include "c_types.h" #include "c_types.h"
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
@ -43,9 +43,9 @@ extern "C" {
* POSSIBILITY OF SUCH DAMAGE. * POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
/* 7 6 5 4 3 2 1 0*/ /* 7 6 5 4 3 2 1 0*/
/*| --- Message Type---- | DUP Flag | QoS Level | Retain | /*| --- Message Type---- | DUP Flag | QoS Level | Retain |
/* Remaining Length */ /* Remaining Length */
enum mqtt_message_type enum mqtt_message_type
@ -66,6 +66,16 @@ enum mqtt_message_type
MQTT_MSG_TYPE_DISCONNECT = 14 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 typedef struct mqtt_message
{ {
uint8_t* data; 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_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_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_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); } 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); mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_disconnect(mqtt_connection_t* connection);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* MQTT_MSG_H */ #endif /* MQTT_MSG_H */

Wyświetl plik

@ -1,4 +1,4 @@
/* /*
* File: proto.h * File: proto.h
* Author: ThuHien * Author: ThuHien
* *
@ -6,21 +6,21 @@
*/ */
#ifndef _PROTO_H_ #ifndef _PROTO_H_
#define _PROTO_H_ #define _PROTO_H_
#include <stdlib.h> #include <stdlib.h>
#include "typedef.h" #include "typedef.h"
#include "ringbuf.h" #include "ringbuf.h"
typedef void(PROTO_PARSE_CALLBACK)(); typedef void(PROTO_PARSE_CALLBACK)();
typedef struct{ typedef struct {
U8 *buf; U8 *buf;
U16 bufSize; U16 bufSize;
U16 dataLen; U16 dataLen;
U8 isEsc; U8 isEsc;
U8 isBegin; U8 isBegin;
PROTO_PARSE_CALLBACK* callback; PROTO_PARSE_CALLBACK* callback;
}PROTO_PARSER; } PROTO_PARSER;
I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize); 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); I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len);

Wyświetl plik

@ -33,8 +33,8 @@
#include "os_type.h" #include "os_type.h"
#include "ringbuf.h" #include "ringbuf.h"
typedef struct { typedef struct {
uint8_t *buf; uint8_t *buf;
RINGBUF rb; RINGBUF rb;
} QUEUE; } QUEUE;
void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize); void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize);

Wyświetl plik

@ -5,13 +5,13 @@
#include <stdlib.h> #include <stdlib.h>
#include "typedef.h" #include "typedef.h"
typedef struct{ typedef struct {
U8* p_o; /**< Original pointer */ U8* p_o; /**< Original pointer */
U8* volatile p_r; /**< Read pointer */ U8* volatile p_r; /**< Read pointer */
U8* volatile p_w; /**< Write pointer */ U8* volatile p_w; /**< Write pointer */
volatile I32 fill_cnt; /**< Number of filled slots */ volatile I32 fill_cnt; /**< Number of filled slots */
I32 size; /**< Buffer size */ I32 size; /**< Buffer size */
}RINGBUF; } RINGBUF;
I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size); I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size);
I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c); I16 ICACHE_FLASH_ATTR RINGBUF_Put(RINGBUF *r, U8 c);

Wyświetl plik

@ -1,6 +1,6 @@
/** /**
* \file * \file
* Standard Types definition * Standard Types definition
*/ */
#ifndef _TYPE_DEF_H_ #ifndef _TYPE_DEF_H_

Wyświetl plik

@ -1,5 +1,5 @@
#ifndef _UTILS_H_ #ifndef _UTILS_H_
#define _UTILS_H_ #define _UTILS_H_
#include "c_types.h" #include "c_types.h"

Plik diff jest za duży Load Diff

Wyświetl plik

@ -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) 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; return -1;
connection->buffer[connection->message.length++] = len >> 8; 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 // If message_id is zero then we should assign one, otherwise
// we'll use the one supplied by the caller // we'll use the one supplied by the caller
while(message_id == 0) while (message_id == 0)
message_id = ++connection->message_id; message_id = ++connection->message_id;
if(connection->message.length + 2 > connection->buffer_length) if (connection->message.length + 2 > connection->buffer_length)
return 0; return 0;
connection->buffer[connection->message.length++] = message_id >> 8; 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; 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[0] = ((type & 0x0f) << 4) | ((dup & 1) << 3) | ((qos & 3) << 1) | (retain & 1);
connection->buffer[1] = 0x80 | (remaining_length % 128); 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 i;
int totlen = 0; int totlen = 0;
for(i = 1; i < length; ++i) for (i = 1; i < length; ++i)
{ {
totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); totlen += (buffer[i] & 0x7f) << (7 * (i - 1));
if((buffer[i] & 0x80) == 0) if ((buffer[i] & 0x80) == 0)
{ {
++i; ++i;
break; break;
@ -157,10 +157,10 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t*
int totlen = 0; int totlen = 0;
int topiclen; int topiclen;
for(i = 1; i < *length; ++i) for (i = 1; i < *length; ++i)
{ {
totlen += (buffer[i] & 0x7f) << (7 * (i -1)); totlen += (buffer[i] & 0x7f) << (7 * (i - 1));
if((buffer[i] & 0x80) == 0) if ((buffer[i] & 0x80) == 0)
{ {
++i; ++i;
break; break;
@ -168,12 +168,12 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_topic(uint8_t* buffer, uint16_t*
} }
totlen += i; totlen += i;
if(i + 2 >= *length) if (i + 2 >= *length)
return NULL; return NULL;
topiclen = buffer[i++] << 8; topiclen = buffer[i++] << 8;
topiclen |= buffer[i++]; topiclen |= buffer[i++];
if(i + topiclen > *length) if (i + topiclen > *length)
return NULL; return NULL;
*length = topiclen; *length = topiclen;
@ -188,10 +188,10 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* l
int blength = *length; int blength = *length;
*length = 0; *length = 0;
for(i = 1; i < blength; ++i) for (i = 1; i < blength; ++i)
{ {
totlen += (buffer[i] & 0x7f) << (7 * (i - 1)); totlen += (buffer[i] & 0x7f) << (7 * (i - 1));
if((buffer[i] & 0x80) == 0) if ((buffer[i] & 0x80) == 0)
{ {
++i; ++i;
break; break;
@ -199,27 +199,27 @@ const char* ICACHE_FLASH_ATTR mqtt_get_publish_data(uint8_t* buffer, uint16_t* l
} }
totlen += i; totlen += i;
if(i + 2 >= blength) if (i + 2 >= blength)
return NULL; return NULL;
topiclen = buffer[i++] << 8; topiclen = buffer[i++] << 8;
topiclen |= buffer[i++]; topiclen |= buffer[i++];
if(i + topiclen >= blength) if (i + topiclen >= blength)
return NULL; return NULL;
i += topiclen; i += topiclen;
if(mqtt_get_qos(buffer) > 0) if (mqtt_get_qos(buffer) > 0)
{ {
if(i + 2 >= blength) if (i + 2 >= blength)
return NULL; return NULL;
i += 2; i += 2;
} }
if(totlen < i) if (totlen < i)
return NULL; return NULL;
if(totlen <= blength) if (totlen <= blength)
*length = totlen - i; *length = totlen - i;
else else
*length = blength - i; *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) uint16_t ICACHE_FLASH_ATTR mqtt_get_id(uint8_t* buffer, uint16_t length)
{ {
if(length < 1) if (length < 1)
return 0; return 0;
switch(mqtt_get_type(buffer)) switch (mqtt_get_type(buffer))
{ {
case MQTT_MSG_TYPE_PUBLISH: 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; if ((buffer[i] & 0x80) == 0)
break; {
++i;
break;
}
} }
}
if(i + 2 >= length) 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)
return 0; return 0;
//i += 2; topiclen = buffer[i++] << 8;
} else { topiclen |= buffer[i++];
return 0;
}
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_PUBACK:
case MQTT_MSG_TYPE_PUBREC: case MQTT_MSG_TYPE_PUBREC:
case MQTT_MSG_TYPE_PUBREL: 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_SUBACK:
case MQTT_MSG_TYPE_UNSUBACK: case MQTT_MSG_TYPE_UNSUBACK:
case MQTT_MSG_TYPE_SUBSCRIBE: case MQTT_MSG_TYPE_SUBSCRIBE:
{ {
// This requires the remaining length to be encoded in 1 byte, // This requires the remaining length to be encoded in 1 byte,
// which it should be. // which it should be.
if(length >= 4 && (buffer[1] & 0x80) == 0) if (length >= 4 && (buffer[1] & 0x80) == 0)
return (buffer[2] << 8) | buffer[3]; return (buffer[2] << 8) | buffer[3];
else else
return 0; return 0;
} }
default: default:
return 0; return 0;
@ -294,7 +294,7 @@ mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection
init_message(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); return fail_message(connection);
variable_header = (void*)(connection->buffer + connection->message.length); variable_header = (void*)(connection->buffer + connection->message.length);
connection->message.length += sizeof(*variable_header); 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->keepaliveMsb = info->keepalive >> 8;
variable_header->keepaliveLsb = info->keepalive & 0xff; variable_header->keepaliveLsb = info->keepalive & 0xff;
if(info->clean_session) if (info->clean_session)
variable_header->flags |= MQTT_CONNECT_FLAG_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); return fail_message(connection);
} }
else else
return fail_message(connection); 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); 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); return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_WILL; 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 |= MQTT_CONNECT_FLAG_WILL_RETAIN;
variable_header->flags |= (info->will_qos & 3) << 3; 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); return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_USERNAME; 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); return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_PASSWORD; 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); init_message(connection);
if(topic == NULL || topic[0] == '\0') if (topic == NULL || topic[0] == '\0')
return fail_message(connection); 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 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); return fail_message(connection);
} }
else else
*message_id = 0; *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); return fail_message(connection);
memcpy(connection->buffer + connection->message.length, data, data_length); memcpy(connection->buffer + connection->message.length, data, data_length);
connection->message.length += 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) mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_puback(mqtt_connection_t* connection, uint16_t message_id)
{ {
init_message(connection); init_message(connection);
if(append_message_id(connection, message_id) == 0) if (append_message_id(connection, message_id) == 0)
return fail_message(connection); return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PUBACK, 0, 0, 0); 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) mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrec(mqtt_connection_t* connection, uint16_t message_id)
{ {
init_message(connection); init_message(connection);
if(append_message_id(connection, message_id) == 0) if (append_message_id(connection, message_id) == 0)
return fail_message(connection); return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PUBREC, 0, 0, 0); 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) mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubrel(mqtt_connection_t* connection, uint16_t message_id)
{ {
init_message(connection); init_message(connection);
if(append_message_id(connection, message_id) == 0) if (append_message_id(connection, message_id) == 0)
return fail_message(connection); return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PUBREL, 0, 1, 0); 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) mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_pubcomp(mqtt_connection_t* connection, uint16_t message_id)
{ {
init_message(connection); init_message(connection);
if(append_message_id(connection, message_id) == 0) if (append_message_id(connection, message_id) == 0)
return fail_message(connection); return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_PUBCOMP, 0, 0, 0); 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); init_message(connection);
if(topic == NULL || topic[0] == '\0') if (topic == NULL || topic[0] == '\0')
return fail_message(connection); 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); 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 fail_message(connection);
if(connection->message.length + 1 > connection->buffer_length) if (connection->message.length + 1 > connection->buffer_length)
return fail_message(connection); return fail_message(connection);
connection->buffer[connection->message.length++] = qos; 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); init_message(connection);
if(topic == NULL || topic[0] == '\0') if (topic == NULL || topic[0] == '\0')
return fail_message(connection); 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); 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 fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_UNSUBSCRIBE, 0, 1, 0); return fini_message(connection, MQTT_MSG_TYPE_UNSUBSCRIBE, 0, 1, 0);

Wyświetl plik

@ -2,128 +2,128 @@
#include "ringbuf.h" #include "ringbuf.h"
I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize) I8 ICACHE_FLASH_ATTR PROTO_Init(PROTO_PARSER *parser, PROTO_PARSE_CALLBACK *completeCallback, U8 *buf, U16 bufSize)
{ {
parser->buf = buf; parser->buf = buf;
parser->bufSize = bufSize; parser->bufSize = bufSize;
parser->dataLen = 0; parser->dataLen = 0;
parser->callback = completeCallback; parser->callback = completeCallback;
parser->isEsc = 0; parser->isEsc = 0;
return 0; return 0;
} }
I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value) I8 ICACHE_FLASH_ATTR PROTO_ParseByte(PROTO_PARSER *parser, U8 value)
{ {
switch(value){ switch (value) {
case 0x7D: case 0x7D:
parser->isEsc = 1; parser->isEsc = 1;
break; break;
case 0x7E: case 0x7E:
parser->dataLen = 0; parser->dataLen = 0;
parser->isEsc = 0; parser->isEsc = 0;
parser->isBegin = 1; parser->isBegin = 1;
break; break;
case 0x7F: case 0x7F:
if (parser->callback != NULL) if (parser->callback != NULL)
parser->callback(); parser->callback();
parser->isBegin = 0; parser->isBegin = 0;
return 0; return 0;
break; break;
default: default:
if(parser->isBegin == 0) break; if (parser->isBegin == 0) break;
if(parser->isEsc){ if (parser->isEsc) {
value ^= 0x20; value ^= 0x20;
parser->isEsc = 0; parser->isEsc = 0;
} }
if(parser->dataLen < parser->bufSize) if (parser->dataLen < parser->bufSize)
parser->buf[parser->dataLen++] = value; parser->buf[parser->dataLen++] = value;
break; break;
} }
return -1; return -1;
} }
I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len) I8 ICACHE_FLASH_ATTR PROTO_Parse(PROTO_PARSER *parser, U8 *buf, U16 len)
{ {
while(len--) while (len--)
PROTO_ParseByte(parser, *buf++); PROTO_ParseByte(parser, *buf++);
return 0; return 0;
} }
I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF* rb, U8 *bufOut, U16* len, U16 maxBufLen) I16 ICACHE_FLASH_ATTR PROTO_ParseRb(RINGBUF* rb, U8 *bufOut, U16* len, U16 maxBufLen)
{ {
U8 c; U8 c;
PROTO_PARSER proto; PROTO_PARSER proto;
PROTO_Init(&proto, NULL, bufOut, maxBufLen); PROTO_Init(&proto, NULL, bufOut, maxBufLen);
while(RINGBUF_Get(rb, &c) == 0){ while (RINGBUF_Get(rb, &c) == 0) {
if(PROTO_ParseByte(&proto, c) == 0){ if (PROTO_ParseByte(&proto, c) == 0) {
*len = proto.dataLen; *len = proto.dataLen;
return 0; return 0;
} }
} }
return -1; return -1;
} }
I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize) I16 ICACHE_FLASH_ATTR PROTO_Add(U8 *buf, const U8 *packet, I16 bufSize)
{ {
U16 i = 2; U16 i = 2;
U16 len = *(U16*) packet; U16 len = *(U16*) packet;
if (bufSize < 1) return -1; if (bufSize < 1) return -1;
*buf++ = 0x7E; *buf++ = 0x7E;
bufSize--; bufSize--;
while (len--) { while (len--) {
switch (*packet) { switch (*packet) {
case 0x7D: case 0x7D:
case 0x7E: case 0x7E:
case 0x7F: case 0x7F:
if (bufSize < 2) return -1; if (bufSize < 2) return -1;
*buf++ = 0x7D; *buf++ = 0x7D;
*buf++ = *packet++ ^ 0x20; *buf++ = *packet++ ^ 0x20;
i += 2; i += 2;
bufSize -= 2; bufSize -= 2;
break; break;
default: default:
if (bufSize < 1) return -1; if (bufSize < 1) return -1;
*buf++ = *packet++; *buf++ = *packet++;
i++; i++;
bufSize--; bufSize--;
break; break;
}
} }
}
if (bufSize < 1) return -1; if (bufSize < 1) return -1;
*buf++ = 0x7F; *buf++ = 0x7F;
return i; return i;
} }
I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len) I16 ICACHE_FLASH_ATTR PROTO_AddRb(RINGBUF *rb, const U8 *packet, I16 len)
{ {
U16 i = 2; U16 i = 2;
if(RINGBUF_Put(rb, 0x7E) == -1) return -1; if (RINGBUF_Put(rb, 0x7E) == -1) return -1;
while (len--) { while (len--) {
switch (*packet) { switch (*packet) {
case 0x7D: case 0x7D:
case 0x7E: case 0x7E:
case 0x7F: case 0x7F:
if(RINGBUF_Put(rb, 0x7D) == -1) return -1; if (RINGBUF_Put(rb, 0x7D) == -1) return -1;
if(RINGBUF_Put(rb, *packet++ ^ 0x20) == -1) return -1; if (RINGBUF_Put(rb, *packet++ ^ 0x20) == -1) return -1;
i += 2; i += 2;
break; break;
default: default:
if(RINGBUF_Put(rb, *packet++) == -1) return -1; if (RINGBUF_Put(rb, *packet++) == -1) return -1;
i++; i++;
break; break;
}
} }
if(RINGBUF_Put(rb, 0x7F) == -1) return -1; }
if (RINGBUF_Put(rb, 0x7F) == -1) return -1;
return i; return i;
} }

Wyświetl plik

@ -36,22 +36,22 @@
#include "proto.h" #include "proto.h"
void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize) void ICACHE_FLASH_ATTR QUEUE_Init(QUEUE *queue, int bufferSize)
{ {
queue->buf = (uint8_t*)os_zalloc(bufferSize); queue->buf = (uint8_t*)os_zalloc(bufferSize);
RINGBUF_Init(&queue->rb, queue->buf, bufferSize); RINGBUF_Init(&queue->rb, queue->buf, bufferSize);
} }
int32_t ICACHE_FLASH_ATTR QUEUE_Puts(QUEUE *queue, uint8_t* buffer, uint16_t len) 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) 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) BOOL ICACHE_FLASH_ATTR QUEUE_IsEmpty(QUEUE *queue)
{ {
if(queue->rb.fill_cnt<=0) if (queue->rb.fill_cnt <= 0)
return TRUE; return TRUE;
return FALSE; return FALSE;
} }

Wyświetl plik

@ -1,6 +1,6 @@
/** /**
* \file * \file
* Ring Buffer library * Ring Buffer library
*/ */
#include "ringbuf.h" #include "ringbuf.h"
@ -15,13 +15,13 @@
*/ */
I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size) I16 ICACHE_FLASH_ATTR RINGBUF_Init(RINGBUF *r, U8* buf, I32 size)
{ {
if(r == NULL || buf == NULL || size < 2) return -1; if (r == NULL || buf == NULL || size < 2) return -1;
r->p_o = r->p_r = r->p_w = buf; r->p_o = r->p_r = r->p_w = buf;
r->fill_cnt = 0; r->fill_cnt = 0;
r->size = size; r->size = size;
return 0; return 0;
} }
/** /**
* \brief put a character into ring buffer * \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) 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->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++ = c; // put character into buffer
r->p_w = r->p_o; // the physical boundary
if (r->p_w >= r->p_o + r->size) // rollback if write pointer go pass
return 0; r->p_w = r->p_o; // the physical boundary
return 0;
} }
/** /**
* \brief get a character from ring buffer * \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) 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
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 *c = *r->p_r++; // get the character out
r->p_r = r->p_o; // the physical boundary
if (r->p_r >= r->p_o + r->size) // rollback if write pointer go pass
return 0; r->p_r = r->p_o; // the physical boundary
return 0;
} }

Wyświetl plik

@ -40,110 +40,110 @@
uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str) uint8_t ICACHE_FLASH_ATTR UTILS_IsIPV4 (int8_t *str)
{ {
uint8_t segs = 0; /* Segment count. */ uint8_t segs = 0; /* Segment count. */
uint8_t chcnt = 0; /* Character count within segment. */ uint8_t chcnt = 0; /* Character count within segment. */
uint8_t accum = 0; /* Accumulator for segment. */ uint8_t accum = 0; /* Accumulator for segment. */
/* Catch NULL pointer. */ /* Catch NULL pointer. */
if (str == 0) 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; return 0;
/* Process every character in string. */ /* Limit number of segments. */
if (++segs == 4)
while (*str != '\0') { return 0;
/* Segment changeover. */ /* Reset segment values and restart loop. */
chcnt = accum = 0;
if (*str == '.') { str++;
/* Must have some digits in segment. */ continue;
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++;
} }
/* Check enough segments and enough characters in last segment. */ /* Check numeric. */
if ((*str < '0') || (*str > '9'))
return 0;
if (segs != 3) /* Accumulate and check segment. */
return 0;
if (chcnt == 0)
return 0;
/* Address okay. */
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) uint8_t ICACHE_FLASH_ATTR UTILS_StrToIP(const int8_t* str, void *ip)
{ {
/* The count of the number of bytes processed. */ /* The count of the number of bytes processed. */
int i; int i;
/* A pointer to the next digit to process. */ /* A pointer to the next digit to process. */
const char * start; const char * start;
start = str; start = str;
for (i = 0; i < 4; i++) { for (i = 0; i < 4; i++) {
/* The digit being processed. */ /* The digit being processed. */
char c; char c;
/* The value of this byte. */ /* The value of this byte. */
int n = 0; int n = 0;
while (1) { while (1) {
c = * start; c = * start;
start++; start++;
if (c >= '0' && c <= '9') { if (c >= '0' && c <= '9') {
n *= 10; n *= 10;
n += c - '0'; n += c - '0';
} }
/* We insist on stopping at "." if we are still parsing /* We insist on stopping at "." if we are still parsing
the first, second, or third numbers. If we have reached the first, second, or third numbers. If we have reached
the end of the numbers, we will allow any character. */ the end of the numbers, we will allow any character. */
else if ((i < 3 && c == '.') || i == 3) { else if ((i < 3 && c == '.') || i == 3) {
break; break;
} }
else { else {
return 0; return 0;
} }
} }
if (n >= 256) { if (n >= 256) {
return 0; return 0;
} }
((uint8_t*)ip)[i] = n; ((uint8_t*)ip)[i] = n;
} }
return 1; return 1;
} }
uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s) uint32_t ICACHE_FLASH_ATTR UTILS_Atoh(const int8_t *s)
{ {
uint32_t value = 0, digit; uint32_t value = 0, digit;
int8_t c; int8_t c;
while((c = *s++)){ while ((c = *s++)) {
if('0' <= c && c <= '9') if ('0' <= c && c <= '9')
digit = c - '0'; digit = c - '0';
else if('A' <= c && c <= 'F') else if ('A' <= c && c <= 'F')
digit = c - 'A' + 10; digit = c - 'A' + 10;
else if('a' <= c && c<= 'f') else if ('a' <= c && c <= 'f')
digit = c - 'a' + 10; digit = c - 'a' + 10;
else break; else break;
value = (value << 4) | digit; value = (value << 4) | digit;
} }
return value; return value;
} }

Wyświetl plik

@ -1,76 +1,76 @@
/****************************************************************************** /******************************************************************************
* Copyright 2016 Vowstar * Copyright 2016 Vowstar
* *
* FileName: init.c * FileName: init.c
* *
* Description: System and user APP initialization. * Description: System and user APP initialization.
* *
* Modification history: * Modification history:
* 2016/03/24, v1.0 create this file. * 2016/03/24, v1.0 create this file.
*******************************************************************************/ *******************************************************************************/
#include "ets_sys.h" #include "ets_sys.h"
#include "osapi.h" #include "osapi.h"
#include "user_interface.h" #include "user_interface.h"
/****************************************************************************** /******************************************************************************
* FunctionName : user_rf_cal_sector_set * FunctionName : user_rf_cal_sector_set
* Description : SDK just reversed 4 sectors, used for rf init data and paramters. * 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 add this function to force users to set rf cal sector, since
* we don't know which sector is free in user's application. * we don't know which sector is free in user's application.
* sector map for last several sectors : ABCCC * sector map for last several sectors : ABCCC
* A : rf cal * A : rf cal
* B : rf init data * B : rf init data
* C : sdk parameters * C : sdk parameters
* Parameters : none * Parameters : none
* Returns : rf cal sector * Returns : rf cal sector
*******************************************************************************/ *******************************************************************************/
uint32 ICACHE_FLASH_ATTR __attribute__((weak)) uint32 ICACHE_FLASH_ATTR __attribute__((weak))
user_rf_cal_sector_set(void) user_rf_cal_sector_set(void)
{ {
enum flash_size_map size_map = system_get_flash_size_map(); enum flash_size_map size_map = system_get_flash_size_map();
uint32 rf_cal_sec = 0; uint32 rf_cal_sec = 0;
switch (size_map) { switch (size_map) {
case FLASH_SIZE_4M_MAP_256_256: case FLASH_SIZE_4M_MAP_256_256:
rf_cal_sec = 128 - 5; rf_cal_sec = 128 - 5;
break; break;
case FLASH_SIZE_8M_MAP_512_512: case FLASH_SIZE_8M_MAP_512_512:
rf_cal_sec = 256 - 5; rf_cal_sec = 256 - 5;
break; break;
case FLASH_SIZE_16M_MAP_512_512: case FLASH_SIZE_16M_MAP_512_512:
case FLASH_SIZE_16M_MAP_1024_1024: case FLASH_SIZE_16M_MAP_1024_1024:
rf_cal_sec = 512 - 5; rf_cal_sec = 512 - 5;
break; break;
case FLASH_SIZE_32M_MAP_512_512: case FLASH_SIZE_32M_MAP_512_512:
case FLASH_SIZE_32M_MAP_1024_1024: case FLASH_SIZE_32M_MAP_1024_1024:
rf_cal_sec = 1024 - 5; rf_cal_sec = 1024 - 5;
break; break;
default: default:
rf_cal_sec = 0; rf_cal_sec = 0;
break; break;
} }
return rf_cal_sec; return rf_cal_sec;
} }
void __attribute__((weak)) void __attribute__((weak))
user_rf_pre_init(void) user_rf_pre_init(void)
{ {
// Warning: IF YOU DON'T KNOW WHAT YOU ARE DOING, DON'T TOUCH THESE CODE // 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 // Control RF_CAL by esp_init_data_default.bin(0~127byte) 108 byte when wakeup
// Will low current // Will low current
// system_phy_set_rfoption(0) // system_phy_set_rfoption(0)
// Process RF_CAL when wakeup. // Process RF_CAL when wakeup.
// Will high current // Will high current
system_phy_set_rfoption(1); system_phy_set_rfoption(1);
// Set Wi-Fi Tx Power, Unit: 0.25dBm, Range: [0, 82] // Set Wi-Fi Tx Power, Unit: 0.25dBm, Range: [0, 82]
system_phy_set_max_tpw(82); system_phy_set_max_tpw(82);
} }

Wyświetl plik

@ -36,87 +36,90 @@
#include "gpio.h" #include "gpio.h"
#include "user_interface.h" #include "user_interface.h"
#include "mem.h" #include "mem.h"
#include "config.h"
MQTT_Client mqttClient; MQTT_Client mqttClient;
static void ICACHE_FLASH_ATTR wifiConnectCb(uint8_t status) static void ICACHE_FLASH_ATTR wifiConnectCb(uint8_t status)
{ {
if(status == STATION_GOT_IP){ if (status == STATION_GOT_IP) {
MQTT_Connect(&mqttClient); MQTT_Connect(&mqttClient);
} else { } else {
MQTT_Disconnect(&mqttClient); MQTT_Disconnect(&mqttClient);
} }
} }
static void ICACHE_FLASH_ATTR mqttConnectedCb(uint32_t *args) static void ICACHE_FLASH_ATTR mqttConnectedCb(uint32_t *args)
{ {
MQTT_Client* client = (MQTT_Client*)args; MQTT_Client* client = (MQTT_Client*)args;
INFO("MQTT: Connected\r\n"); INFO("MQTT: Connected\r\n");
MQTT_Subscribe(client, "/mqtt/topic/0", 0); MQTT_Subscribe(client, "/mqtt/topic/0", 0);
MQTT_Subscribe(client, "/mqtt/topic/1", 1); MQTT_Subscribe(client, "/mqtt/topic/1", 1);
MQTT_Subscribe(client, "/mqtt/topic/2", 2); MQTT_Subscribe(client, "/mqtt/topic/2", 2);
MQTT_Publish(client, "/mqtt/topic/0", "hello0", 6, 0, 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/1", "hello1", 6, 1, 0);
MQTT_Publish(client, "/mqtt/topic/2", "hello2", 6, 2, 0); MQTT_Publish(client, "/mqtt/topic/2", "hello2", 6, 2, 0);
} }
static void ICACHE_FLASH_ATTR mqttDisconnectedCb(uint32_t *args) static void ICACHE_FLASH_ATTR mqttDisconnectedCb(uint32_t *args)
{ {
MQTT_Client* client = (MQTT_Client*)args; MQTT_Client* client = (MQTT_Client*)args;
INFO("MQTT: Disconnected\r\n"); INFO("MQTT: Disconnected\r\n");
} }
static void ICACHE_FLASH_ATTR mqttPublishedCb(uint32_t *args) static void ICACHE_FLASH_ATTR mqttPublishedCb(uint32_t *args)
{ {
MQTT_Client* client = (MQTT_Client*)args; MQTT_Client* client = (MQTT_Client*)args;
INFO("MQTT: Published\r\n"); 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) 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), char *topicBuf = (char*)os_zalloc(topic_len + 1),
*dataBuf = (char*)os_zalloc(data_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); void ICACHE_FLASH_ATTR print_info()
topicBuf[topic_len] = 0; {
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); INFO("[INFO] -------------------------------------------\n");
dataBuf[data_len] = 0; 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) static void ICACHE_FLASH_ATTR app_init(void)
{ {
uart_init(BIT_RATE_115200, BIT_RATE_115200); uart_init(BIT_RATE_115200, BIT_RATE_115200);
// os_delay_us(1000000); 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); WIFI_Connect(STA_SSID, STA_PASS, wifiConnectCb);
//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");
} }
void user_init(void) void user_init(void)
{ {
system_init_done_cb(app_init); system_init_done_cb(app_init);
} }