14 Commits

Author SHA1 Message Date
oopuuu
8496e8cfd6 Update README.md
增加烧录说明引用
2025-05-08 17:02:34 +08:00
nhkefus
ade64139cb Merge branch 'dev_file_ota'
# Conflicts:
#	TC1/http_server/app_httpd.c
#	TC1/http_server/web/index.html
#	TC1/mqtt_server/user_mqtt_client.c
#	TC1/ota_server/ota_server.c
#	mico-os/libraries/daemons/http_server/httpd.c
2025-04-28 16:19:53 +08:00
nhkefus
eaf8f5bf60 去除web后台没数据时的默认值,修复hass中重启按钮按了以后 同一mqtt服务中的所有插座都重启的问题 2025-04-28 16:11:35 +08:00
Your Name
5eecfefc74 尝试修复mqtt重连时内存泄漏问题 2025-04-25 11:30:43 +08:00
Your Name
0c675c6f03 尝试修复日志中的定时器错误 2025-04-25 10:02:25 +08:00
oopuuu
e352b74e19 Update README.md 2025-04-19 15:36:15 +08:00
nhkefus
55a5f93148 调试用 2025-04-09 17:27:30 +08:00
nhkefus
86b78d8a4e 调试用 2025-04-09 17:06:49 +08:00
nhkefus
d8099ad499 调试用 2025-04-09 16:59:16 +08:00
nhkefus
4aca161327 调试用 2025-04-09 15:11:52 +08:00
nhkefus
67aa42fdd9 调试用 2025-04-09 14:54:46 +08:00
Your Name
6e3a48cba6 修复自定义名称过长可能导致系统崩溃的问题 2025-04-08 23:00:40 +08:00
nhkefus
fea21ab02a 更新了一些新版SDK中 ota和http相关的代码,不知道有没有用 2025-04-08 13:29:35 +08:00
nhkefus
49847dc77c 尝试增加https下载ota文件的功能,增加后台直接上传ota bin文件来升级的功能 2025-04-03 16:05:55 +08:00
16 changed files with 1505 additions and 1811 deletions

View File

