16 Commits

Author SHA1 Message Date
nhkefus
8374484d0a 去除web后台没数据时的默认值 2025-04-28 15:57:54 +08:00
Your Name
c3d9db335e 调试用 2025-04-25 11:46:19 +08:00
nhkefus
3470d373eb 尝试增加一个外网mqtt客户端 2025-04-24 13:00:44 +08:00
Your Name
3caf76f4c6 开发基于udp的app控制协议 2025-04-23 23:32:04 +08:00
Your Name
982e82c2bb v2.2.0 2025-04-21 21:30:17 +08:00
Your Name
eece61e380 修复了MQTT曾经连上,但中途长时间断开,导致消息队列一直增加爆内存,进而导致死机的问题 2025-04-21 21:29:15 +08:00
Your Name
36861fadff 修复了MQTT曾经连上,但中途长时间断开,导致消息队列一直增加爆内存,进而导致死机的问题 2025-04-21 21:17:34 +08:00
Your Name
f3b7477550 优化了web端iOS Safari按钮的一些逻辑,现在可以看到文件ota上传进度条了 2025-04-19 23:55:57 +08:00
Your Name
dfa8b1c475 现在可以连接名称带特殊符号的wifi,例如有空格 2025-04-19 18:01:14 +08:00
Your Name
c7d2f8d7d0 修复编译警告 2025-04-19 16:06:32 +08:00
Your Name
3f5078294f 修复已知问题 2025-04-18 22:35:59 +08:00
Peng
d7e2243a86 增加本地文件更新功能 2025-04-18 18:39:33 +08:00
Your Name
4e1b376b6a 本地ota加入写flash逻辑以后 会卡死。目前不知道如何优化 2025-04-18 10:12:57 +08:00
Your Name
393af288ec 补漏的代码 2025-04-17 17:52:13 +08:00
nhkefus
e9f1448a69 开发本地ota上传用的 2025-04-17 17:42:51 +08:00
nhkefus
004eaf28dd 开发本地ota上传用的 2025-04-17 17:39:27 +08:00
24 changed files with 1684 additions and 1008 deletions

View File

@@ -1,2 +1,2 @@
set remotetimeout 20 set remotetimeout 20
shell start /B C:\Users\ooo\Desktop\MiCoder/OpenOCD/Win32/openocd_mico.exe -s ./ -f ./mico-os/makefiles/OpenOCD/interface/jlink_swd.cfg -f ./mico-os/makefiles/OpenOCD/mw3xx/mw3xx.cfg -f ./mico-os/makefiles/OpenOCD/mw3xx/mw3xx_gdb_jtag.cfg -l ./build/openocd_log.txt shell start /B F:\TC1\MiCoder_v1.3_Win32-64\MiCoder/OpenOCD/Win32/openocd_mico.exe -s ./ -f ./mico-os/makefiles/OpenOCD/interface/jlink_swd.cfg -f ./mico-os/makefiles/OpenOCD/mw3xx/mw3xx.cfg -f ./mico-os/makefiles/OpenOCD/mw3xx/mw3xx_gdb_jtag.cfg -l ./build/openocd_log.txt

View File

@@ -1,3 +1,3 @@
source [find C:\Users\ooo\Desktop\MiCoder/OpenOCD/jlink_swd.cfg] source [find F:\TC1\MiCoder_v1.3_Win32-64\MiCoder/OpenOCD/jlink_swd.cfg]
source [find C:\Users\ooo\Desktop\MiCoder/OpenOCD/mw3xx.cfg] source [find F:\TC1\MiCoder_v1.3_Win32-64\MiCoder/OpenOCD/mw3xx.cfg]
source [find C:\Users\ooo\Desktop\MiCoder/OpenOCD/mw3xx_gdb_jtag.cfg] source [find F:\TC1\MiCoder_v1.3_Win32-64\MiCoder/OpenOCD/mw3xx_gdb_jtag.cfg]

1
.version Normal file
View File

@@ -0,0 +1 @@
v1.0.79

View File

@@ -34,7 +34,8 @@ $(NAME)_SOURCES := main.c\
user_power.c\ user_power.c\
timed_task/timed_task.c\ timed_task/timed_task.c\
http_server/web_log.c\ http_server/web_log.c\
http_server/app_httpd.c http_server/app_httpd.c\
udp_server/udp_server.c
$(NAME)_COMPONENTS := protocols/SNTP\ $(NAME)_COMPONENTS := protocols/SNTP\
protocols/mqtt\ protocols/mqtt\

View File

