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

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:**
- 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:**

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 "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,16 +68,9 @@ 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)
{
@ -104,18 +81,10 @@ uart_tx_one_char(uint8 uart, uint8 TxChar)
break;
}
}
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,13 +130,6 @@ 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)
{
@ -183,111 +139,61 @@ uart0_sendStr(const char *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);
// }
/* 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))
{
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);
}

Wyświetl plik

@ -1,24 +1,23 @@
#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_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_%08X"
#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 "PASSWORD"
#define STA_TYPE AUTH_WPA2_PSK
#define STA_PASS "PASS"
#define MQTT_RECONNECT_TIMEOUT 5 /*second*/
@ -28,4 +27,10 @@
#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__

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"
typedef void (*WifiCallback)(uint8_t);
void ICACHE_FLASH_ATTR WIFI_Connect(uint8_t* ssid, uint8_t* pass, WifiCallback cb);
#endif /* USER_WIFI_H_ */

Wyświetl plik

@ -13,7 +13,6 @@
#include "mqtt_msg.h"
#include "debug.h"
#include "user_config.h"
#include "config.h"
static ETSTimer WiFiLinker;
WifiCallback wifiCb = NULL;
@ -21,42 +20,30 @@ static uint8_t wifiStatus = STATION_IDLE, lastWifiStatus = STATION_IDLE;
static void ICACHE_FLASH_ATTR wifi_check_ip(void *arg)
{
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
{
@ -79,22 +66,14 @@ void ICACHE_FLASH_ATTR WIFI_Connect(uint8_t* ssid, uint8_t* pass, WifiCallback c
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();
}

Wyświetl plik

@ -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_ */

Wyświetl plik

@ -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); }

Wyświetl plik

@ -64,12 +64,12 @@ mqtt_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
if (ipaddr == NULL)
{
INFO("DNS: Found, but got no ip, try to reconnect\r\n");
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",
MQTT_INFO("DNS: found ip %d.%d.%d.%d\n",
*((uint8 *) &ipaddr->addr),
*((uint8 *) &ipaddr->addr + 1),
*((uint8 *) &ipaddr->addr + 2),
@ -82,7 +82,7 @@ mqtt_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
#ifdef MQTT_SSL_ENABLE
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 {
@ -90,7 +90,7 @@ mqtt_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
}
client->connState = TCP_CONNECTING;
INFO("TCP: connecting...\r\n");
MQTT_INFO("TCP: connecting...\r\n");
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
@ -116,7 +116,7 @@ deliver_publish(MQTT_Client* client, uint8_t* message, int 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);
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);
@ -124,13 +124,13 @@ mqtt_send_keepalive(MQTT_Client *client)
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);
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);
#else
INFO("TCP: Do not support SSL\r\n");
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
@ -158,7 +158,7 @@ void ICACHE_FLASH_ATTR
mqtt_tcpclient_delete(MQTT_Client *mqttClient)
{
if (mqttClient->pCon != NULL) {
INFO("TCP: Free memory\r\n");
MQTT_INFO("TCP: Free memory\r\n");
// Force abort connections
espconn_abort(mqttClient->pCon);
// Delete connections
@ -260,7 +260,7 @@ mqtt_client_delete(MQTT_Client *mqttClient)
mqttClient->timeoutCb = NULL;
mqttClient->dataCb = NULL;
INFO("MQTT: client already deleted\r\n");
MQTT_INFO("MQTT: client already deleted\r\n");
}
@ -277,14 +277,15 @@ 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_conn_ret;
struct espconn *pCon = (struct espconn*)arg;
MQTT_Client *client = (MQTT_Client *)pCon->reverse;
client->keepAliveTick = 0;
READPACKET:
INFO("TCP: data received %d bytes\r\n", len);
// INFO("STATE: %d\r\n", client->connState);
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);
@ -295,22 +296,45 @@ READPACKET:
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");
MQTT_INFO("MQTT: Invalid packet\r\n");
if (client->security) {
#ifdef MQTT_SSL_ENABLE
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);
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);
}
}
}
}
@ -326,11 +350,11 @@ READPACKET:
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");
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)
INFO("MQTT: UnSubscribe successful\r\n");
MQTT_INFO("MQTT: UnSubscribe successful\r\n");
break;
case MQTT_MSG_TYPE_PUBLISH:
if (msg_qos == 1)
@ -338,9 +362,9 @@ READPACKET:
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);
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) {
INFO("MQTT: Queue full\r\n");
MQTT_INFO("MQTT: Queue full\r\n");
}
}
@ -348,31 +372,31 @@ READPACKET:
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");
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");
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) {
INFO("MQTT: Queue full\r\n");
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) {
INFO("MQTT: receive MQTT_MSG_TYPE_PUBCOMP, finish QoS2 publish\r\n");
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) {
INFO("MQTT: Queue full\r\n");
MQTT_INFO("MQTT: Queue full\r\n");
}
break;
case MQTT_MSG_TYPE_PINGRESP:
@ -393,7 +417,7 @@ READPACKET:
len -= client->mqtt_state.message_length;
pdata += client->mqtt_state.message_length;
INFO("Get another published message\r\n");
MQTT_INFO("Get another published message\r\n");
goto READPACKET;
}
@ -401,7 +425,7 @@ READPACKET:
break;
}
} else {
INFO("ERROR: Message too long\r\n");
MQTT_INFO("ERROR: Message too long\r\n");
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
}
@ -416,7 +440,7 @@ mqtt_tcpclient_sent_cb(void *arg)
{
struct espconn *pCon = (struct espconn *)arg;
MQTT_Client* client = (MQTT_Client *)pCon->reverse;
INFO("TCP: Sent\r\n");
MQTT_INFO("TCP: Sent\r\n");
client->sendTimeout = 0;
client->keepAliveTick = 0;
@ -459,7 +483,7 @@ 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");
MQTT_INFO("TCP: Disconnected callback\r\n");
if (TCP_DISCONNECTING == client->connState) {
client->connState = TCP_DISCONNECTED;
}
@ -491,7 +515,7 @@ mqtt_tcpclient_connect_cb(void *arg)
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);
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);
@ -500,12 +524,12 @@ mqtt_tcpclient_connect_cb(void *arg)
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);
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);
#else
INFO("TCP: Do not support SSL\r\n");
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
@ -528,7 +552,7 @@ mqtt_tcpclient_recon_cb(void *arg, sint8 errType)
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;
@ -556,14 +580,14 @@ MQTT_Publish(MQTT_Client *client, const char* topic, const char* data, int data_
qos, retain,
&client->mqtt_state.pending_msg_id);
if (client->mqtt_state.outbound_message->length == 0) {
INFO("MQTT: Queuing publish failed\r\n");
MQTT_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);
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) {
INFO("MQTT: Queue full\r\n");
MQTT_INFO("MQTT: Queue full\r\n");
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) {
INFO("MQTT: Serious buffer error\r\n");
MQTT_INFO("MQTT: Serious buffer error\r\n");
return FALSE;
}
}
@ -587,15 +611,16 @@ MQTT_Subscribe(MQTT_Client *client, char* topic, uint8_t qos)
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);
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) {
INFO("MQTT: Queue full\r\n");
MQTT_INFO("MQTT: Queue full\r\n");
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) {
INFO("MQTT: Serious buffer error\r\n");
MQTT_INFO("MQTT: Serious buffer error\r\n");
return FALSE;
}
}
system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client);
return TRUE;
}
@ -613,11 +638,11 @@ MQTT_UnSubscribe(MQTT_Client *client, char* topic)
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);
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) {
INFO("MQTT: Queue full\r\n");
MQTT_INFO("MQTT: Queue full\r\n");
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) {
INFO("MQTT: Serious buffer error\r\n");
MQTT_INFO("MQTT: Serious buffer error\r\n");
return FALSE;
}
}
@ -637,14 +662,14 @@ MQTT_Ping(MQTT_Client *client)
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");
MQTT_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);
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) {
INFO("MQTT: Queue full\r\n");
MQTT_INFO("MQTT: Queue full\r\n");
if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == -1) {
INFO("MQTT: Serious buffer error\r\n");
MQTT_INFO("MQTT: Serious buffer error\r\n");
return FALSE;
}
}
@ -667,7 +692,7 @@ MQTT_Task(os_event_t *e)
case TCP_RECONNECT:
mqtt_tcpclient_delete(client);
MQTT_Connect(client);
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_CONNECTING;
break;
case MQTT_DELETING:
@ -677,7 +702,7 @@ MQTT_Task(os_event_t *e)
#ifdef MQTT_SSL_ENABLE
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 {
@ -685,11 +710,11 @@ MQTT_Task(os_event_t *e)
}
break;
case TCP_DISCONNECTED:
INFO("MQTT: Disconnected\r\n");
MQTT_INFO("MQTT: Disconnected\r\n");
mqtt_tcpclient_delete(client);
break;
case MQTT_DELETED:
INFO("MQTT: Deleted client\r\n");
MQTT_INFO("MQTT: Deleted client\r\n");
mqtt_client_delete(client);
break;
case MQTT_KEEPALIVE_SEND:
@ -705,12 +730,12 @@ MQTT_Task(os_event_t *e)
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);
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);
#else
INFO("TCP: Do not support SSL\r\n");
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else {
@ -736,7 +761,7 @@ 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");
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);
@ -760,7 +785,7 @@ 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");
MQTT_INFO("MQTT:InitClient\r\n");
os_memset(&mqttClient->connect_info, 0, sizeof(mqtt_connect_info_t));
@ -853,13 +878,13 @@ MQTT_Connect(MQTT_Client *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);
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);
#else
INFO("TCP: Do not support SSL\r\n");
MQTT_INFO("TCP: Do not support SSL\r\n");
#endif
}
else
@ -868,7 +893,7 @@ MQTT_Connect(MQTT_Client *mqttClient)
}
}
else {
INFO("TCP: Connect to domain %s:%d\r\n", mqttClient->host, mqttClient->port);
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;

Wyświetl plik

@ -36,10 +36,8 @@
#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) {
@ -80,41 +78,46 @@ static void ICACHE_FLASH_ATTR mqttDataCb(uint32_t *args, const char* topic, uint
*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 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();
INFO("[INFO] -------------------------------------------\n");
INFO("[INFO] Build time: %s\n", BUID_TIME);
INFO("[INFO] -------------------------------------------\n");
}
static void ICACHE_FLASH_ATTR app_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);
print_info();
MQTT_InitConnection(&mqttClient, MQTT_HOST, MQTT_PORT, DEFAULT_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, 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);
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)
{