@@ -60,7 +60,9 @@ TC1 排插硬件分 A1 A2 两个版本, 本固件仅支持 **A1 版本**. A1 A2
- [x] 后台可自定义设备名称此名称将会同至ha mqtt作为mqtt中插座名称的前缀
- [x] 后台可自定义按键连击,长按等功能
- [x] 定时开关现在支持更多操作项,与按键功能自定义一样
- [x] 现在可以上传本地文件来更新固件,同时可以在最新发布的固件说明中参考使用我搭建的文件服务来在线更新
# 固件烧录
- 参考原始固件代码提供者[a2633063](https://github.com/a2633063/zTC1/wiki/固件烧录)大佬提供的说明
# 编译固件
- windows环境先安装python2.7,下载安装的时候添加环境变量到Path默认安装路径需要添加两个环境变量C:\Python27C:\Python27\Scripts

View File

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

View File

@@ -11,7 +11,6 @@
#include "time_server/user_rtc.h"
#include "user_power.h"
#include "http_server/app_httpd.h"
#include "udp_server/udp_server.h"
#include "timed_task/timed_task.h"
char rtc_init = 0; //sntp校时成功标志位
@@ -190,10 +189,7 @@ int application_start(void) {
require_noerr(err, exit);
PowerInit();
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);
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "p_count",

View File

@@ -36,18 +36,10 @@ typedef struct {
uint32_t datalen;
} 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 MessageArrived(MessageData *md);
static void MqttClientThread2(mico_thread_arg_t arg);
static OSStatus
MqttMsgPublish(Client *c, const char *topic, char qos, char retained, const unsigned char *msg,
uint32_t msg_len);
@@ -57,14 +49,13 @@ OSStatus UserRecvHandler(void *arg);
void ProcessHaCmd(char *cmd);
bool isconnect = false;
bool isconnect2 = false;
mico_queue_t mqtt_msg_send_queue = NULL;
mico_queue_t mqtt_msg_send_queue2 = NULL;
Client c; // mqtt client object
Network n; // socket network for mqtt client
volatile bool mqtt_thread_should_exit = false;
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;
char topic_state[MAX_MQTT_TOPIC_SIZE];
@@ -72,8 +63,6 @@ char topic_set[MAX_MQTT_TOPIC_SIZE];
mico_timer_t timer_handle;
static char timer_status = 0;
mico_timer_t timer_handle2;
static char timer_status_2 = 0;
void UserMqttTimerFunc(void *arg) {
LinkStatusTypeDef LinkStatus;
@@ -110,41 +99,6 @@ 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;
@@ -154,10 +108,23 @@ OSStatus UserMqttDeInit(void) {
return err;
}
void clear_mqtt_msg_send_queue(void) {
if(mqtt_msg_send_queue == NULL){
return;
}
void *msg = NULL;
while (mico_rtos_is_queue_empty(&mqtt_msg_send_queue) == false) {
if (mico_rtos_pop_from_queue(&mqtt_msg_send_queue, &msg, 0) == kNoErr) {
if (msg) free(msg); // 释放消息内存,避免泄漏
}
}
}
/* Application entrance */
OSStatus UserMqttInit(void) {
OSStatus err = kNoErr;
if(mqtt_msg_send_queue != NULL)
return err;
sprintf(topic_set, MQTT_CLIENT_SUB_TOPIC1);
sprintf(topic_state, MQTT_CLIENT_PUB_TOPIC, str_mac);
//TODO size:0x800
@@ -174,28 +141,14 @@ OSStatus UserMqttInit(void) {
require_noerr_action(err, exit, mqtt_log("ERROR: create mqtt msg send queue err=%d.", err));
/* start mqtt client */
mqtt_context_t *ctx1 = malloc(sizeof(mqtt_context_t));
memset(ctx1, 0, sizeof(mqtt_context_t));
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mqtt_client_1",
(mico_thread_function_t)MqttClientThread,
mqtt_thread_stack_size, ctx1);
err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mqtt_client",
(mico_thread_function_t) MqttClientThread,
mqtt_thread_stack_size, 0);
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 */
err = mico_rtos_create_worker_thread(&mqtt_client_worker_thread, MICO_APPLICATION_PRIORITY,
0x1000, 5);
0x800, 5);
require_noerr_string(err, exit, "ERROR: Unable to start the mqtt client worker thread.");
exit:
@@ -206,13 +159,32 @@ OSStatus UserMqttInit(void) {
static OSStatus UserMqttClientRelease(Client *c, Network *n) {
OSStatus err = kNoErr;
if (c->isconnected) MQTTDisconnect(c);
if (c == NULL || n == NULL) return kParamErr;
n->disconnect(n); // close connection
if (c->isconnected) {
MQTTDisconnect(c);
c->isconnected = 0;
}
if (MQTT_SUCCESS != MQTTClientDeinit(c)) { mqtt_log("MQTTClientDeinit failed!");
if (c->buf) {
free(c->buf);
c->buf = NULL;
}
if (c->readbuf) {
free(c->readbuf);
c->readbuf = NULL;
}
if (n->disconnect) {
n->disconnect(n);
}
if (MQTT_SUCCESS != MQTTClientDeinit(c)) {
mqtt_log("MQTTClientDeinit failed!");
err = kDeletedErr;
}
return err;
}
@@ -247,18 +219,16 @@ static OSStatus MqttMsgPublish(Client *c, const char *topic, char qos, char reta
}
void registerMqttEvents(void) {
if(timer_status !=0){
mico_stop_timer(&timer_handle);
}
timer_status = 0;
mico_start_timer(&timer_handle);
}
void registerMqttEvents2(void) {
timer_status_2 = 0;
mico_start_timer(&timer_handle2);
}
void MqttClientThread(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};
@@ -272,11 +242,13 @@ void MqttClientThread(mico_thread_arg_t arg) {
mqtt_log("MQTT client thread started...");
memset(&ctx->client, 0, sizeof(ctx->client));
memset(&ctx->network, 0, sizeof(ctx->network));
memset(&c, 0, sizeof(c));
memset(&n, 0, sizeof(n));
/* create msg send queue event fd */
msg_send_event_fd = mico_create_event_fd(mqtt_msg_send_queue);
mico_init_timer(&timer_handle, 150, UserMqttTimerFunc, &arg);
require_action(msg_send_event_fd >= 0, exit,
mqtt_log("ERROR: create msg send queue event fd failed!!!"));
mqtt_thread_should_exit = false;
@@ -299,15 +271,16 @@ void MqttClientThread(mico_thread_arg_t arg) {
continue;
}
rc = NewNetwork(&ctx->network, MQTT_SERVER, MQTT_SERVER_PORT, ssl_settings);
rc = NewNetwork(&n, MQTT_SERVER, MQTT_SERVER_PORT, ssl_settings);
if (rc == MQTT_SUCCESS) break;
//mqtt_log("ERROR: MQTT network connect err=%d, reconnect after 3s...", rc);
}mqtt_log("MQTT network connect success!");
}
mqtt_log("MQTT network connect success!");
/* 2. init mqtt client */
//c.heartbeat_retry_max = 2;
rc = MQTTClientInit(&ctx->client, &ctx->network, MQTT_CMD_TIMEOUT);
rc = MQTTClientInit(&c, &n, MQTT_CMD_TIMEOUT);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client init err.");
mqtt_log("MQTT client init success!");
@@ -321,15 +294,15 @@ void MqttClientThread(mico_thread_arg_t arg) {
connectData.keepAliveInterval = MQTT_CLIENT_KEEPALIVE;
connectData.cleansession = 1;
rc = MQTTConnect(&ctx->client, &connectData);
rc = MQTTConnect(&c, &connectData);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client connect err.");
mqtt_log("MQTT client connect success!");
mqtt_log("MQTT client connect success, result: %d ", rc);
UserLedSet(RelayOut() && user_config->power_led_enabled);
/* 4. mqtt client subscribe */
rc = MQTTSubscribe(&ctx->client, topic_set, QOS0, MessageArrived);
rc = MQTTSubscribe(&c, topic_set, QOS0, MessageArrived);
require_noerr_string(rc, MQTT_reconnect, "ERROR: MQTT client subscribe err.");mqtt_log(
"MQTT client subscribe success! recv_topic=[%s].", topic_set);
/*4.1 杩炴帴鎴愬姛鍚庡厛鏇存柊鍙戦<E98D99>佷竴娆℃暟鎹<E69A9F>*/
@@ -344,20 +317,19 @@ void MqttClientThread(mico_thread_arg_t arg) {
UserMqttSendTotalSocketState();
UserMqttSendChildLockState();
mico_init_timer(&timer_handle, 150, UserMqttTimerFunc, &arg);
registerMqttEvents();
/* 5. client loop for recv msg && keepalive */
while (!mqtt_thread_should_exit) {
isconnect = true;
no_mqtt_msg_exchange = true;
FD_ZERO(&readfds);
FD_SET(ctx->client.ipstack->my_socket, &readfds);
FD_SET(c.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);
if (FD_ISSET(c.ipstack->my_socket, &readfds)) {
rc = MQTTYield(&c, (int) MQTT_YIELD_TMIE);
require_noerr(rc, MQTT_reconnect);
no_mqtt_msg_exchange = false;
}
@@ -370,22 +342,21 @@ void MqttClientThread(mico_thread_arg_t arg) {
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,
err = MqttMsgPublish(&c, p_send_msg->topic, p_send_msg->qos, p_send_msg->retained,
(const unsigned char *) p_send_msg->data,
p_send_msg->datalen);
free(p_send_msg);
p_send_msg = NULL;
require_noerr_string(err, MQTT_reconnect, "ERROR: MQTT 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);
rc = keepalive(&c);
require_noerr_string(rc, MQTT_reconnect, "ERROR: keepalive err");
}
}
@@ -395,8 +366,8 @@ void MqttClientThread(mico_thread_arg_t arg) {
mqtt_log("Disconnect MQTT client, and reconnect after 5s, reason: mqtt_rc = %d, err = %d", rc, err);
timer_status = 100;
UserMqttClientRelease(&ctx->client, &ctx->network);
clear_mqtt_msg_send_queue();
UserMqttClientRelease(&c, &n);
isconnect = false;
UserLedSet(-1);
mico_rtos_thread_msleep(100);
@@ -407,166 +378,7 @@ mqtt_log("Disconnect MQTT client, and reconnect after 5s, reason: mqtt_rc = %d,
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:
isconnect2 = false;
mqtt_log("EXIT: MQTT2 client exit with err = %d.", err);
UserMqttClientRelease(&ctx->client, &ctx->network);
UserMqttClientRelease(&c, &n);
mico_rtos_delete_thread(NULL); // 自删
return;
}
@@ -659,7 +471,9 @@ void ProcessHaCmd(char *cmd) {
childLockEnabled = on;
UserMqttSendChildLockState();
mico_system_context_update(sys_config);
}else if (strcmp(cmd, "reboot") == 0) {
}else if (strcmp(cmd, "reboot") == ' ') {
sscanf(cmd, "reboot %s", mac);
if (strcmp(mac, str_mac)) return;
MicoSystemReboot(); // 立即重启设备
}
}
@@ -667,23 +481,17 @@ void ProcessHaCmd(char *cmd) {
OSStatus UserMqttSendTopic(char *topic, char *arg, char retained) {
OSStatus err = kUnknownErr;
p_mqtt_send_msg_t p_send_msg = NULL;
if(mqtt_msg_send_queue == NULL|| !isconnect){
return err;
}
// mqtt_log("======App prepare to send ![%d]======", MicoGetMemoryInfo()->free_memory);
if(mqtt_msg_send_queue != NULL && isconnect) {
/* Send queue is full, pop the oldest */
if (mico_rtos_is_queue_full(&mqtt_msg_send_queue) == true) {
mico_rtos_pop_from_queue(&mqtt_msg_send_queue, &p_send_msg, 0);
free(p_send_msg);
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;
}
/* Send queue is full, pop the oldest */
if (mico_rtos_is_queue_full(&mqtt_msg_send_queue) == true) {
mico_rtos_pop_from_queue(&mqtt_msg_send_queue, &p_send_msg, 0);
free(p_send_msg);
p_send_msg = NULL;
}
/* Push the latest data into send queue*/
@@ -695,13 +503,10 @@ OSStatus UserMqttSendTopic(char *topic, char *arg, char retained) {
p_send_msg->datalen = strlen(arg);
memcpy(p_send_msg->data, arg, p_send_msg->datalen);
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);
}
if(mqtt_msg_send_queue2 != NULL && isconnect2) {
err = mico_rtos_push_to_queue(&mqtt_msg_send_queue2, &p_send_msg, 0);
}
err = mico_rtos_push_to_queue(&mqtt_msg_send_queue, &p_send_msg, 0);
require_noerr(err, exit);
//mqtt_log("Push user msg into send queue success!");
exit:
@@ -823,13 +628,13 @@ void UserMqttHassAutoRebootButton(void) {
"\"uniq_id\":\"tc1_%s_reboot\","
"\"object_id\":\"tc1_%s_reboot\","
"\"cmd_t\":\"device/ztc1/set\","
"\"pl_prs\":\"reboot\","
"\"pl_prs\":\"reboot %s\","
"\"device\":{"
"\"identifiers\":[\"tc1_%s\"],"
"\"name\":\"%s\","
"\"model\":\"TC1\","
"\"manufacturer\":\"PHICOMM\"}}",
str_mac,str_mac,str_mac, sys_config->micoSystemConfig.name);
str_mac,str_mac,str_mac,str_mac, sys_config->micoSystemConfig.name);
UserMqttSendTopic(topic_buf, send_buf, 1);
}
if (send_buf) free(send_buf);

View File

@@ -21,11 +21,6 @@
#define MQTT_REPORT_FREQ user_config->mqtt_report_freq
#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 UserMqttDeInit(void);

View File

@@ -32,7 +32,7 @@
#define __ota_server_H
#define OTA_DEBUG (1)
#define OTA_USE_HTTPS (0)
#define OTA_USE_HTTPS (1)
#define OTA_MD5_LENTH 32
#define OTA_SEND_HEAD_SIZE 256
@@ -49,8 +49,8 @@ typedef enum _OTA_STATE_E{
}OTA_STATE_E;
typedef enum _HTTP_SECURITY_E{
HTTP_SECURITY_HTTP,
HTTP_SECURITY_HTTPS
HTTP_SECURITY_HTTP,
HTTP_SECURITY_HTTPS
} HTTP_SECURITY_E;
typedef enum _OTA_CONTROL_E{
@@ -87,11 +87,11 @@ typedef struct _ota_check_t{
typedef void (*ota_server_cb_fn) (OTA_STATE_E state, float progress);
typedef struct _ota_server_context_t{
download_url_t download_url;
download_state_t download_state;
ota_check_t ota_check;
OTA_CONTROL_E ota_control;
ota_server_cb_fn ota_server_cb;
download_url_t download_url;
download_state_t download_state;
ota_check_t ota_check;
OTA_CONTROL_E ota_control;
ota_server_cb_fn ota_server_cb;
} ota_server_context_t;
@@ -109,34 +109,34 @@ typedef struct _ota_server_context_t{
* @return kNoErr : on success.
* @return kGeneralErr : if an error occurred
*/
OSStatus OtaServerStart(char *url, char *md5, ota_server_cb_fn call_back);
OSStatus ota_server_start( char *url, char *md5, ota_server_cb_fn call_back );
/** @brief Get OTA server state
*
* @return OTA_CONTROL_E : state
*/
OTA_CONTROL_E OtaServerStateGet(void);
OTA_CONTROL_E ota_server_state_get( void );
/** @brief Pause OTA server daemons
*
* @return No
*/
void OtaServerPause(void);
void ota_server_pause( void );
/** @brief Continue OTA server daemons
*
* @return No
*/
void OtaServerContinue(void);
void ota_server_continue( void );
/** @brief Stop OTA server daemons
*
* @return No
*/
void OtaServerStop(void);
void ota_server_stop( void );
#endif
#endif

View File

@@ -36,6 +36,6 @@ void UserOtaStart(char *url, char *md5)
{
ota_progress = 0;
ota_log("ready to ota:%s",url);
OtaServerStart(url, md5, OtaServerStatusHandler);
ota_server_start(url, md5, OtaServerStatusHandler);
}

View File

@@ -1,137 +0,0 @@
#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

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

View File

@@ -123,11 +123,9 @@ static void WifiLedTimerCallback(void* arg)
UserLedSet(-1);
break;
case WIFI_STATE_CONNECTED:
wifi_log("wifi connected!!");
if (!(MQTT_SERVER[0] < 0x20 || MQTT_SERVER[0] > 0x7f || MQTT_SERVER_PORT < 1)){
UserMqttInit();
}
if (!(MQTT_SERVER[0] < 0x20 || MQTT_SERVER[0] > 0x7f || MQTT_SERVER_PORT < 1)){
UserMqttInit();
}
UserLedSet(0);
mico_rtos_stop_timer(&wifi_led_timer);
if (RelayOut()&&user_config->power_led_enabled)

View File

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

View File

@@ -58,173 +58,203 @@ static httpd_request_t httpd_req;
int httpd_send_chunk_begin(int conn, int size)
{
int err;
char buf[CHUNK_SIZE_DIGITS];
int i;
int digit;
int begin = 1;
int err;
char buf[CHUNK_SIZE_DIGITS];
int i;
int digit;
int begin = 1;
for (i = CHUNK_SIZE_DIGITS - 1; i >= 0; i--) {
digit = size & 0xf;
if (!begin && !size) {
i++;
break;
}
buf[i] = (digit > 9) ? digit - 0xA + 'a' : digit + '0';
size = size >> 4;
begin = 0;
}
err = httpd_send(conn, &buf[i], CHUNK_SIZE_DIGITS - i);
if (err != kNoErr) {
return err;
}
for (i = CHUNK_SIZE_DIGITS - 1; i >= 0; i--) {
digit = size & 0xf;
if (!begin && !size) {
i++;
break;
}
buf[i] = (digit > 9) ? digit - 0xA + 'a' : digit + '0';
size = size >> 4;
begin = 0;
}
err = httpd_send(conn, &buf[i], CHUNK_SIZE_DIGITS - i);
if (err != kNoErr) {
return err;
}
err = httpd_send_crlf(conn);
err = httpd_send_crlf(conn);
return err;
return err;
}
/* Send the last chunk which is simply an ascii "0\r\n\r\n"
*/
int httpd_send_last_chunk(int conn)
{
int err;
int err;
err = httpd_send(conn, http_last_chunk,
sizeof(http_last_chunk) - 1);
err = httpd_send(conn, http_last_chunk,
sizeof(http_last_chunk) - 1);
if (err != kNoErr) {
httpd_d("Send last chunk failed");
}
if (err != kNoErr) {
httpd_d("Send last chunk failed");
}
return err;
return err;
}
/* Send one chunk of data of a given size
*/
int httpd_send_chunk(int conn, const char *buf, int len)
{
int err;
int err;
if (len) {
/* Send chunk begin header */
err = httpd_send_chunk_begin(conn, len);
if (err != kNoErr)
return err;
/* Send our data */
err = httpd_send(conn, buf, len);
if (err != kNoErr)
return err;
/* Send chunk end indicator */
err = httpd_send_crlf(conn);
if (err != kNoErr)
return err;
} else {
/* Length is 0, last chunk */
err = httpd_send(conn, http_last_chunk,
sizeof(http_last_chunk) - 1);
if (err != kNoErr)
return err;
}
if (len) {
/* Send chunk begin header */
err = httpd_send_chunk_begin(conn, len);
if (err != kNoErr)
return err;
/* Send our data */
err = httpd_send(conn, buf, len);
if (err != kNoErr)
return err;
/* Send chunk end indicator */
err = httpd_send_crlf(conn);
if (err != kNoErr)
return err;
} else {
/* Length is 0, last chunk */
err = httpd_send(conn, http_last_chunk,
sizeof(http_last_chunk) - 1);
if (err != kNoErr)
return err;
}
return err;
return err;
}
/*Helper function to send a buffer over a connection.
*/
int httpd_send(int conn, const char *buf, int len)
{
int num;
do {
int num;
struct timeval t;
fd_set writefds;
t.tv_sec = 0;
t.tv_usec = 200*1000;
do {
#ifdef CONFIG_ENABLE_HTTPS
if (httpd_is_https_active())
if (httpd_is_https_active())
num = tls_send(httpd_tls_handle, buf, len);
else
#endif /* ENABLE_HTTPS */
num = send(conn, buf, len, 0);
if (num < 0) {
httpd_d("send() failed: %d" ,conn);
return -kInProgressErr;
}
len -= num;
buf += num;
} while (len > 0);
FD_ZERO( &writefds );
FD_SET( conn, &writefds );
select( conn + 1, NULL, &writefds, NULL, &t );
if( FD_ISSET( conn, &writefds) )
{
num = send(conn, buf, len, 0);
if (num < 0) {
httpd_d("send() failed: %d" ,conn);
return -kInProgressErr;
}
len -= num;
buf += num;
}
} while (len > 0);
return kNoErr;
return kNoErr;
}
int httpd_recv(int fd, void *buf, size_t n, int flags)
{
int len = 0;
struct timeval t;
fd_set readfds;
FD_ZERO( &readfds );
FD_SET( fd, &readfds );
t.tv_sec = 0;
t.tv_usec = 200*1000;
#ifdef CONFIG_ENABLE_HTTPS
if (httpd_is_https_active())
if (httpd_is_https_active())
return tls_recv(httpd_tls_handle, buf, n);
else
#endif /* ENABLE_HTTPS */
return recv(fd, buf, n, flags);
return recv(fd, buf, n, flags);
select( fd + 1, &readfds, NULL, NULL, &t );
if( FD_ISSET( fd, &readfds) )
{
len = recv( fd, buf, n, flags );
}
return len;
}
int httpd_send_hdr_from_code(int sock, int stat_code,
enum http_content_type content_type)
enum http_content_type content_type)
{
const char *str;
unsigned int str_len;
/*
* Set the HTTP Response Status 200 OK, 404 NOT FOUND etc.
* Also set the Transfer-Encoding to chunked.
*/
switch (stat_code) {
case -WM_E_HTTPD_HANDLER_404:
str = http_header_404;
str_len = strlen(http_header_404);
break;
case -WM_E_HTTPD_HANDLER_400:
str = http_header_400;
str_len = strlen(http_header_400);
break;
case -WM_E_HTTPD_HANDLER_500:
str = http_header_500;
str_len = strlen(http_header_500);
break;
default:
/* The handler doesn't want an HTTP error code, but would return
* 200 OK with an error in the response */
str = http_header_200;
str_len = strlen(http_header_200);
break;
}
const char *str;
unsigned int str_len;
/*
* Set the HTTP Response Status 200 OK, 404 NOT FOUND etc.
* Also set the Transfer-Encoding to chunked.
*/
switch (stat_code) {
case -WM_E_HTTPD_HANDLER_404:
str = http_header_404;
str_len = strlen(http_header_404);
break;
case -WM_E_HTTPD_HANDLER_400:
str = http_header_400;
str_len = strlen(http_header_400);
break;
case -WM_E_HTTPD_HANDLER_500:
str = http_header_500;
str_len = strlen(http_header_500);
break;
default:
/* The handler doesn't want an HTTP error code, but would return
* 200 OK with an error in the response */
str = http_header_200;
str_len = strlen(http_header_200);
break;
}
if (httpd_send(sock, str, str_len) != kNoErr) {
return -kInProgressErr;
}
if (httpd_send(sock, str, str_len) != kNoErr) {
return -kInProgressErr;
}
/* Send the Content-Type */
switch (content_type) {
case HTTP_CONTENT_JSON:
str = http_content_type_json_nocache;
str_len = sizeof(http_content_type_json_nocache) - 1;
break;
case HTTP_CONTENT_XML:
str = http_content_type_xml_nocache;
str_len = sizeof(http_content_type_xml_nocache) - 1;
break;
case HTTP_CONTENT_HTML:
str = http_content_type_html;
str_len = sizeof(http_content_type_html) - 1;
break;
case HTTP_CONTENT_JPEG:
str = http_content_type_jpg;
str_len = sizeof(http_content_type_jpg) - 1;
break;
default:
str = http_content_type_plain;
str_len = sizeof(http_content_type_plain) - 1;
break;
}
if (httpd_send(sock, str, str_len) != kNoErr) {
return -kInProgressErr;
}
return kNoErr;
/* Send the Content-Type */
switch (content_type) {
case HTTP_CONTENT_JSON:
str = http_content_type_json_nocache;
str_len = sizeof(http_content_type_json_nocache) - 1;
break;
case HTTP_CONTENT_XML:
str = http_content_type_xml_nocache;
str_len = sizeof(http_content_type_xml_nocache) - 1;
break;
case HTTP_CONTENT_HTML:
str = http_content_type_html;
str_len = sizeof(http_content_type_html) - 1;
break;
case HTTP_CONTENT_JPEG:
str = http_content_type_jpg;
str_len = sizeof(http_content_type_jpg) - 1;
break;
default:
str = http_content_type_plain;
str_len = sizeof(http_content_type_plain) - 1;
break;
}
if (httpd_send(sock, str, str_len) != kNoErr) {
return -kInProgressErr;
}
return kNoErr;
}
@@ -234,62 +264,62 @@ static char httpd_error[HTTPD_MAX_ERROR_STRING + 1];
void httpd_set_error(const char *fmt, ...)
{
va_list argp;
va_start(argp, fmt);
vsnprintf(httpd_error, HTTPD_MAX_ERROR_STRING + 1, fmt, argp);
va_end(argp);
httpd_d("http set err");
httpd_d("http set err");
}
/* Helper function to send an error.
*/
int httpd_send_error(int conn, int http_error)
{
int err = 0;
int err = 0;
switch (http_error) {
case HTTP_404:
err = httpd_send(conn, http_header_404,
strlen(http_header_404));
break;
case HTTP_500:
err = httpd_send(conn, http_header_500,
strlen(http_header_500));
break;
switch (http_error) {
case HTTP_404:
err = httpd_send(conn, http_header_404,
strlen(http_header_404));
break;
case HTTP_500:
err = httpd_send(conn, http_header_500,
strlen(http_header_500));
break;
case HTTP_505:
err = httpd_send(conn, http_header_505,
strlen(http_header_505));
break;
}
case HTTP_505:
err = httpd_send(conn, http_header_505,
strlen(http_header_505));
break;
}
if (err != kNoErr) {
return err;
}
if (err != kNoErr) {
return err;
}
err = httpd_send(conn, http_header_type_chunked,
strlen(http_header_type_chunked));
if (err != kNoErr) {
return err;
}
err = httpd_send(conn, http_header_type_chunked,
strlen(http_header_type_chunked));
if (err != kNoErr) {
return err;
}
err = httpd_send(conn, http_content_type_plain,
sizeof(http_content_type_plain) - 1);
if (err != kNoErr) {
return err;
}
err = httpd_send(conn, http_content_type_plain,
sizeof(http_content_type_plain) - 1);
if (err != kNoErr) {
return err;
}
err = httpd_send_crlf(conn);
if (err != kNoErr) {
return err;
}
err = httpd_send_crlf(conn);
if (err != kNoErr) {
return err;
}
err = httpd_send_chunk(conn, httpd_error, strlen(httpd_error));
if (err != kNoErr) {
return err;
}
return httpd_send_last_chunk(conn);
err = httpd_send_chunk(conn, httpd_error, strlen(httpd_error));
if (err != kNoErr) {
return err;
}
return httpd_send_last_chunk(conn);
}
@@ -299,28 +329,28 @@ int httpd_send_error(int conn, int http_error)
* data after that.
*/
void httpd_purge_socket_data(httpd_request_t *req, char *msg_in,
int msg_in_len, int conn)
int msg_in_len, int conn)
{
int status = httpd_parse_hdr_tags(req, conn, msg_in, msg_in_len);
if (status != kNoErr) {
/* We were unsuccessful in purging the socket.*/
httpd_d("Unable to purge socket: %d", status);
return;
}
int status = httpd_parse_hdr_tags(req, conn, msg_in, msg_in_len);
if (status != kNoErr) {
/* We were unsuccessful in purging the socket.*/
httpd_d("Unable to purge socket: %d", status);
return;
}
unsigned data_remaining = req->body_nbytes;
unsigned data_remaining = req->body_nbytes;
while (data_remaining) {
unsigned to_read = msg_in_len >= data_remaining ?
data_remaining : msg_in_len;
int actually_read = httpd_recv(conn, msg_in, to_read, 0);
if (actually_read < 0) {
httpd_d("Unable to read content."
"Was purging socket data");
return;
}
data_remaining -= actually_read;
}
while (data_remaining) {
unsigned to_read = msg_in_len >= data_remaining ?
data_remaining : msg_in_len;
int actually_read = httpd_recv(conn, msg_in, to_read, 0);
if (actually_read < 0) {
httpd_d("Unable to read content."
"Was purging socket data");
return;
}
data_remaining -= actually_read;
}
}
/* Handle an incoming message (request) from the client. This is the
@@ -328,72 +358,72 @@ void httpd_purge_socket_data(httpd_request_t *req, char *msg_in,
*/
int httpd_handle_message(int conn)
{
int err;
int req_line_len;
char msg_in[128];
int err;
int req_line_len;
char msg_in[128];
/* clear out the httpd_req structure */
memset(&httpd_req, 0x00, sizeof(httpd_req));
/* clear out the httpd_req structure */
memset(&httpd_req, 0x00, sizeof(httpd_req));
httpd_req.sock = conn;
httpd_req.sock = conn;
/* Read the first line of the HTTP header */
req_line_len = htsys_getln_soc(conn, msg_in, sizeof(msg_in));
if (req_line_len == 0)
return HTTPD_DONE;
/* Read the first line of the HTTP header */
req_line_len = htsys_getln_soc(conn, msg_in, sizeof(msg_in));
if (req_line_len == 0)
return HTTPD_DONE;
if (req_line_len < 0) {
httpd_d("Could not read from socket");
return -kInProgressErr;
}
if (req_line_len < 0) {
httpd_d("Could not read from socket");
return -kInProgressErr;
}
/* Parse the first line of the header */
err = httpd_parse_hdr_main(msg_in, &httpd_req);
if (err == -WM_E_HTTPD_NOTSUPP)
/* Send 505 HTTP Version not supported */
return httpd_send_error(conn, HTTP_505);
else if (err != kNoErr) {
/* Send 500 Internal Server Error */
return httpd_send_error(conn, HTTP_500);
}
/* Parse the first line of the header */
err = httpd_parse_hdr_main(msg_in, &httpd_req);
if (err == -WM_E_HTTPD_NOTSUPP)
/* Send 505 HTTP Version not supported */
return httpd_send_error(conn, HTTP_505);
else if (err != kNoErr) {
/* Send 500 Internal Server Error */
return httpd_send_error(conn, HTTP_500);
}
/* set a generic error that can be overridden by the wsgi handling. */
httpd_d("Presetting");
/* set a generic error that can be overridden by the wsgi handling. */
httpd_d("Presetting");
/* Web Services Gateway Interface branch point:
* At this point we have the request type (httpd_req.type) and the path
* (httpd_req.filename) and all the headers waiting to be read from
* the socket.
*
* The call bellow will iterate through all the url patterns and
* invoke the handlers that match the request type and pattern. If
* request type and url patern match, invoke the handler.
*/
err = httpd_wsgi(&httpd_req);
/* Web Services Gateway Interface branch point:
* At this point we have the request type (httpd_req.type) and the path
* (httpd_req.filename) and all the headers waiting to be read from
* the socket.
*
* The call bellow will iterate through all the url patterns and
* invoke the handlers that match the request type and pattern. If
* request type and url patern match, invoke the handler.
*/
err = httpd_wsgi(&httpd_req);
if (err == HTTPD_DONE) {
httpd_d("Done processing request.");
return kNoErr;
} else if (err == -WM_E_HTTPD_NO_HANDLER) {
httpd_d("No handler for the given URL %s was found",
httpd_req.filename);
/*
* We have not yet read the complete data from the current
* request, from the socket. We are in an error state and
* we wish to cancel this HTTP transaction. We sent
* appropriate message to the client and read (flush) out
* all the pending data in the socket. We let the client
* close the socket for us, if necessary.
*/
httpd_purge_socket_data(&httpd_req, msg_in,
sizeof(msg_in), conn);
httpd_set_error("File %s not_found", httpd_req.filename);
httpd_send_error(conn, HTTP_404);
return kNoErr;
} else {
httpd_d("WSGI handler failed.");
/* Send 500 Internal Server Error */
return httpd_send_error(conn, HTTP_500);
}
if (err == HTTPD_DONE) {
httpd_d("Done processing request.");
return kNoErr;
} else if (err == -WM_E_HTTPD_NO_HANDLER) {
httpd_d("No handler for the given URL %s was found",
httpd_req.filename);
/*
* We have not yet read the complete data from the current
* request, from the socket. We are in an error state and
* we wish to cancel this HTTP transaction. We sent
* appropriate message to the client and read (flush) out
* all the pending data in the socket. We let the client
* close the socket for us, if necessary.
*/
httpd_purge_socket_data(&httpd_req, msg_in,
sizeof(msg_in), conn);
httpd_set_error("File %s not_found", httpd_req.filename);
httpd_send_error(conn, HTTP_404);
return kNoErr;
} else {
httpd_d("WSGI handler failed.");
/* Send 500 Internal Server Error */
return httpd_send_error(conn, HTTP_500);
}
}
}

View File

@@ -56,21 +56,21 @@ static OSStatus onReceivedData( struct _HTTPHeader_t * httpHeader,
static void hex2str(uint8_t *hex, int hex_len, char *str)
{
int i = 0;
for(i=0; i<hex_len; i++){
sprintf(str+i*2, "%02x", hex[i]);
}
int i = 0;
for(i=0; i<hex_len; i++){
sprintf(str+i*2, "%02x", hex[i]);
}
}
static void upper2lower(char *str, int len)
{
int i = 0;
for(i=0; i<len; i++)
{
if( (*(str+i) >= 'A') && (*(str+i) <= 'Z') ){
*(str+i) += 32;
int i = 0;
for(i=0; i<len; i++)
{
if( (*(str+i) >= 'A') && (*(str+i) <= 'Z') ){
*(str+i) += 32;
}
}
}
}
static int ota_server_send( uint8_t *data, int datalen )
@@ -104,7 +104,7 @@ static OSStatus ota_server_connect( struct sockaddr_in *addr, socklen_t addrlen
}
#endif
exit:
exit:
return err;
}
@@ -244,7 +244,7 @@ static void ota_server_thread( mico_thread_arg_t arg )
struct in_addr in_addr;
mico_logic_partition_t* ota_partition = MicoFlashGetInfo( MICO_PARTITION_OTA_TEMP );
ota_server_context->ota_control = OTA_CONTROL_START;
hostent_content = gethostbyname( ota_server_context->download_url.host );
@@ -256,12 +256,12 @@ static void ota_server_thread( mico_thread_arg_t arg )
offset = 0;
MicoFlashErase( MICO_PARTITION_OTA_TEMP, 0x0, ota_partition->partition_length );
CRC16_Init( &crc_context );
if( ota_server_context->ota_check.is_md5 == true ){
InitMd5( &md5 );
}
httpHeader = HTTPHeaderCreateWithCallback( 1024, onReceivedData, NULL, NULL );
require_action( httpHeader, DELETE, ota_server_progress_set(OTA_FAIL) );
@@ -334,13 +334,13 @@ static void ota_server_thread( mico_thread_arg_t arg )
goto DELETE;
}
RECONNECTED:
RECONNECTED:
ota_server_socket_close( );
mico_thread_sleep(2);
continue;
}
DELETE:
DELETE:
HTTPHeaderDestory( &httpHeader );
ota_server_socket_close( );
if( ota_server_context != NULL ){
@@ -421,7 +421,7 @@ static OSStatus ota_server_set_url( char *url )
strcpy( ota_server_context->download_url.url, pos );
}
exit:
exit:
url_free( url_t );
return err;
}
@@ -461,7 +461,7 @@ OSStatus ota_server_start( char *url, char *md5, ota_server_cb_fn call_back )
ota_server_context->ota_server_cb = call_back;
err = mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY, "OTA", ota_server_thread, OTA_SERVER_THREAD_STACK_SIZE, 0 );
exit:
exit:
return err;
}
@@ -483,4 +483,4 @@ void ota_server_stop( void )
OTA_CONTROL_E ota_server_get( void )
{
return ota_server_context->ota_control;
}
}