@@ -36,6 +36,11 @@
#include <http-strings.h> #include <http-strings.h>
#include "stdlib.h" #include "stdlib.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mico.h" #include "mico.h"
#include "httpd_priv.h" #include "httpd_priv.h"
#include "app_httpd.h" #include "app_httpd.h"
@@ -55,6 +60,8 @@ const struct httpd_wsgi_call g_app_handlers[];
char power_info_json[2560] = {0}; char power_info_json[2560] = {0};
char up_time[16] = "00:00:00"; char up_time[16] = "00:00:00";
#define CHUNK_SIZE 512 // 每次发送 512 字节,避免 buffer 太大 #define CHUNK_SIZE 512 // 每次发送 512 字节,避免 buffer 太大
#define OTA_BUFFER_SIZE 512
#define MAX_OTA_SIZE 1024*1024
/* /*
void GetPraFromUrl(char* url, char* pra, char* val) void GetPraFromUrl(char* url, char* pra, char* val)
@@ -255,6 +262,90 @@ static int HttpSetButtonEvent(httpd_request_t *req) {
return err; return err;
} }
#define OTA_BUF_SIZE 5120
static int HttpSetOTAFile(httpd_request_t *req)
{
tc1_log("[OTA] hdr_parsed=%d, remaining=%d, body_nbytes=%d, req.chunked=%d",
req->hdr_parsed, req->remaining_bytes, req->body_nbytes, req->chunked);
OSStatus err = kNoErr;
int total = 0;
int ret = 0;
// req->chunked = 1;
int total1 = req->remaining_bytes;
char *buffer = malloc(OTA_BUF_SIZE);
if (!buffer) return kNoMemoryErr;
uint32_t offset = 0;
mico_logic_partition_t* ota_partition = MicoFlashGetInfo(MICO_PARTITION_OTA_TEMP);
MicoFlashErase(MICO_PARTITION_OTA_TEMP, 0x0, ota_partition->partition_length);
CRC16_Context crc_context;
CRC16_Init(&crc_context);
// 尝试读取全部 POST 数据
while (1) {
ret = httpd_get_data2(req, buffer,OTA_BUF_SIZE);
// ret = httpd_recv(req->sock, buffer, 128, 0);
total += ret;
// req->remaining_bytes -= ret;
if (ret > 0) {
CRC16_Update(&crc_context, buffer, ret);
err = MicoFlashWrite(MICO_PARTITION_OTA_TEMP, &offset, (uint8_t *)buffer, ret);
require_noerr_quiet(err, exit);
tc1_log("[OTA] 本次读取 %d 字节,累计 %d 字节", ret, total);
}
if (ret == 0 || req->remaining_bytes <= 0) {
// 读取完毕
tc1_log("[OTA] 数据读取完成, 总计 %d 字节", total);
break;
} else if (ret < 0) {
tc1_log("[OTA] 数据读取失败, ret=%d", ret);
err = kConnectionErr;
break;
}
mico_rtos_thread_msleep(100);
// tc1_log("[OTA] %x", buffer);
// tc1_log("[OTA] hdr_parsed=%d, remaining=%d, body_nbytes=%d",
// req->hdr_parsed, req->remaining_bytes, req->body_nbytes);
}
// if (buffer) free(buffer);
uint16_t crc16;
CRC16_Final(&crc_context, &crc16);
err = mico_ota_switch_to_new_fw(total, crc16);
tc1_log("[OTA] mico_ota_switch_to_new_fw err=%d", err);
require_noerr(err, exit);
char resp[128];
snprintf(resp, sizeof(resp), "OK, total: %d bytes, req %d %d", total, req->body_nbytes, total1);
send_http(resp, strlen(resp), exit, &err);
mico_system_power_perform(mico_system_context_get(), eState_Software_Reset);
exit:
if (buffer) free(buffer);
return err;
// ota_file_req = req;
// OSStatus err = kNoErr;
// err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "OtaFileThread", OtaFileThread, 0x1000, 0);
// char buf[16] = {0};
// sprintf(buf, "%d", sizeof(ota_file_req));
// send_http(buf, strlen(buf), exit, &err);
// exit:
// if (buf) free(buf);
// return err;
}
static int HttpSetDeviceName(httpd_request_t *req) { static int HttpSetDeviceName(httpd_request_t *req) {
OSStatus err = kNoErr; OSStatus err = kNoErr;
@@ -344,19 +435,62 @@ static int HttpGetWifiConfig(httpd_request_t *req) {
return err; return err;
} }
// 单个十六进制字符转数字(安全)
static int hex_char_to_int(char c) {
if ('0' <= c && c <= '9') return c - '0';
if ('a' <= c && c <= 'f') return c - 'a' + 10;
if ('A' <= c && c <= 'F') return c - 'A' + 10;
return -1;
}
// 健壮版 URL 解码函数
void url_decode(const char *src, char *dest, size_t max_len) {
size_t i = 0;
while (*src && i < max_len - 1) {
if (*src == '%') {
if (isxdigit((unsigned char)src[1]) && isxdigit((unsigned char)src[2])) {
int high = hex_char_to_int(src[1]);
int low = hex_char_to_int(src[2]);
if (high >= 0 && low >= 0) {
dest[i++] = (char)((high << 4) | low);
src += 3;
continue;
}
}
// 非法编码,跳过 %
src++;
} else if (*src == '+') {
dest[i++] = ' ';
src++;
} else {
dest[i++] = *src++;
}
}
dest[i] = '\0';
}
static int HttpSetWifiConfig(httpd_request_t *req) { static int HttpSetWifiConfig(httpd_request_t *req) {
OSStatus err = kNoErr; OSStatus err = kNoErr;
int buf_size = 97; char *buf = malloc(256);
char *buf = malloc(buf_size); char *ssid_enc = malloc(128);
char *key_enc = malloc(128);
char *wifi_ssid = malloc(128);
char *wifi_key = malloc(128);
int mode = -1; int mode = -1;
char *wifi_ssid = malloc(32);
char *wifi_key = malloc(32);
err = httpd_get_data(req, buf, buf_size);
err = httpd_get_data(req, buf, 256);
require_noerr(err, exit); require_noerr(err, exit);
// 假设 httpd_get_data(req, buf, 256);
sscanf(buf, "%d %s %s", &mode, wifi_ssid, wifi_key); // tc1_log("wifi config %s",buf);
sscanf(buf, "%d %s %s", &mode, ssid_enc, key_enc);
// tc1_log("wifi config %s %s",ssid_enc,key_enc);
url_decode(ssid_enc, wifi_ssid,128);
url_decode(key_enc, wifi_key,128);
// tc1_log("wifi config decode %s %s",wifi_ssid,wifi_key);
if (mode == 1) { if (mode == 1) {
WifiConnect(wifi_ssid, wifi_key); WifiConnect(wifi_ssid, wifi_key);
} else { } else {
@@ -643,6 +777,7 @@ const struct httpd_wsgi_call g_app_handlers[] = {
{"/childLock", HTTPD_HDR_DEFORT, 0, NULL, HttpSetChildLock, NULL, NULL}, {"/childLock", HTTPD_HDR_DEFORT, 0, NULL, HttpSetChildLock, NULL, NULL},
{"/deviceName", HTTPD_HDR_DEFORT, 0, NULL, HttpSetDeviceName, NULL, NULL}, {"/deviceName", HTTPD_HDR_DEFORT, 0, NULL, HttpSetDeviceName, NULL, NULL},
{"/buttonEvents", HTTPD_HDR_DEFORT, 0, HttpGetButtonEvents, HttpSetButtonEvent, NULL, NULL}, {"/buttonEvents", HTTPD_HDR_DEFORT, 0, HttpGetButtonEvents, HttpSetButtonEvent, NULL, NULL},
{"/ota/fileUpload", HTTPD_HDR_DEFORT, 0, NULL, HttpSetOTAFile, NULL, NULL},
}; };
static int g_app_handlers_no = sizeof(g_app_handlers) / sizeof(struct httpd_wsgi_call); static int g_app_handlers_no = sizeof(g_app_handlers) / sizeof(struct httpd_wsgi_call);

View File

@@ -73,7 +73,7 @@
#define POWER_INFO_JSON "{'sockets':'%s','idx':%d,'len':%d,'p_count':%ld,'powers':[%s],'up_time':'%s','led_enabled':%d,'total_switch_on':%d,'socketNames':'%s','p_count_1_day_ago':%d,'p_count_2_days_ago':%d,'child_lock_enabled':%d,'deviceName':'%s','btnClicks':%s}" #define POWER_INFO_JSON "{'sockets':'%s','idx':%d,'len':%d,'p_count':%ld,'powers':[%s],'up_time':'%s','led_enabled':%d,'total_switch_on':%d,'socketNames':'%s','p_count_1_day_ago':%d,'p_count_2_days_ago':%d,'child_lock_enabled':%d,'deviceName':'%s','btnClicks':%s}"
int AppHttpdStart(void); extern int AppHttpdStart(void);
int AppHttpdStop(); extern int AppHttpdStop();

View File

@@ -31,7 +31,7 @@
<div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header"> <div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header">
<header class="demo-header mdl-layout__header"> <header class="demo-header mdl-layout__header">
<div class="mdl-layout__header-row"> <div class="mdl-layout__header-row">
<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon edit-device-name"> <button class="mdl-button mdl-button--icon edit-device-name">
<i class="material-icons"> <i class="material-icons">
<svg> <svg>
<use xlink:href="#icon-edit"/> <use xlink:href="#icon-edit"/>
@@ -40,22 +40,22 @@
</button> </button>
<span class="mdl-layout-title">TC1智能插座</span> <span class="mdl-layout-title">TC1智能插座</span>
<div class="mdl-layout-spacer"></div> <div class="mdl-layout-spacer"></div>
<!-- <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button&#45;&#45;icon"--> <!-- <button class="mdl-button mdl-button&#45;&#45;icon"-->
<!-- id="hdrbtn">--> <!-- id="hdrbtn">-->
<!-- <i class="material-icons">--> <!-- <i class="material-icons">-->
<!-- <svg>--> <!-- <svg>-->
<!-- <use xlink:href="#icon-translate"/>--> <!-- <use xlink:href="#icon-translate"/>-->
<!-- </svg>--> <!-- </svg>-->
<!-- </i>--> <!-- </i>-->
<!-- </button>--> <!-- </button>-->
<!-- <ul class="mdl-menu mdl-js-menu mdl-js-ripple-effect mdl-menu&#45;&#45;bottom-right"--> <!-- <ul class="mdl-menu mdl-js-menu mdl-js-ripple-effect mdl-menu&#45;&#45;bottom-right"-->
<!-- for="hdrbtn">--> <!-- for="hdrbtn">-->
<!-- <li class="mdl-menu__item" onclick="ChangeLanguage('en')">English</li>--> <!-- <li class="mdl-menu__item" onclick="ChangeLanguage('en')">English</li>-->
<!-- <li class="mdl-menu__item" onclick="ChangeLanguage('cn')">中文</li>--> <!-- <li class="mdl-menu__item" onclick="ChangeLanguage('cn')">中文</li>-->
<!-- <li class="mdl-menu__item" onclick="ChangeLanguage('jp')">日本語</li>--> <!-- <li class="mdl-menu__item" onclick="ChangeLanguage('jp')">日本語</li>-->
<!-- </ul>--> <!-- </ul>-->
<button onclick="reboot()" <button onclick="reboot()"
class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" class="mdl-button mdl-button--icon"
id="rebootbtn"> id="rebootbtn">
<i class="material-icons"> <i class="material-icons">
<svg> <svg>
@@ -113,7 +113,7 @@
<use xlink:href="#icon-cloud_download"/> <use xlink:href="#icon-cloud_download"/>
</svg> </svg>
</i> </i>
<span class="lang" langKey="OTA">在线升级</span> <span class="lang" langKey="OTA">固件升级</span>
</a> </a>
<a class="mdl-navigation__link" href="javascript:ShowPage(7);"> <a class="mdl-navigation__link" href="javascript:ShowPage(7);">
<i class="mdl-color-text--blue-grey-400 material-icons" role="presentation"> <i class="mdl-color-text--blue-grey-400 material-icons" role="presentation">
@@ -176,7 +176,7 @@
</li> </li>
<li class="mdl-list__item"> <li class="mdl-list__item">
<span class="mdl-list__item-primary-content"> <span class="mdl-list__item-primary-content">
<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon edit-socket-name"> <button class="mdl-button mdl-button--icon edit-socket-name">
<i class="material-icons"> <i class="material-icons">
<svg> <svg>
<use xlink:href="#icon-edit"/> <use xlink:href="#icon-edit"/>
@@ -195,7 +195,7 @@
</li> </li>
<li class="mdl-list__item"> <li class="mdl-list__item">
<span class="mdl-list__item-primary-content"> <span class="mdl-list__item-primary-content">
<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon edit-socket-name"> <button class="mdl-button mdl-button--icon edit-socket-name">
<i class="material-icons"> <i class="material-icons">
<svg> <svg>
<use xlink:href="#icon-edit"/> <use xlink:href="#icon-edit"/>
@@ -214,7 +214,7 @@
</li> </li>
<li class="mdl-list__item"> <li class="mdl-list__item">
<span class="mdl-list__item-primary-content"> <span class="mdl-list__item-primary-content">
<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon edit-socket-name"> <button class="mdl-button mdl-button--icon edit-socket-name">
<i class="material-icons"> <i class="material-icons">
<svg> <svg>
<use xlink:href="#icon-edit"/> <use xlink:href="#icon-edit"/>
@@ -233,7 +233,7 @@
</li> </li>
<li class="mdl-list__item"> <li class="mdl-list__item">
<span class="mdl-list__item-primary-content"> <span class="mdl-list__item-primary-content">
<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon edit-socket-name"> <button class="mdl-button mdl-button--icon edit-socket-name">
<i class="material-icons"> <i class="material-icons">
<svg> <svg>
<use xlink:href="#icon-edit"/> <use xlink:href="#icon-edit"/>
@@ -252,7 +252,7 @@
</li> </li>
<li class="mdl-list__item"> <li class="mdl-list__item">
<span class="mdl-list__item-primary-content"> <span class="mdl-list__item-primary-content">
<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon edit-socket-name"> <button class="mdl-button mdl-button--icon edit-socket-name">
<i class="material-icons"> <i class="material-icons">
<svg> <svg>
<use xlink:href="#icon-edit"/> <use xlink:href="#icon-edit"/>
@@ -271,7 +271,7 @@
</li> </li>
<li class="mdl-list__item"> <li class="mdl-list__item">
<span class="mdl-list__item-primary-content"> <span class="mdl-list__item-primary-content">
<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon edit-socket-name"> <button class="mdl-button mdl-button--icon edit-socket-name">
<i class="material-icons"> <i class="material-icons">
<svg> <svg>
<use xlink:href="#icon-edit"/> <use xlink:href="#icon-edit"/>
@@ -368,10 +368,10 @@
</form> </form>
</div> </div>
<div class="mdl-card__actions mdl-card--border"> <div class="mdl-card__actions mdl-card--border">
<a id="wifi_submit" <button type="button" id="wifi_submit"
class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect"> class="mdl-button mdl-button--colored ">
提交 提交
</a> </button>
</div> </div>
</div> </div>
@@ -401,10 +401,10 @@
</form> </form>
</div> </div>
<div class="mdl-card__actions mdl-card--border"> <div class="mdl-card__actions mdl-card--border">
<a id="mqtt_submit" <button type="button" id="mqtt_submit"
class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect"> class="mdl-button mdl-button--colored ">
提交 提交
</a> </button>
</div> </div>
</div> </div>
@@ -422,10 +422,10 @@
</form> </form>
</div> </div>
<div class="mdl-card__actions mdl-card--border"> <div class="mdl-card__actions mdl-card--border">
<a id="mqtt_freq_submit" <button type="button" id="mqtt_freq_submit"
class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect"> class="mdl-button mdl-button--colored ">
提交 提交
</a> </button>
</div> </div>
</div> </div>
@@ -438,20 +438,6 @@
<th>循环</th> <th>循环</th>
<th>操作</th> <th>操作</th>
</tr> </tr>
<tr>
<td>02-15 07:11</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td><a>删除</a></td>
</tr>
<tr>
<td>2020-02-15<br>07:11:08</td>
<td>1</td>
<td>0</td>
<td>6</td>
<td><a>删除</a></td>
</tr>
</table> </table>
</div> </div>
@@ -519,10 +505,10 @@
</form> </form>
</div> </div>
<div class="mdl-card__actions mdl-card--border"> <div class="mdl-card__actions mdl-card--border">
<a href="javascript:AddTimedTask();" <button type="button" onclick="AddTimedTask();"
class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect"> class="mdl-button mdl-button--colored ">
提交 提交
</a> </button>
</div> </div>
</div> </div>
@@ -598,10 +584,10 @@
</form> </form>
</div> </div>
<div class="mdl-card__actions mdl-card--border"> <div class="mdl-card__actions mdl-card--border">
<a href="javascript:addButtonEvent();" <button type="button" onclick="addButtonEvent();"
class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect"> class="mdl-button mdl-button--colored ">
添加 添加
</a> </button>
</div> </div>
</div> </div>
@@ -610,23 +596,23 @@
<table class="mdl-data-table mdl-js-data-table"> <table class="mdl-data-table mdl-js-data-table">
<tr> <tr>
<th>版本</th> <th>版本</th>
<th id="info_version">v1.0.33</th> <th id="info_version"></th>
</tr> </tr>
<tr> <tr>
<td>IP</td> <td>IP</td>
<td id="info_ip">192.168.33.222</td> <td id="info_ip"></td>
</tr> </tr>
<tr> <tr>
<td>子网掩码</td> <td>子网掩码</td>
<td id="info_mask">255.255.255.0</td> <td id="info_mask"></td>
</tr> </tr>
<tr> <tr>
<td>网关</td> <td>网关</td>
<td id="info_gateway">192.168.33.1</td> <td id="info_gateway"></td>
</tr> </tr>
<tr> <tr>
<td>启动时间</td> <td>启动时间</td>
<td id="uptime">10:13:43</td> <td id="uptime"></td>
</tr> </tr>
</table> </table>
<div class="mdl-card__actions mdl-card--border" style="display: flex; align-items: center; flex-wrap: wrap;"> <div class="mdl-card__actions mdl-card--border" style="display: flex; align-items: center; flex-wrap: wrap;">
@@ -638,7 +624,7 @@
</svg> </svg>
</i> </i>
<!-- <span>2020-02-22</span> --> <!-- <span>2020-02-22</span> -->
<a class="mdl-button" id="st-date">2020-02-22</a> <a class="mdl-button" id="st-date"></a>
</div> </div>
</div> </div>
@@ -655,14 +641,33 @@
</form> </form>
</div> </div>
<div class="mdl-card__actions mdl-card--border"> <div class="mdl-card__actions mdl-card--border">
<a href="javascript:OtaStart();" <button type="button" onclick="OtaStart();" id="submit-ota-link"
class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect"> class="mdl-button mdl-button--colored ">
提交 提交
</a> </button>
</div> </div>
<div id="ota_status" class="mdl-progress mdl-js-progress"></div> <div id="ota_status" class="mdl-progress mdl-js-progress"></div>
</div> </div>
<div class="page page6 mdl-cell mdl-cell--12-col demo-card-square mdl-card mdl-shadow--2dp">
<div class="mdl-card__title mdl-card--expand">
<h2 class="mdl-card__title-text">本地升级</h2>
</div>
<div class="mdl-card__supporting-text">
<form id="otaForm" action="/ota/fileUpload" method="post" enctype="multipart/form-data">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="file" id="ota_file" name="ota_file">
</div>
</form>
</div>
<div class="mdl-card__actions mdl-card--border">
<button type="button" onclick="OtaFileUpload();" class="mdl-button mdl-button--colored " id="submit-ota-file">
上传 OTA 文件
</button>
</div>
<div id="upload_status" class="mdl-progress mdl-js-progress"></div>
</div>
<div class="page page7 mdl-cell mdl-cell--12-col demo-card-square mdl-card mdl-shadow--2dp"> <div class="page page7 mdl-cell mdl-cell--12-col demo-card-square mdl-card mdl-shadow--2dp">
<div class="mdl-card__title mdl-card--expand"> <div class="mdl-card__title mdl-card--expand">
<h2 class="mdl-card__title-text">系统日志</h2> <h2 class="mdl-card__title-text">系统日志</h2>
@@ -671,10 +676,10 @@
<pre id="sys_log"></pre> <pre id="sys_log"></pre>
</div> </div>
<div class="mdl-card__actions mdl-card--border"> <div class="mdl-card__actions mdl-card--border">
<a href="javascript:GetSysLog();" <button type="button" onclick="GetSysLog();"
class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect"> class="mdl-button mdl-button--colored ">
刷新 刷新
</a> </button>
</div> </div>
</div> </div>
@@ -777,7 +782,7 @@
Config: {en: "Config", cn: "设置"}, Config: {en: "Config", cn: "设置"},
TimedTask: {en: "Timed Task", cn: "定时任务"}, TimedTask: {en: "Timed Task", cn: "定时任务"},
SystemStatus: {en: "System Status", cn: "系统状态"}, SystemStatus: {en: "System Status", cn: "系统状态"},
OTA: {en: "OTA", cn: "在线升级"}, OTA: {en: "OTA", cn: "固件升级"},
SystemLog: {en: "System Log", cn: "系统日志"}, SystemLog: {en: "System Log", cn: "系统日志"},
About: {en: "About", cn: "关于"}, About: {en: "About", cn: "关于"},
//主页 //主页
@@ -957,6 +962,7 @@
BTN_OPERATIONS.push("重新配网"); BTN_OPERATIONS.push("重新配网");
BTN_OPERATIONS.push("重置系统"); BTN_OPERATIONS.push("重置系统");
BTN_OPERATIONS.push("切换童锁"); BTN_OPERATIONS.push("切换童锁");
BTN_OPERATIONS.push("重启网页");
$('#btn_action_selector').append( $('#btn_action_selector').append(
$('<li>') $('<li>')
@@ -1216,15 +1222,15 @@ componentHandler.upgradeDom();
var mode = $("#custom_station").prop("checked") ? 1 : 0; var mode = $("#custom_station").prop("checked") ? 1 : 0;
var ssid = $("#custom_ssid").val(); var ssid = $("#custom_ssid").val();
var passwd = $("#custom_password").val(); var passwd = $("#custom_password").val();
if (ContainQM(ssid) || ContainQM(passwd)) { //if (ContainQM(ssid) || ContainQM(passwd)) {
alert(qm_mess); // alert(qm_mess);
return; // return;
} //}
if (passwd.length < 8) { if (passwd.length < 8) {
alert(le_mess); alert(le_mess);
return; return;
} }
var params = mode + " " + ssid + " " + passwd; var params = mode + " " + encodeURIComponent(ssid) + " " + encodeURIComponent(passwd);
HttpPost("/wifi/config", function (re) { HttpPost("/wifi/config", function (re) {
ShowToast(re); ShowToast(re);
}, params); }, params);
@@ -1240,6 +1246,7 @@ componentHandler.upgradeDom();
var w = document.getElementById("w"); var w = document.getElementById("w");
var w_t = document.getElementById("w_t"); var w_t = document.getElementById("w_t");
var w_y = document.getElementById("w_y"); var w_y = document.getElementById("w_y");
var powerTimerId;
function GetPowerRecord() { function GetPowerRecord() {
HttpPost("/power", function (re) { HttpPost("/power", function (re) {
@@ -1305,7 +1312,7 @@ componentHandler.upgradeDom();
switch_lables[i+3].MaterialSwitch.off(); switch_lables[i+3].MaterialSwitch.off();
} }
} }
window.powerTimeout= window.setTimeout(GetPowerRecord, 3000); powerTimerId= window.setTimeout(GetPowerRecord, 3000);
}, power_idx.toString()); }, power_idx.toString());
} }
$(document).ready(function(){ $(document).ready(function(){
@@ -1484,12 +1491,51 @@ HttpPost("/shortClickEvent", function (re) {
var ota_url = document.getElementById("ota_url").value; var ota_url = document.getElementById("ota_url").value;
var protocol = window.location.protocol; var protocol = window.location.protocol;
var baseUrl = protocol+"//"+window.location.host; var baseUrl = protocol+"//"+window.location.host;
document.getElementById("submit-ota-link").disabled = true;
clearTimeout(window.powerTimeout);
HttpPost("/ota", function (re) { HttpPost("/ota", function (re) {
OtaStatus(); OtaStatus();
}, ota_url); }, ota_url);
} }
var upload_status = document.querySelector('#upload_status');
upload_status.addEventListener('mdl-componentupgraded', function() {
this.MaterialProgress.setProgress(0);
});
function OtaFileUpload() {
//alert("假的假的是假的,忽略");
//return;
var fileInput = document.getElementById("ota_file");
if (fileInput.files.length === 0) {
ShowToast("请选择要上传的 OTA 文件");
return;
}
clearTimeout(powerTimerId);
console.log(fileInput.files[0].size); // 应显示 647168 左右
document.getElementById("submit-ota-file").disabled = true;
const xhr = new XMLHttpRequest();
xhr.open("POST", "/ota/fileUpload");
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
let percent = (e.loaded / e.total * 100).toFixed(1);
upload_status.MaterialProgress.setProgress(percent);
console.log(`上传进度:${percent}%`);
}
};
xhr.onload = function () {
alert("上传完成:" + xhr.responseText);
document.getElementById("submit-ota-file").disabled = false;
};
xhr.onerror = function () {
alert("上传失败");
document.getElementById("submit-ota-file").disabled = false;
};
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(fileInput.files[0]);
}
var ota_status = document.querySelector('#ota_status'); var ota_status = document.querySelector('#ota_status');
ota_status.addEventListener('mdl-componentupgraded', function() { ota_status.addEventListener('mdl-componentupgraded', function() {
this.MaterialProgress.setProgress(0); this.MaterialProgress.setProgress(0);

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,8 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <stdarg.h> #include <stdarg.h>
#include "mico.h"
#include"http_server/web_log.h" #include"http_server/web_log.h"
@@ -36,6 +38,9 @@ char* GetLogRecord()
tmp += strlen(tmp); tmp += strlen(tmp);
if (!log_record.logs[i%LOG_NUM]) continue; if (!log_record.logs[i%LOG_NUM]) continue;
sprintf(tmp, "%s\n", log_record.logs[i%LOG_NUM]); sprintf(tmp, "%s\n", log_record.logs[i%LOG_NUM]);
if(i == log_record.idx){
sprintf(tmp, "%s\nFreeMem %d bytes\n",log_record.logs[i%LOG_NUM],MicoGetMemoryInfo()->free_memory);
}
} }
return log_record_str; return log_record_str;
} }

View File

@@ -10,8 +10,8 @@
#include "user_wifi.h" #include "user_wifi.h"
#include "time_server/user_rtc.h" #include "time_server/user_rtc.h"
#include "user_power.h" #include "user_power.h"
#include "mqtt_server/user_mqtt_client.h"
#include "http_server/app_httpd.h" #include "http_server/app_httpd.h"
#include "udp_server/udp_server.h"
#include "timed_task/timed_task.h" #include "timed_task/timed_task.h"
char rtc_init = 0; //sntp校时成功标志位 char rtc_init = 0; //sntp校时成功标志位
@@ -186,25 +186,24 @@ int application_start(void) {
} }
} }
KeyInit(); KeyInit();
if (!(MQTT_SERVER[0] < 0x20 || MQTT_SERVER[0] > 0x7f || MQTT_SERVER_PORT < 1)){
err = UserMqttInit();
require_noerr(err, exit);
}
err = UserRtcInit(); err = UserRtcInit();
require_noerr(err, exit); require_noerr(err, exit);
PowerInit(); PowerInit();
AppHttpdStart(); // start http server thread AppHttpdStart(); // start http server thread
// udp_server_start();
//if (!(MQTT_SERVER[0] < 0x20 || MQTT_SERVER[0] > 0x7f || MQTT_SERVER_PORT < 1)){
// UserMqttInit();
// }
UserLedSet(user_config->power_led_enabled); UserLedSet(user_config->power_led_enabled);
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "p_count", err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "p_count",
(mico_thread_function_t) schedule_p_count_task, (mico_thread_function_t) schedule_p_count_task,
0x2000, 0); 0x800, 0);
require_noerr_string(err, exit, "ERROR: Unable to start the p_count thread."); require_noerr_string(err, exit, "ERROR: Unable to start the p_count thread.");
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mqtt_power_report", err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mqtt_power_report",
(mico_thread_function_t) reportMqttPowerInfoThread, (mico_thread_function_t) reportMqttPowerInfoThread,
0x2000, 0); 0x800, 0);
require_noerr_string(err, exit, "ERROR: Unable to start the mqtt_power_report thread."); require_noerr_string(err, exit, "ERROR: Unable to start the mqtt_power_report thread.");
@@ -213,7 +212,6 @@ int application_start(void) {
if (user_config->task_top && now >= user_config->task_top->prs_time) { if (user_config->task_top && now >= user_config->task_top->prs_time) {
ProcessTask(); ProcessTask();
} }
mico_thread_msleep(1000); mico_thread_msleep(1000);
} }

View File

@@ -16,7 +16,7 @@
#define wifi_log(M, ...) custom_log("WIFI", M, ##__VA_ARGS__); web_log("WIFI", M, ##__VA_ARGS__); #define wifi_log(M, ...) custom_log("WIFI", M, ##__VA_ARGS__); web_log("WIFI", M, ##__VA_ARGS__);
#define power_log(M, ...) custom_log("POWER", M, ##__VA_ARGS__); web_log("POWER", M, ##__VA_ARGS__); #define power_log(M, ...) custom_log("POWER", M, ##__VA_ARGS__); web_log("POWER", M, ##__VA_ARGS__);
#define VERSION "v2.1.7" #define VERSION "v2.2.0"
#define TYPE 1 #define TYPE 1
#define TYPE_NAME "TC1" #define TYPE_NAME "TC1"

View File

@@ -36,10 +36,18 @@ typedef struct {
uint32_t datalen; uint32_t datalen;
} mqtt_recv_msg_t, *p_mqtt_recv_msg_t, mqtt_send_msg_t, *p_mqtt_send_msg_t; } mqtt_recv_msg_t, *p_mqtt_recv_msg_t, mqtt_send_msg_t, *p_mqtt_send_msg_t;
typedef struct {
Client client;
Network network;
// 其他状态、配置参数……
} mqtt_context_t;
static void MqttClientThread(mico_thread_arg_t arg); static void MqttClientThread(mico_thread_arg_t arg);
static void MessageArrived(MessageData *md); static void MessageArrived(MessageData *md);
static void MqttClientThread2(mico_thread_arg_t arg);
static OSStatus static OSStatus
MqttMsgPublish(Client *c, const char *topic, char qos, char retained, const unsigned char *msg, MqttMsgPublish(Client *c, const char *topic, char qos, char retained, const unsigned char *msg,
uint32_t msg_len); uint32_t msg_len);
@@ -49,12 +57,14 @@ OSStatus UserRecvHandler(void *arg);
void ProcessHaCmd(char *cmd); void ProcessHaCmd(char *cmd);
bool isconnect = false; bool isconnect = false;
bool isconnect2 = false;
mico_queue_t mqtt_msg_send_queue = NULL; mico_queue_t mqtt_msg_send_queue = NULL;
mico_queue_t mqtt_msg_send_queue2 = NULL;
Client c; // mqtt client object volatile bool mqtt_thread_should_exit = false;
Network n; // socket network for mqtt client
static mico_worker_thread_t mqtt_client_worker_thread; /* Worker thread to manage send/recv events */ static mico_worker_thread_t mqtt_client_worker_thread; /* Worker thread to manage send/recv events */
//static mico_timed_event_t mqtt_client_send_event; //static mico_timed_event_t mqtt_client_send_event;
char topic_state[MAX_MQTT_TOPIC_SIZE]; char topic_state[MAX_MQTT_TOPIC_SIZE];
@@ -62,6 +72,8 @@ char topic_set[MAX_MQTT_TOPIC_SIZE];
mico_timer_t timer_handle; mico_timer_t timer_handle;
static char timer_status = 0; static char timer_status = 0;
mico_timer_t timer_handle2;
static char timer_status_2 = 0;
void UserMqttTimerFunc(void *arg) { void UserMqttTimerFunc(void *arg) {
LinkStatusTypeDef LinkStatus; LinkStatusTypeDef LinkStatus;
@@ -98,6 +110,50 @@ void UserMqttTimerFunc(void *arg) {
} }
} }
void UserMqttTimerFunc2(void *arg) {
LinkStatusTypeDef LinkStatus;
micoWlanGetLinkStatus(&LinkStatus);
if (LinkStatus.is_connected != 1) {
mico_stop_timer(&timer_handle2);
return;
}
if (mico_rtos_is_queue_empty(&mqtt_msg_send_queue2)) {
switch (timer_status_2) {
case 0:
UserMqttHassAutoLed();
UserMqttHassAutoTotalSocket();
UserMqttHassAutoChildLock();
UserMqttHassAutoRebootButton();
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
UserMqttHassAuto(timer_status_2);
break;
case 7:
UserMqttHassAutoPower();
break;
default:
mico_stop_timer(&timer_handle2);
break;
}
timer_status_2++;
}
}
OSStatus UserMqttDeInit(void) {
OSStatus err = kNoErr;
// 1. 请求线程退出
mqtt_thread_should_exit = true;
return err;
}
/* Application entrance */ /* Application entrance */
OSStatus UserMqttInit(void) { OSStatus UserMqttInit(void) {
OSStatus err = kNoErr; OSStatus err = kNoErr;
@@ -118,14 +174,28 @@ OSStatus UserMqttInit(void) {
require_noerr_action(err, exit, mqtt_log("ERROR: create mqtt msg send queue err=%d.", err)); require_noerr_action(err, exit, mqtt_log("ERROR: create mqtt msg send queue err=%d.", err));
/* start mqtt client */ /* start mqtt client */
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mqtt_client", mqtt_context_t *ctx1 = malloc(sizeof(mqtt_context_t));
(mico_thread_function_t) MqttClientThread, memset(ctx1, 0, sizeof(mqtt_context_t));
mqtt_thread_stack_size, 0);
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mqtt_client_1",
(mico_thread_function_t)MqttClientThread,
mqtt_thread_stack_size, ctx1);
require_noerr_string(err, exit, "ERROR: Unable to start the mqtt client thread."); require_noerr_string(err, exit, "ERROR: Unable to start the mqtt client thread.");
// 第二个客户端
mqtt_context_t *ctx2 = malloc(sizeof(mqtt_context_t));
memset(ctx2, 0, sizeof(mqtt_context_t));
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mqtt_client_2",
(mico_thread_function_t)MqttClientThread2,
mqtt_thread_stack_size, ctx2);
require_noerr_string(err, exit, "ERROR: Unable to start the mqtt client thread2.");
/* Create a worker thread for user handling MQTT data event */ /* Create a worker thread for user handling MQTT data event */
err = mico_rtos_create_worker_thread(&mqtt_client_worker_thread, MICO_APPLICATION_PRIORITY, err = mico_rtos_create_worker_thread(&mqtt_client_worker_thread, MICO_APPLICATION_PRIORITY,
0x800, 5); 0x1000, 5);
require_noerr_string(err, exit, "ERROR: Unable to start the mqtt client worker thread."); require_noerr_string(err, exit, "ERROR: Unable to start the mqtt client worker thread.");
exit: exit:
@@ -180,10 +250,15 @@ void registerMqttEvents(void) {
timer_status = 0; timer_status = 0;
mico_start_timer(&timer_handle); mico_start_timer(&timer_handle);
} }
void registerMqttEvents2(void) {
timer_status_2 = 0;
mico_start_timer(&timer_handle2);
}
void MqttClientThread(mico_thread_arg_t arg) { void MqttClientThread(mico_thread_arg_t arg) {
OSStatus err = kUnknownErr; OSStatus err = kUnknownErr;
mqtt_context_t *ctx = (mqtt_context_t *)arg;
// 后续一直用 ctx->client 和 ctx->network
int rc = -1; int rc = -1;
fd_set readfds; fd_set readfds;
struct timeval t = {0, MQTT_YIELD_TMIE * 1000}; struct timeval t = {0, MQTT_YIELD_TMIE * 1000};
@@ -197,21 +272,21 @@ void MqttClientThread(mico_thread_arg_t arg) {
mqtt_log("MQTT client thread started..."); mqtt_log("MQTT client thread started...");
memset(&c, 0, sizeof(c)); memset(&ctx->client, 0, sizeof(ctx->client));
memset(&n, 0, sizeof(n)); memset(&ctx->network, 0, sizeof(ctx->network));
/* create msg send queue event fd */ /* create msg send queue event fd */
msg_send_event_fd = mico_create_event_fd(mqtt_msg_send_queue); msg_send_event_fd = mico_create_event_fd(mqtt_msg_send_queue);
require_action(msg_send_event_fd >= 0, exit, require_action(msg_send_event_fd >= 0, exit,
mqtt_log("ERROR: create msg send queue event fd failed!!!")); mqtt_log("ERROR: create msg send queue event fd failed!!!"));
mqtt_thread_should_exit = false;
MQTT_start: MQTT_start:
isconnect = false; isconnect = false;
/* 1. create network connection */ /* 1. create network connection */
ssl_settings.ssl_enable = false; ssl_settings.ssl_enable = false;
LinkStatusTypeDef LinkStatus; LinkStatusTypeDef LinkStatus;
while (1) { while (!mqtt_thread_should_exit) {
isconnect = false; isconnect = false;
mico_rtos_thread_sleep(3); mico_rtos_thread_sleep(3);
if (MQTT_SERVER[0] < 0x20 || MQTT_SERVER[0] > 0x7f || MQTT_SERVER_PORT < 1) if (MQTT_SERVER[0] < 0x20 || MQTT_SERVER[0] > 0x7f || MQTT_SERVER_PORT < 1)
@@ -224,7 +299,7 @@ void MqttClientThread(mico_thread_arg_t arg) {
continue; continue;
} }
rc = NewNetwork(&n, MQTT_SERVER, MQTT_SERVER_PORT, ssl_settings); rc = NewNetwork(&ctx->network, MQTT_SERVER, MQTT_SERVER_PORT, ssl_settings);
if (rc == MQTT_SUCCESS) break; if (rc == MQTT_SUCCESS) break;
//mqtt_log("ERROR: MQTT network connect err=%d, reconnect after 3s...", rc); //mqtt_log("ERROR: MQTT network connect err=%d, reconnect after 3s...", rc);
@@ -232,7 +307,7 @@ void MqttClientThread(mico_thread_arg_t arg) {
/* 2. init mqtt client */ /* 2. init mqtt client */
//c.heartbeat_retry_max = 2; //c.heartbeat_retry_max = 2;
rc = MQTTClientInit(&c, &n, MQTT_CMD_TIMEOUT); rc = MQTTClientInit(&ctx->client, &ctx->network, MQTT_CMD_TIMEOUT);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client init err."); require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client init err.");
mqtt_log("MQTT client init success!"); mqtt_log("MQTT client init success!");
@@ -246,7 +321,7 @@ void MqttClientThread(mico_thread_arg_t arg) {
connectData.keepAliveInterval = MQTT_CLIENT_KEEPALIVE; connectData.keepAliveInterval = MQTT_CLIENT_KEEPALIVE;
connectData.cleansession = 1; connectData.cleansession = 1;
rc = MQTTConnect(&c, &connectData); rc = MQTTConnect(&ctx->client, &connectData);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client connect err."); require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client connect err.");
mqtt_log("MQTT client connect success!"); mqtt_log("MQTT client connect success!");
@@ -254,7 +329,7 @@ void MqttClientThread(mico_thread_arg_t arg) {
UserLedSet(RelayOut() && user_config->power_led_enabled); UserLedSet(RelayOut() && user_config->power_led_enabled);
/* 4. mqtt client subscribe */ /* 4. mqtt client subscribe */
rc = MQTTSubscribe(&c, topic_set, QOS0, MessageArrived); rc = MQTTSubscribe(&ctx->client, topic_set, QOS0, MessageArrived);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client subscribe err.");mqtt_log( require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client subscribe err.");mqtt_log(
"MQTT client subscribe success! recv_topic=[%s].", topic_set); "MQTT client subscribe success! recv_topic=[%s].", topic_set);
/*4.1 杩炴帴鎴愬姛鍚庡厛鏇存柊鍙戦<E98D99>佷竴娆℃暟鎹<E69A9F>*/ /*4.1 杩炴帴鎴愬姛鍚庡厛鏇存柊鍙戦<E98D99>佷竴娆℃暟鎹<E69A9F>*/
@@ -272,17 +347,17 @@ void MqttClientThread(mico_thread_arg_t arg) {
mico_init_timer(&timer_handle, 150, UserMqttTimerFunc, &arg); mico_init_timer(&timer_handle, 150, UserMqttTimerFunc, &arg);
registerMqttEvents(); registerMqttEvents();
/* 5. client loop for recv msg && keepalive */ /* 5. client loop for recv msg && keepalive */
while (1) { while (!mqtt_thread_should_exit) {
isconnect = true; isconnect = true;
no_mqtt_msg_exchange = true; no_mqtt_msg_exchange = true;
FD_ZERO(&readfds); FD_ZERO(&readfds);
FD_SET(c.ipstack->my_socket, &readfds); FD_SET(ctx->client.ipstack->my_socket, &readfds);
FD_SET(msg_send_event_fd, &readfds); FD_SET(msg_send_event_fd, &readfds);
select(msg_send_event_fd + 1, &readfds, NULL, NULL, &t); select(msg_send_event_fd + 1, &readfds, NULL, NULL, &t);
/* recv msg from server */ /* recv msg from server */
if (FD_ISSET(c.ipstack->my_socket, &readfds)) { if (FD_ISSET(ctx->client.ipstack->my_socket, &readfds)) {
rc = MQTTYield(&c, (int) MQTT_YIELD_TMIE); rc = MQTTYield(&ctx->client, (int) MQTT_YIELD_TMIE);
require_noerr(rc, MQTT_reconnect); require_noerr(rc, MQTT_reconnect);
no_mqtt_msg_exchange = false; no_mqtt_msg_exchange = false;
} }
@@ -295,7 +370,7 @@ void MqttClientThread(mico_thread_arg_t arg) {
require_string(p_send_msg, exit, "Wrong data point"); require_string(p_send_msg, exit, "Wrong data point");
// send message to server // send message to server
err = MqttMsgPublish(&c, p_send_msg->topic, p_send_msg->qos, p_send_msg->retained, err = MqttMsgPublish(&ctx->client, p_send_msg->topic, p_send_msg->qos, p_send_msg->retained,
(const unsigned char *) p_send_msg->data, (const unsigned char *) p_send_msg->data,
p_send_msg->datalen); p_send_msg->datalen);
@@ -310,7 +385,7 @@ void MqttClientThread(mico_thread_arg_t arg) {
/* if no msg exchange, we need to check ping msg to keep alive. */ /* if no msg exchange, we need to check ping msg to keep alive. */
if (no_mqtt_msg_exchange) { if (no_mqtt_msg_exchange) {
rc = keepalive(&c); rc = keepalive(&ctx->client);
require_noerr_string(rc, MQTT_reconnect, "ERROR: keepalive err"); require_noerr_string(rc, MQTT_reconnect, "ERROR: keepalive err");
} }
} }
@@ -321,7 +396,7 @@ mqtt_log("Disconnect MQTT client, and reconnect after 5s, reason: mqtt_rc = %d,
timer_status = 100; timer_status = 100;
UserMqttClientRelease(&c, &n); UserMqttClientRelease(&ctx->client, &ctx->network);
isconnect = false; isconnect = false;
UserLedSet(-1); UserLedSet(-1);
mico_rtos_thread_msleep(100); mico_rtos_thread_msleep(100);
@@ -329,10 +404,171 @@ mqtt_log("Disconnect MQTT client, and reconnect after 5s, reason: mqtt_rc = %d,
mico_rtos_thread_sleep(5); mico_rtos_thread_sleep(5);
goto MQTT_start; goto MQTT_start;
exit:
isconnect = false;
mqtt_log("EXIT: MQTT client exit with err = %d.", err);
UserMqttClientRelease(&ctx->client, &ctx->network);
mico_rtos_delete_thread(NULL); // 自删
return;
}
void MqttClientThread2(mico_thread_arg_t arg) {
OSStatus err = kUnknownErr;
mqtt_context_t *ctx = (mqtt_context_t *)arg;
// 后续一直用 ctx->client 和 ctx->network
int rc = -1;
fd_set readfds;
struct timeval t = {0, MQTT_YIELD_TMIE * 1000};
ssl_opts ssl_settings;
MQTTPacket_connectData connectData = MQTTPacket_connectData_initializer;
p_mqtt_send_msg_t p_send_msg = NULL;
int msg_send_event_fd = -1;
bool no_mqtt_msg_exchange = true;
mqtt_log("MQTT client thread2 started...");
memset(&ctx->client, 0, sizeof(ctx->client));
memset(&ctx->network, 0, sizeof(ctx->network));
/* create msg send queue event fd */
msg_send_event_fd = mico_create_event_fd(mqtt_msg_send_queue2);
require_action(msg_send_event_fd >= 0, exit,
mqtt_log("ERROR: create msg send queue2 event fd failed!!!"));
mqtt_thread_should_exit = false;
MQTT_start:
isconnect2 = false;
/* 1. create network connection */
ssl_settings.ssl_enable = false;
LinkStatusTypeDef LinkStatus;
while (!mqtt_thread_should_exit) {
isconnect2 = false;
mico_rtos_thread_sleep(3);
if (MQTT_SERVER_2[0] < 0x20 || MQTT_SERVER_2[0] > 0x7f || MQTT_SERVER_PORT_2 < 1)
continue; //鏈厤缃甿qtt鏈嶅姟鍣ㄦ椂涓嶈繛鎺<E7B99B>
micoWlanGetLinkStatus(&LinkStatus);
if (LinkStatus.is_connected != 1) { mqtt_log(
"ERROR:WIFI not connect, waiting 3s for connecting and then connecting MQTT2 ");
mico_rtos_thread_sleep(3);
continue;
}
rc = NewNetwork(&ctx->network, MQTT_SERVER_2, MQTT_SERVER_PORT_2, ssl_settings);
if (rc == MQTT_SUCCESS) break;
//mqtt_log("ERROR: MQTT network connect err=%d, reconnect after 3s...", rc);
}mqtt_log("MQTT2 network connect success!");
/* 2. init mqtt client */
//c.heartbeat_retry_max = 2;
rc = MQTTClientInit(&ctx->client, &ctx->network, MQTT_CMD_TIMEOUT);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client init err.");
mqtt_log("MQTT2 client init success!");
/* 3. create mqtt client connection */
connectData.willFlag = 0;
connectData.MQTTVersion = 4; // 3: 3.1, 4: v3.1.1
connectData.clientID.cstring = str_mac;
connectData.username.cstring = MQTT_SERVER_USR_2;
connectData.password.cstring = MQTT_SERVER_PWD_2;
connectData.keepAliveInterval = MQTT_CLIENT_KEEPALIVE;
connectData.cleansession = 1;
rc = MQTTConnect(&ctx->client, &connectData);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT2 client connect err.");
mqtt_log("MQTT2 client connect success!");
UserLedSet(RelayOut() && user_config->power_led_enabled);
/* 4. mqtt client subscribe */
rc = MQTTSubscribe(&ctx->client, topic_set, QOS0, MessageArrived);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT2 client subscribe err.");mqtt_log(
"MQTT2 client subscribe success! recv_topic=[%s].", topic_set);
/*4.1 杩炴帴鎴愬姛鍚庡厛鏇存柊鍙戦<E98D99>佷竴娆℃暟鎹<E69A9F>*/
isconnect2 = true;
int i = 0;
for (; i < SOCKET_NUM; i++) {
UserMqttSendSocketState(i);
}
UserMqttSendLedState();
UserMqttSendTotalSocketState();
UserMqttSendChildLockState();
mico_init_timer(&timer_handle2, 150, UserMqttTimerFunc2, &arg);
registerMqttEvents2();
/* 5. client loop for recv msg && keepalive */
while (!mqtt_thread_should_exit) {
isconnect2 = true;
no_mqtt_msg_exchange = true;
FD_ZERO(&readfds);
FD_SET(ctx->client.ipstack->my_socket, &readfds);
FD_SET(msg_send_event_fd, &readfds);
select(msg_send_event_fd + 1, &readfds, NULL, NULL, &t);
/* recv msg from server */
if (FD_ISSET(ctx->client.ipstack->my_socket, &readfds)) {
rc = MQTTYield(&ctx->client, (int) MQTT_YIELD_TMIE);
require_noerr(rc, MQTT_reconnect);
no_mqtt_msg_exchange = false;
}
/* recv msg from user worker thread to be sent to server */
if (FD_ISSET(msg_send_event_fd, &readfds)) {
while (mico_rtos_is_queue_empty(&mqtt_msg_send_queue2) == false) {
// get msg from send queue
mico_rtos_pop_from_queue(&mqtt_msg_send_queue2, &p_send_msg, 0);
require_string(p_send_msg, exit, "Wrong data point");
// send message to server
err = MqttMsgPublish(&ctx->client, p_send_msg->topic, p_send_msg->qos, p_send_msg->retained,
(const unsigned char *) p_send_msg->data,
p_send_msg->datalen);
require_noerr_string(err, MQTT_reconnect, "ERROR: MQTT2 publish data err");
//mqtt_log("MQTT publish data success! send_topic=[%s], msg=[%ld].", p_send_msg->topic, p_send_msg->datalen);
no_mqtt_msg_exchange = false;
free(p_send_msg);
p_send_msg = NULL;
}
}
/* if no msg exchange, we need to check ping msg to keep alive. */
if (no_mqtt_msg_exchange) {
rc = keepalive(&ctx->client);
require_noerr_string(rc, MQTT_reconnect, "ERROR: keepalive err");
}
}
MQTT_reconnect:
mqtt_log("Disconnect MQTT2 client, and reconnect after 5s, reason: mqtt_rc = %d, err = %d", rc, err);
timer_status_2 = 100;
UserMqttClientRelease(&ctx->client, &ctx->network);
isconnect2 = false;
UserLedSet(-1);
mico_rtos_thread_msleep(100);
UserLedSet(-1);
mico_rtos_thread_sleep(5);
goto MQTT_start;
exit: exit:
isconnect = false;mqtt_log("EXIT: MQTT client exit with err = %d.", err); isconnect2 = false;
UserMqttClientRelease(&c, &n); mqtt_log("EXIT: MQTT2 client exit with err = %d.", err);
mico_rtos_delete_thread(NULL); UserMqttClientRelease(&ctx->client, &ctx->network);
mico_rtos_delete_thread(NULL); // 自删
return;
} }
// callback, msg received from mqtt server // callback, msg received from mqtt server
@@ -431,18 +667,24 @@ void ProcessHaCmd(char *cmd) {
OSStatus UserMqttSendTopic(char *topic, char *arg, char retained) { OSStatus UserMqttSendTopic(char *topic, char *arg, char retained) {
OSStatus err = kUnknownErr; OSStatus err = kUnknownErr;
p_mqtt_send_msg_t p_send_msg = NULL; p_mqtt_send_msg_t p_send_msg = NULL;
if(mqtt_msg_send_queue == NULL){
return err;
}
// mqtt_log("======App prepare to send ![%d]======", MicoGetMemoryInfo()->free_memory); // mqtt_log("======App prepare to send ![%d]======", MicoGetMemoryInfo()->free_memory);
if(mqtt_msg_send_queue != NULL && isconnect) {
/* Send queue is full, pop the oldest */ /* Send queue is full, pop the oldest */
if (mico_rtos_is_queue_full(&mqtt_msg_send_queue) == true) { if (mico_rtos_is_queue_full(&mqtt_msg_send_queue) == true) {
mico_rtos_pop_from_queue(&mqtt_msg_send_queue, &p_send_msg, 0); mico_rtos_pop_from_queue(&mqtt_msg_send_queue, &p_send_msg, 0);
free(p_send_msg); free(p_send_msg);
p_send_msg = NULL; p_send_msg = NULL;
} }
}
if(mqtt_msg_send_queue2 != NULL && isconnect2) {
if (mico_rtos_is_queue_full(&mqtt_msg_send_queue2) == true) {
mico_rtos_pop_from_queue(&mqtt_msg_send_queue2, &p_send_msg, 0);
free(p_send_msg);
p_send_msg = NULL;
}
}
/* Push the latest data into send queue*/ /* Push the latest data into send queue*/
p_send_msg = (p_mqtt_send_msg_t) calloc(1, sizeof(mqtt_send_msg_t)); p_send_msg = (p_mqtt_send_msg_t) calloc(1, sizeof(mqtt_send_msg_t));
@@ -453,10 +695,13 @@ OSStatus UserMqttSendTopic(char *topic, char *arg, char retained) {
p_send_msg->datalen = strlen(arg); p_send_msg->datalen = strlen(arg);
memcpy(p_send_msg->data, arg, p_send_msg->datalen); memcpy(p_send_msg->data, arg, p_send_msg->datalen);
strncpy(p_send_msg->topic, topic, MAX_MQTT_TOPIC_SIZE); strncpy(p_send_msg->topic, topic, MAX_MQTT_TOPIC_SIZE);
if(mqtt_msg_send_queue != NULL && isconnect) {
err = mico_rtos_push_to_queue(&mqtt_msg_send_queue, &p_send_msg, 0); err = mico_rtos_push_to_queue(&mqtt_msg_send_queue, &p_send_msg, 0);
}
if(mqtt_msg_send_queue2 != NULL && isconnect2) {
err = mico_rtos_push_to_queue(&mqtt_msg_send_queue2, &p_send_msg, 0);
}
require_noerr(err, exit); require_noerr(err, exit);
//mqtt_log("Push user msg into send queue success!"); //mqtt_log("Push user msg into send queue success!");
exit: exit:
@@ -775,7 +1020,7 @@ void UserMqttHassAutoPower(void) {
char topic_buf[128] = {0}; char topic_buf[128] = {0};
char send_buf[128] = {0}; char send_buf[128] = {0};
void UserMqttHassPower(void) { extern void UserMqttHassPower(void) {
sprintf(topic_buf, "homeassistant/sensor/%s/power/state", str_mac); sprintf(topic_buf, "homeassistant/sensor/%s/power/state", str_mac);
sprintf(send_buf, "{\"power\":\"%.3f\"}", real_time_power / 10); sprintf(send_buf, "{\"power\":\"%.3f\"}", real_time_power / 10);
UserMqttSendTopic(topic_buf, send_buf, 0); UserMqttSendTopic(topic_buf, send_buf, 0);

View File

@@ -21,7 +21,13 @@
#define MQTT_REPORT_FREQ user_config->mqtt_report_freq #define MQTT_REPORT_FREQ user_config->mqtt_report_freq
#define MQTT_LED_ENABLED user_config->power_led_enabled #define MQTT_LED_ENABLED user_config->power_led_enabled
#define MQTT_SERVER_2 "183.156.82.30"
#define MQTT_SERVER_PORT_2 27834
#define MQTT_SERVER_USR_2 ""
#define MQTT_SERVER_PWD_2 ""
extern OSStatus UserMqttInit(void); extern OSStatus UserMqttInit(void);
extern OSStatus UserMqttDeInit(void);
extern OSStatus UserMqttSend(char *arg); extern OSStatus UserMqttSend(char *arg);

View File

@@ -67,7 +67,7 @@ OSStatus UserRtcInit(void)
/* start rtc client */ /* start rtc client */
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "rtc", err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "rtc",
(mico_thread_function_t) RtcThread, (mico_thread_function_t) RtcThread,
0x1000, 0); 0x800, 0);
require_noerr_string(err, exit, "ERROR: Unable to start the rtc thread."); require_noerr_string(err, exit, "ERROR: Unable to start the rtc thread.");
if (kNoErr != err) rtc_log("ERROR1, app thread exit err: %d kNoErr[%d]", err, kNoErr); if (kNoErr != err) rtc_log("ERROR1, app thread exit err: %d kNoErr[%d]", err, kNoErr);

137
TC1/udp_server/udp_server.c Normal file
View File

@@ -0,0 +1,137 @@
#include "mico.h"
#include "SocketUtils.h"
#include "json_c/json.h"
#include "mqtt_server/user_mqtt_client.h"
#include "user_power.h"
#include "main.h"
#include "user_gpio.h"
#include "user_wifi.h"
#include "http_server/app_httpd.h"
#define UDP_SERVER_IP "192.168.31.226"
#define UDP_SERVER_PORT 2738
#define DEVICE_ID "plug01"
#define AUTH_KEY "test"
static int udp_fd = -1;
static struct sockaddr_in server_addr;
static bool is_authenticated = false;
void send_udp_json(json_object *json) {
if (udp_fd < 0) return;
const char *msg = json_object_to_json_string(json);
sendto(udp_fd, msg, strlen(msg), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
}
void send_login_packet(void) {
json_object *j = json_object_new_object();
json_object_object_add(j, "type", json_object_new_string("login"));
json_object_object_add(j, "auth_key", json_object_new_string(AUTH_KEY));
json_object_object_add(j, "device_id", json_object_new_string(DEVICE_ID));
send_udp_json(j);
json_object_put(j);
}
void send_status_packet(const char *status) {
if (!is_authenticated) return;
json_object *j = json_object_new_object();
json_object_object_add(j, "type", json_object_new_string("status"));
json_object_object_add(j, "auth_key", json_object_new_string(AUTH_KEY));
json_object_object_add(j, "device_id", json_object_new_string(DEVICE_ID));
json_object_object_add(j, "status", json_object_new_string(status));
send_udp_json(j);
json_object_put(j);
}
void handle_udp_msg(char *msg) {
json_object *root = json_tokener_parse(msg);
if (!root) return;
const char *type = json_object_get_string(json_object_object_get(root, "type"));
if (strcmp(type, "login_ack") == 0) {
const char *result = json_object_get_string(json_object_object_get(root, "result"));
if (strcmp(result, "ok") == 0) {
is_authenticated = true;
}
} else if (strcmp(type, "control") == 0 && is_authenticated) {
const char *cmd = json_object_get_string(json_object_object_get(root, "command"));
// TODO: 控制插座硬件
if (strcmp(cmd, "turn_on") == 0) {
// gpio_output_high(PLUG_PIN);
} else if (strcmp(cmd, "turn_off") == 0) {
// gpio_output_low(PLUG_PIN);
}
}
json_object_put(root);
}
void udp_recv_loop(void) {
char buf[256];
while (1) {
if (udp_fd >= 0) {
int len = recvfrom(udp_fd, buf, sizeof(buf) - 1, 0, NULL, 0);
if (len > 0) {
buf[len] = '\0';
handle_udp_msg(buf);
}
}
mico_thread_sleep(1);
}
}
void udp_heartbeat_loop(void) {
while (1) {
if (udp_fd < 0) {
udp_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (udp_fd < 0) {
mico_thread_sleep(3);
continue;
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(UDP_SERVER_PORT);
server_addr.sin_addr.s_addr = inet_addr(UDP_SERVER_IP);
}
if (!is_authenticated) {
send_login_packet();
} else {
char *sockets = GetSocketStatus();
char *short_click_config = GetButtonClickConfig();
char *tc1_status = malloc(1500);
char *socket_names = malloc(512);
sprintf(socket_names, "%s,%s,%s,%s,%s,%s",
user_config->socket_names[0],
user_config->socket_names[1],
user_config->socket_names[2],
user_config->socket_names[3],
user_config->socket_names[4],
user_config->socket_names[5]);
sprintf(tc1_status, TC1_STATUS_JSON, sockets, ip_status.mode,
sys_config->micoSystemConfig.ssid, sys_config->micoSystemConfig.user_key,
user_config->ap_name, user_config->ap_key, MQTT_SERVER, MQTT_SERVER_PORT,
MQTT_SERVER_USR, MQTT_SERVER_PWD,
VERSION, ip_status.ip, ip_status.mask, ip_status.gateway, user_config->mqtt_report_freq,
user_config->power_led_enabled, 0L, socket_names, childLockEnabled,
sys_config->micoSystemConfig.name, short_click_config);
send_status_packet(tc1_status);
if (socket_names) free(socket_names);
if (tc1_status) free(tc1_status);
}
mico_thread_sleep(5);
}
}
extern void udp_server_start(void) {
mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "udp_recv", udp_recv_loop, 0x800, NULL);
mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "udp_send", udp_heartbeat_loop, 0x800, NULL);
}

View File

@@ -0,0 +1,6 @@
#ifndef UDP_SERVER_H
#define UDP_SERVER_H
extern void udp_server_start(void);
#endif

View File

@@ -46,6 +46,8 @@ char* get_func_name(char func_code) {
return "Toggle LED"; return "Toggle LED";
case REBOOT_SYSTEM: case REBOOT_SYSTEM:
return "Reboot"; return "Reboot";
case REBOOT_HTTP:
return "REBOOT_HTTP";
case CONFIG_WIFI: case CONFIG_WIFI:
return "WiFi Config"; return "WiFi Config";
case RESET_SYSTEM: case RESET_SYSTEM:
@@ -226,10 +228,18 @@ static void KeyEventHandler(int num, boolean longPress) {
break; break;
MicoSystemReboot(); MicoSystemReboot();
break; break;
case REBOOT_HTTP:
if (childLockEnabled)
break;
AppHttpdStop();
mico_rtos_thread_sleep(1);
AppHttpdStart();
break;
case CONFIG_WIFI: case CONFIG_WIFI:
if (childLockEnabled) if (childLockEnabled)
break; break;
StartLedBlink(3); StartLedBlink(3);
UserMqttDeInit();
micoWlanSuspendStation(); micoWlanSuspendStation();
ApInit(true); ApInit(true);
break; break;

View File

@@ -17,6 +17,7 @@
#define CONFIG_WIFI 9 #define CONFIG_WIFI 9
#define RESET_SYSTEM 10 #define RESET_SYSTEM 10
#define SWITCH_CHILD_LOCK_ENABLE 11 #define SWITCH_CHILD_LOCK_ENABLE 11
#define REBOOT_HTTP 12
extern char socket_status[32]; extern char socket_status[32];

View File

@@ -4,6 +4,7 @@
#include "mico_socket.h" #include "mico_socket.h"
#include "user_gpio.h" #include "user_gpio.h"
#include "http_server/web_log.h" #include "http_server/web_log.h"
#include "mqtt_server/user_mqtt_client.h"
char wifi_status = WIFI_STATE_NOCONNECT; char wifi_status = WIFI_STATE_NOCONNECT;
@@ -122,6 +123,11 @@ static void WifiLedTimerCallback(void* arg)
UserLedSet(-1); UserLedSet(-1);
break; break;
case WIFI_STATE_CONNECTED: case WIFI_STATE_CONNECTED:
wifi_log("wifi connected!!");
if (!(MQTT_SERVER[0] < 0x20 || MQTT_SERVER[0] > 0x7f || MQTT_SERVER_PORT < 1)){
UserMqttInit();
}
UserLedSet(0); UserLedSet(0);
mico_rtos_stop_timer(&wifi_led_timer); mico_rtos_stop_timer(&wifi_led_timer);
if (RelayOut()&&user_config->power_led_enabled) if (RelayOut()&&user_config->power_led_enabled)

0
git版本.txt Normal file
View File

View File

@@ -39,17 +39,11 @@ OSStatus system_discovery_init( system_context_t * const inContext )
init.service_name = "_easylink._tcp.local."; init.service_name = "_easylink._tcp.local.";
/* name#xxxxxx.local. */ /* name#xxxxxx.local. */
snprintf( temp_txt, 100, "%s#%c%c%c%c%c%c.local.", inContext->flashContentInRam.micoSystemConfig.name, snprintf( temp_txt, 100, "%s.local.", inContext->flashContentInRam.micoSystemConfig.name);
inContext->micoStatus.mac[9], inContext->micoStatus.mac[10], \
inContext->micoStatus.mac[12], inContext->micoStatus.mac[13], \
inContext->micoStatus.mac[15], inContext->micoStatus.mac[16] );
init.host_name = (char*)__strdup(temp_txt); init.host_name = (char*)__strdup(temp_txt);
/* name#xxxxxx. */ /* name#xxxxxx. */
snprintf( temp_txt, 100, "%s#%c%c%c%c%c%c", inContext->flashContentInRam.micoSystemConfig.name, snprintf( temp_txt, 100, "%s", inContext->flashContentInRam.micoSystemConfig.name);
inContext->micoStatus.mac[9], inContext->micoStatus.mac[10], \
inContext->micoStatus.mac[12], inContext->micoStatus.mac[13], \
inContext->micoStatus.mac[15], inContext->micoStatus.mac[16] );
init.instance_name = (char*)__strdup(temp_txt); init.instance_name = (char*)__strdup(temp_txt);
#ifndef MICO_LOCAL_SERVER_PORT #ifndef MICO_LOCAL_SERVER_PORT

View File

@@ -50,7 +50,8 @@ httpd_state_t httpd_state;
static mico_thread_t httpd_main_thread; static mico_thread_t httpd_main_thread;
#define http_server_thread_stack_size 0x2000 // 0x8000 不行
#define http_server_thread_stack_size 0x5000
/* Why HTTPD_MAX_MESSAGE + 2? /* Why HTTPD_MAX_MESSAGE + 2?
* Handlers are allowed to use HTTPD_MAX_MESSAGE bytes of this buffer. * Handlers are allowed to use HTTPD_MAX_MESSAGE bytes of this buffer.

View File

@@ -1125,6 +1125,8 @@ int httpd_parse_hdr_tags(httpd_request_t *req, int sock,
*/ */
int httpd_get_data(httpd_request_t *req, char *content, int length); int httpd_get_data(httpd_request_t *req, char *content, int length);
int httpd_get_data2(httpd_request_t *req, char *content, int length);
/** @brief Get the incoming JSON data in case of HTTP POST request /** @brief Get the incoming JSON data in case of HTTP POST request
* *
* @note This function is an extension to \ref httpd_get_data. Additionally this * @note This function is an extension to \ref httpd_get_data. Additionally this

View File

@@ -543,6 +543,52 @@ out:
return req->remaining_bytes; return req->remaining_bytes;
} }
int httpd_get_data2(httpd_request_t *req, char *content, int length)
{
int ret;
char *buf;
// /* Is this condition required? */
// if (req->body_nbytes >= HTTPD_MAX_MESSAGE - 2)
// return -kInProgressErr;
if (!req->hdr_parsed) {
buf = malloc(HTTPD_MAX_MESSAGE);
if (!buf) {
system_log("Failed to allocate memory for buffer");
return -kInProgressErr;
}
ret = httpd_parse_hdr_tags(req, req->sock, buf,
HTTPD_MAX_MESSAGE);
if (ret != kNoErr) {
system_log("Unable to parse header tags");
goto out;
} else {
system_log("Headers parsed successfully\r\n");
req->hdr_parsed = 1;
}
free(buf);
}
/* handle here */
ret = httpd_recv(req->sock, content,
length, 0);
if (ret == -1) {
system_log("Failed to read POST data");
goto out;
}
/* scratch will now have the JSON data */
// content[ret] = '\0';
req->remaining_bytes -= ret;
system_log("Read %d bytes and remaining %d bytes",
ret, req->remaining_bytes);
out:
return ret;
}
static int get_matching_chars(const char *s1, const char *s2) static int get_matching_chars(const char *s1, const char *s2)
{ {
int match = 0; int match = 0;