View File

@@ -49,8 +49,8 @@ typedef enum _OTA_STATE_E{
}OTA_STATE_E;
typedef enum _HTTP_SECURITY_E{
HTTP_SECURITY_HTTP,
HTTP_SECURITY_HTTPS
HTTP_SECURITY_HTTP,
HTTP_SECURITY_HTTPS
} HTTP_SECURITY_E;
typedef enum _OTA_CONTROL_E{
@@ -87,11 +87,11 @@ typedef struct _ota_check_t{
typedef void (*ota_server_cb_fn) (OTA_STATE_E state, float progress);
typedef struct _ota_server_context_t{
download_url_t download_url;
download_state_t download_state;
ota_check_t ota_check;
OTA_CONTROL_E ota_control;
ota_server_cb_fn ota_server_cb;
download_url_t download_url;
download_state_t download_state;
ota_check_t ota_check;
OTA_CONTROL_E ota_control;
ota_server_cb_fn ota_server_cb;
} ota_server_context_t;
@@ -139,4 +139,4 @@ void ota_server_continue( void );
*/
void ota_server_stop( void );
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -40,33 +40,35 @@
#include "URLUtils.h"
#include "stdbool.h"
#define Boolean bool
#define kHTTPPostMethod "POST"
// Status-Code =
// "100" ; Section 10.1.1: Continue
// | "101" ; Section 10.1.2: Switching Protocols
// | "200" ; Section 10.2.1: OK
// | "201" ; Section 10.2.2: Created
// | "202" ; Section 10.2.3: Accepted
// | "203" ; Section 10.2.4: Non-Authoritative Information
// | "204" ; Section 10.2.5: No Content
// | "205" ; Section 10.2.6: Reset Content
// | "206" ; Section 10.2.7: Partial Content
// | "207" ; ??? : Multi-Status
// | "300" ; Section 10.3.1: Multiple Choices
// | "301" ; Section 10.3.2: Moved Permanently
// | "302" ; Section 10.3.3: Found
// | "303" ; Section 10.3.4: See Other
// | "304" ; Section 10.3.5: Not Modified
// | "305" ; Section 10.3.6: Use Proxy
// | "307" ; Section 10.3.8: Temporary Redirect
// | "400" ; Section 10.4.1: Bad Request
// | "401" ; Section 10.4.2: Unauthorized
// | "402" ; Section 10.4.3: Payment Required
// | "403" ; Section 10.4.4: Forbidden
// | "404" ; Section 10.4.5: Not Found
// | "405" ; Section 10.4.6: Method Not Allowed
// | "406" ; Section 10.4.7: Not Acceptable
// Status-Code =
// "100" ; Section 10.1.1: Continue
// | "101" ; Section 10.1.2: Switching Protocols
// | "200" ; Section 10.2.1: OK
// | "201" ; Section 10.2.2: Created
// | "202" ; Section 10.2.3: Accepted
// | "203" ; Section 10.2.4: Non-Authoritative Information
// | "204" ; Section 10.2.5: No Content
// | "205" ; Section 10.2.6: Reset Content
// | "206" ; Section 10.2.7: Partial Content
// | "207" ; ??? : Multi-Status
// | "300" ; Section 10.3.1: Multiple Choices
// | "301" ; Section 10.3.2: Moved Permanently
// | "302" ; Section 10.3.3: Found
// | "303" ; Section 10.3.4: See Other
// | "304" ; Section 10.3.5: Not Modified
// | "305" ; Section 10.3.6: Use Proxy
// | "307" ; Section 10.3.8: Temporary Redirect
// | "400" ; Section 10.4.1: Bad Request
// | "401" ; Section 10.4.2: Unauthorized
// | "402" ; Section 10.4.3: Payment Required
// | "403" ; Section 10.4.4: Forbidden
// | "404" ; Section 10.4.5: Not Found
// | "405" ; Section 10.4.6: Method Not Allowed
// | "406" ; Section 10.4.7: Not Acceptable
#define kStatusAccept 202
@@ -76,9 +78,9 @@
#define kStatusBadRequest 400
#define kStatusNotFound 404
#define kStatusMethodNotAllowed 405
#define kStatusForbidden 403
#define kStatusAuthenticationErr 470
#define kStatusInternalServerErr 500
#define kStatusForbidden 403
#define kStatusAuthenticationErr 470
#define kStatusInternalServerErr 500
#define kMIMEType_Binary "application/octet-stream"
#define kMIMEType_DMAP "application/x-dmap-tagged"
@@ -130,7 +132,7 @@ typedef struct _HTTPHeader_t
void * userContext;
bool isCallbackSupported;
OSStatus (*onReceivedDataCallback) ( struct _HTTPHeader_t * , uint32_t, uint8_t *, size_t, void * );
OSStatus (*onReceivedDataCallback) ( struct _HTTPHeader_t * , uint32_t, uint8_t *, size_t, void * );
void (*onClearCallback) ( struct _HTTPHeader_t * httpHeader, void * userContext );
@@ -168,14 +170,14 @@ int HTTPHeaderMatchURL( HTTPHeader_t *inHeader, const char *url );
char* HTTPHeaderMatchPartialURL( HTTPHeader_t *inHeader, const char *url );
int HTTPGetHeaderField( const char *inHeaderPtr,
size_t inHeaderLen,
const char *inName,
const char **outNamePtr,
size_t *outNameLen,
const char **outValuePtr,
size_t *outValueLen,
const char **outNext );
int HTTPGetHeaderField( const char *inHeaderPtr,
size_t inHeaderLen,
const char *inName,
const char **outNamePtr,
size_t *outNameLen,
const char **outValuePtr,
size_t *outValueLen,
const char **outNext );
HTTPHeader_t * HTTPHeaderCreate( size_t bufLen );
@@ -196,10 +198,9 @@ OSStatus CreateHTTPRespondMessageNoCopy( int status, const char *contentType, si
OSStatus CreateHTTPMessage( const char *methold, const char *url, const char *contentType, uint8_t *inData, size_t inDataLen, uint8_t **outMessage, size_t *outMessageSize );
OSStatus CreateHTTPMessageWithHost( const char *methold, const char *url,
const char* host, uint16_t port,
const char *contentType,
uint8_t *inData, size_t inDataLen,
uint8_t **outMessage, size_t *outMessageSize );
const char* host, uint16_t port,
const char *contentType,
uint8_t *inData, size_t inDataLen,
uint8_t **outMessage, size_t *outMessageSize );
#endif // __HTTPUtils_h__