optimized code alot

This commit is contained in:
strawmanbobi
2024-10-25 17:33:38 +08:00
parent 8e3d25fea5
commit a3dfc6e6d0
14 changed files with 168 additions and 146 deletions

View File

@@ -59,9 +59,9 @@ int connectToAliot(PubSubClient& mqtt_client) {
int res = iot.begin(mqtt_client, g_product_key.c_str(), g_device_name.c_str(), g_device_token.c_str(), g_aliot_region.c_str());
if (0 == res) {
INFOLN("Aliyun IoT connected");
INFOF("Aliyun IoT connected\n");
} else {
ERRORLN("Failed to connect to Aliyun IoT");
ERRORF("Failed to connect to Aliyun IoT\n");
}
return res;
}

View File

@@ -47,8 +47,9 @@ typedef unsigned char uint8_t;
#endif
/* ----------------- auth settings ----------------- */
#define CREDENTIAL_INIT_RETRY_MAX (3)
#define CREDENTIAL_INIT_RETRY_MAX (10)
#define SYSTEM_DELAY (2000)
#define AUTH_RETRY_DELAY (6000)
/* ----------------- iot settings -----------------*/
#define MQTT_HOST_REL "iot.irext.net"

View File

@@ -49,7 +49,6 @@ static bool force_disconnected = false;
static PubSubClient* emqx_client = NULL;
// private function declarations
static void irisIrextIoTCallback(char *topic, uint8_t *data, uint32_t length);
// public function definitions
@@ -75,15 +74,16 @@ int connectToEMQXBroker(PubSubClient &mqtt_client) {
}
}
if (emqx_client->connected()) {
INFOF("IRext IoT connect done\n");
INFOF("IoT connect done\n");
return 0;
} else {
ERRORF("IRext IoT failed to connect\n");
ERRORF("IoT failed to connect\n");
return -1;
}
}
void emqxClientKeepAlive() {
void emqxClientKeepAlive(PubSubClient& mqtt_client) {
(void) mqtt_client;
emqx_client->loop();
}

View File

@@ -31,6 +31,6 @@ int connectToEMQXBroker(PubSubClient &mqtt_client);
int disconnectFromEMQXBroker();
void emqxClientKeepAlive();
void emqxClientKeepAlive(PubSubClient &mqtt_client);
#endif // IRIS_KIT_EMQ_CLIENT_H

View File

@@ -99,6 +99,6 @@ void registAC(String filename, bool flag) {
if (flag) {
serializeJson(send_msg_doc, reg_content);
}
DEBUGLN(reg_topic_head);
INFOLN(reg_topic_head);
// mqttPublishRetained(reg_topic_head, reg_content);
}

View File

@@ -82,22 +82,22 @@ http_error_t downLoadFile(String url, String file, String path) {
download_flag = true;
break;
} else {
ERRORF("http response error : %d\n", response_code);
ERRORF("HTTP response error : %d\n", response_code);
delay(HTTP_REQUEST_RETRY_INTERVAL);
}
}
if (download_flag) {
http_client.writeToStream(&cache);
ret = HTTP_ERROR_SUCCESS;
DEBUGF("download %s successfully\n", file.c_str());
INFOF("Download %s successfully\n", file.c_str());
} else {
LittleFS.remove(save_path);
ret = HTTP_ERROR_GENERIC;
ERRORF("download %s failed\n", file.c_str());
ERRORF("Download %s failed\n", file.c_str());
}
} else {
ret = HTTP_ERROR_LOCAL_SPACE;
ERRORLN("there is not enough storage space for file");
ERRORF("There is not enough storage space for file\n");
}
cache.close();
http_client.end();

View File

@@ -66,7 +66,7 @@ static bool downstream_topic_subscribed = false;
// private function declarations
static void irisIrextIoTCallback(char *topic, uint8_t *data, uint32_t length);
static void irisIoTCallback(char *topic, uint8_t *data, uint32_t length);
static int iot_retry = 0;
@@ -74,7 +74,7 @@ static PubSubClient g_mqtt_client(wifi_client);
// public function definitions
int connectToIrextIoT() {
int connectIot() {
downstream_topic_subscribed = false;
int conn_ret = -1;
@@ -85,7 +85,7 @@ int connectToIrextIoT() {
g_upstream_topic = "/" + g_product_key + "/" + g_device_name + TOPIC_UPSTREAM_REL;
g_downstream_topic = "/" + g_product_key + "/" + g_device_name + TOPIC_DOWNSTREAM_REL;
} else {
ERRORF("IRIS Kit release key is not supported yet\n");
ERRORF("Release key is not supported yet\n");
factoryReset();
return -1;
}
@@ -98,7 +98,7 @@ int connectToIrextIoT() {
conn_ret = connectToAliot(g_mqtt_client);
if (0 != conn_ret) {
INFOF("Try connecting to IRext IoT %s:%d, client_id = %s, user_name = %s, password.size = %d\n",
INFOF("Try connecting to IoT %s:%d, client_id = %s, user_name = %s, password.size = %d\n",
g_mqtt_server.c_str(), g_mqtt_port,
g_mqtt_client_id.c_str(), g_mqtt_user_name.c_str(), g_mqtt_password.length());
conn_ret = connectToEMQXBroker(g_mqtt_client);
@@ -111,13 +111,13 @@ int connectToIrextIoT() {
}
if (0 != conn_ret) {
ERRORLN("Something may went wrong with your credential, please retry connect to Wifi...");
ERRORF("Something may went wrong with your credential, please retry connect to Wifi...\n");
factoryReset();
return -1;
}
if (!g_subscribed) {
g_mqtt_client.setCallback(irisIoTCallback);
g_mqtt_client.setCallback(iotCallback);
g_mqtt_client.subscribe(g_downstream_topic.c_str());
g_subscribed = true;
}
@@ -128,20 +128,20 @@ int connectToIrextIoT() {
return conn_ret;
}
void irextIoTKeepAlive() {
if (MQTT_TYPE_ALIOT == g_mqtt_type) {
aliotKeepAlive(g_mqtt_client);
} else if (MQTT_TYPE_EMQX == g_mqtt_type) {
emqxClientKeepAlive();
void keepAliveIot() {
if (g_mqtt_client.connected()) {
if (MQTT_TYPE_ALIOT == g_mqtt_type) {
aliotKeepAlive(g_mqtt_client);
} else if (MQTT_TYPE_EMQX == g_mqtt_type) {
emqxClientKeepAlive(g_mqtt_client);
}
}
unsigned long current_time = millis();
if (current_time - last_check_time > 10000) {
if (!g_mqtt_client.connected()) {
g_mqtt_client.unsubscribe(g_downstream_topic.c_str());
g_subscribed = false;
connectToIrextIoT();
connectIot();
}
}
}
@@ -155,15 +155,15 @@ void* getSession() {
return &g_mqtt_client;
}
void checkIrisIoT() {
void checkIot() {
if (g_mqtt_client.connected()) {
INFOLN("send iris kit heart beat");
INFOF("Send iris kit heart beat\n");
sendIrisKitHeartBeat();
}
}
void irisIoTCallback(char *topic, uint8_t *data, uint32_t length) {
INFOF("downstream message received, topic = %s, length = %d\n", topic, length);
void iotCallback(char *topic, uint8_t *data, uint32_t length) {
INFOF("Downstream message received, topic = %s, length = %d\n", topic, length);
if (NULL != g_downstream_topic.c_str() && 0 == strcmp(topic, g_downstream_topic.c_str())) {
handleIrisKitMessage((const char*) data, length);
}

View File

@@ -40,16 +40,16 @@ typedef enum {
MQTT_TYPE_MAX = 7,
} mqtt_type_t;
int connectToIrextIoT();
int connectIot();
void irextIoTKeepAlive();
void keepAliveIot();
void checkIrisIoT();
void checkIot();
void* getSession();
void sendData(const char* topic, const uint8_t *data, int length);
void irisIoTCallback(char *topic, uint8_t *data, uint32_t length);
void iotCallback(char *topic, uint8_t *data, uint32_t length);
#endif // IRIS_KIT_IOT_H

View File

@@ -44,24 +44,22 @@ const uint16_t k_capture_buffer_size = IR_SERIES_MAX;
static IRsend * ir_send = nullptr;
static IRrecv * ir_recv = nullptr;
int g_ready_to_study = 0;
int g_study_key_id = -1;
String g_study_key_name = "";
String g_study_remote_index = "";
bool sendIR(String file_name) {
String save_path = SAVE_PATH + file_name;
if (LittleFS.exists(save_path)) {
File cache = LittleFS.open(save_path, "r");
if (!cache) {
ERRORF("Failed to open %s", save_path.c_str());
ERRORF("Failed to open %s\n", save_path.c_str());
return false;
}
Serial.println();
uint16_t *data_buffer = (uint16_t *)malloc(sizeof(uint16_t) * IR_SERIES_MAX);
uint16_t length = cache.size() / 2;
memset(data_buffer, 0x0, IR_SERIES_MAX);
INFOF("file size = %d\n", cache.size());
INFOLN();
cache.readBytes((char *)data_buffer, cache.size());
ir_recv->disableIRIn();
ir_send->sendRaw(data_buffer, length, 38);
@@ -98,7 +96,7 @@ bool sendCommand(String file_name, int key) {
File cache = LittleFS.open(save_path, "r");
if (cache) {
UINT16 content_size = cache.size();
DEBUGF("content size = %d\n", content_size);
INFOF("Send command, content size = %d\n", content_size);
if (content_size != 0) {
UINT8 *content = (UINT8 *)malloc(content_size * sizeof(UINT8));
@@ -108,7 +106,7 @@ bool sendCommand(String file_name, int key) {
UINT16 *user_data = (UINT16 *)malloc(IR_SERIES_MAX * sizeof(UINT16));
UINT16 data_length = ir_decode(0, user_data, NULL, FALSE);
DEBUGF("data_length = %d\n", data_length);
INFOF("Send command, data_length = %d\n", data_length);
if (LOG_DEBUG) {
for (int i = 0; i < data_length; i++)
Serial.printf("%d ", *(user_data + i));
@@ -139,7 +137,7 @@ void sendStatus(String file, t_remote_ac_status status) {
File cache = LittleFS.open(save_path, "r");
if (cache) {
UINT16 content_size = cache.size();
DEBUGF("content size = %d\n", content_size);
INFOF("Send status, content size = %d\n", content_size);
if (content_size != 0) {
UINT8 *content = (UINT8 *)malloc(content_size * sizeof(UINT8));
@@ -149,7 +147,7 @@ void sendStatus(String file, t_remote_ac_status status) {
UINT16 *user_data = (UINT16 *)malloc(IR_SERIES_MAX * sizeof(UINT16));
UINT16 data_length = ir_decode(0, user_data, &status, FALSE);
DEBUGF("data_length = %d\n", data_length);
INFOF("Send status, data_length = %d\n", data_length);
ir_recv->disableIRIn();
ir_send->sendRaw(user_data, data_length, 38);
ir_close();
@@ -163,16 +161,16 @@ void sendStatus(String file, t_remote_ac_status status) {
}
}
void prepareRecvIR(int key_id, String key_name) {
enableIRIn();
void prepareRecvIR(int key_id, String key_name, String remote_index) {
g_study_key_id = key_id;
g_study_key_name = key_name;
g_ready_to_study = 1;
g_study_remote_index = remote_index;
removeReceived();
enableIRIn();
}
void cancelRecvIR() {
// called solicited
g_ready_to_study = 0;
g_study_remote_index = "";
g_study_key_name = "";
g_study_key_id = -1;
disableIRIn();
@@ -180,7 +178,7 @@ void cancelRecvIR() {
void completedRecvIR(int key_id, String key_name) {
// called unsolicited
g_ready_to_study = 0;
g_study_remote_index = "";
g_study_key_name = "";
g_study_key_id = -1;
disableIRIn();
@@ -189,35 +187,31 @@ void completedRecvIR(int key_id, String key_name) {
void recvIR() {
decode_results results;
if (ir_recv->decode(&results)) {
DEBUGF("raw length = %d\n", results.rawlen - 1);
INFOF("Recv IR, raw length = %d\n", results.rawlen - 1);
String raw_data;
for (int i = 1; i < results.rawlen; i++) {
raw_data += String(*(results.rawbuf + i) * kRawTick) + ",";
}
ir_recv->resume();
send_msg_doc.clear();
send_msg_doc["cmd"] = "record_rt";
send_msg_doc["params"]["signal"] = "IR";
send_msg_doc["params"]["length"] = results.rawlen;
send_msg_doc["params"]["value"] = raw_data.c_str();
DEBUGLN(raw_data.c_str());
saveIR(results);
INFOLN(raw_data.c_str());
saveReceived(results);
}
}
bool saveIR(String file_name) {
bool saveReceived(decode_results& results) {
String save_path = SAVE_PATH;
save_path += file_name;
return LittleFS.rename("/bin/test", save_path);
}
String file_name = "";
bool saveIR(decode_results& results) {
String save_path = SAVE_PATH;
save_path += "test";
DEBUGF("save raw data as %s\n", save_path.c_str());
if (g_study_remote_index.isEmpty()) {
return false;
}
file_name = "ir_" + g_study_remote_index + RECEIVED_SUFFIX;
save_path += file_name;
INFOF("Save received code to: %s\n", save_path.c_str());
File cache = LittleFS.open(save_path, "w");
if (!cache) {
ERRORLN("Failed to create file");
ERRORF("Failed to create file\n");
return false;
}
for (size_t i = 0; i < results.rawlen; i++)
@@ -227,6 +221,21 @@ bool saveIR(decode_results& results) {
return true;
}
bool removeReceived() {
String save_path = SAVE_PATH;
String file_name = "";
if (g_study_remote_index.isEmpty()) {
return false;
}
file_name = "ir_" + g_study_remote_index + RECEIVED_SUFFIX;
save_path += file_name;
INFOF("Delete received code file: %s\n", save_path.c_str());
LittleFS.remove(save_path);
return true;
}
void initAC(String file) {
ACStatus[file]["power"] = 0;
ACStatus[file]["temperature"] = 8;
@@ -243,7 +252,7 @@ void loadIRPin(uint8_t send_pin, uint8_t recv_pin) {
delete ir_recv;
}
ir_send = new IRsend(send_pin);
DEBUGF("Load IR send pin at %d\n", send_pin);
INFOF("Load IR send pin at %d\n", send_pin);
ir_send->begin();
ir_recv = new IRrecv(recv_pin, k_capture_buffer_size, k_timeout, true);
disableIRIn();

View File

@@ -42,13 +42,11 @@ bool sendIR(String file_name);
bool emitIR(String timing);
bool saveIR(decode_results &results);
bool sendCommand(String file_name, int key);
void sendStatus(String file_name, t_remote_ac_status status);
void prepareRecvIR(int key_id, String key_name);
void prepareRecvIR(int key_id, String key_name, String remote_index);
void cancelRecvIR();
@@ -56,7 +54,9 @@ void completedRecvIR(int key_id, String key_name);
void recvIR();
bool saveIR(String file_name);
bool saveReceived(decode_results& results);
bool removeReceived();
void initAC(String);

View File

@@ -51,7 +51,7 @@ extern String g_product_key;
extern String g_device_name;
extern String g_upstream_topic;
extern int g_app_id;
extern iris_kit_status_t g_iris_kit_status;
char iris_credential_token[CREDENTIAL_MAX] = { 0 };
char iris_server_address[URL_SHORT_MAX] = { 0 };
@@ -66,7 +66,7 @@ static int handleConnected(String product_key, String device_name, String conten
static int handleHartBeat(String product_key, String device_name, String content);
static int handleEmit(String product_key, String device_name, String content);
static int handleNotifyStatus(String product_key, String device_name, String content);
static int processStatusChange(int status, int console_id, int key_id, String key_name);
static int processStatusChange(int status, int console_id, int key_id, String key_name, String remote_index);
static int hb_count = 0;
@@ -134,14 +134,14 @@ int authIrisKit(String credential_token,
}
fetch_credential_url.concat(String(GET_IRIS_KIT_ACCOUNT_SUFFIX));
INFOF("fetch credential URL = %s\n", fetch_credential_url.c_str());
INFOF("Fetch credential URL = %s\n", fetch_credential_url.c_str());
if (credential_token.isEmpty()) {
ERRORLN("credential token is empty");
ERRORF("Credential token is empty\n");
return -1;
}
tsi = credential_token.indexOf(",");
if (-1 == tsi) {
ERRORLN("credential token format error");
ERRORF("Credential token format error\n");
return -1;
}
product_key = credential_token.substring(0, tsi);
@@ -162,7 +162,7 @@ int authIrisKit(String credential_token,
if (DeserializationError::Ok == deserializeJson(http_response_doc, response_data)) {
int resultCode = http_response_doc["status"]["code"];
if (0 == resultCode) {
INFOLN("response valid, try getting entity");
INFOF("response valid, try getting entity\n");
// for aliot connection, use deviceToken as deviceSecret
device_token = (const char*) http_response_doc["entity"]["deviceToken"];
app_id = (int) http_response_doc["entity"]["appId"];
@@ -170,7 +170,7 @@ int authIrisKit(String credential_token,
product_key.c_str(), device_name.c_str(), device_secret.c_str(), device_token.c_str());
ret = 0;
} else {
INFOF("response invalid, code = %d\n", resultCode);
INFOF("Response invalid, code = %d\n", resultCode);
}
}
}
@@ -197,7 +197,7 @@ bool downloadBin(int remote_id) {
download_bin_url.concat(String(DOWNLOAD_BIN_SUFFIX));
if (-1 != remote_id) {
INFOF("notified to download bin: %d", remote_id);
INFOF("Notified to download bin: %d\n", remote_id);
save_file = String("ir_") + String(remote_id);
String temp = String(SAVE_PATH) + String("/") + save_file;
@@ -215,7 +215,7 @@ void sendIrisKitConnect() {
}
void sendIrisKitHeartBeat() {
INFOF("send iris kit heart beat[%d]\n", hb_count++);
INFOF("Send iris kit heart beat[%d]\n", hb_count++);
String heartBeatMessage = buildHeartBeat();
sendData(g_upstream_topic.c_str(), (uint8_t*) heartBeatMessage.c_str(), heartBeatMessage.length());
}
@@ -232,9 +232,9 @@ void handleIrisKitMessage(const char* data, int length) {
String product_key = iris_ind_doc["productKey"];
String device_name = iris_ind_doc["deviceName"];
String content = iris_ind_doc["content"];
INFOF("received ind : %s\n", event_name.c_str());
INFOF("Received ind : %s\n", event_name.c_str());
ret = processEvent(event_name.c_str(), product_key, device_name, content);
INFOF("event handle result = %d\n", ret);
INFOF("Event handle result = %d\n", ret);
}
}
@@ -249,7 +249,7 @@ static int processEvent(String event_name, String product_key, String device_nam
int event_table_length = sizeof(event_handler_table) / sizeof(event_handler_table[0]);
for (int i = 0; i < event_table_length; i++) {
if (0 == strcmp(event_name.c_str(), event_handler_table[i].event_name)) {
INFOF("call event handler with payload : %s, %s\n", product_key.c_str(), device_name.c_str());
INFOF("Call event handler with payload : %s, %s\n", product_key.c_str(), device_name.c_str());
return event_handler_table[i].handler(product_key, device_name, content);
}
}
@@ -312,61 +312,65 @@ static int handleConnected(String product_key, String device_name, String conten
}
static int handleHartBeat(String product_key, String device_name, String content) {
INFOF("received heartbeat : %s, %s\n", product_key.c_str(), device_name.c_str());
INFOF("Received heartbeat : %s, %s\n", product_key.c_str(), device_name.c_str());
return 0;
}
static int handleEmit(String product_key, String device_name, String content) {
INFOF("received emit code : %s, %s, %s\n", product_key.c_str(), device_name.c_str(), content.c_str());
INFOF("Received emit code : %s, %s, %s\n", product_key.c_str(), device_name.c_str(), content.c_str());
g_iris_kit_status = IRIS_KIT_STATUS_EMITTING;
emit_code_doc.clear();
if (DeserializationError::Ok == deserializeJson(emit_code_doc, content)) {
int remote_id = emit_code_doc["remoteId"];
String key_name = emit_code_doc["keyName"];
String key_value = emit_code_doc["keyValue"];
INFOF("will emit key : %s for remote %d = %s\n", key_name.c_str(), remote_id, key_value.c_str());
INFOF("Emitting key : %s for remote %d = %s\n", key_name.c_str(), remote_id, key_value.c_str());
emitIR(key_value);
} else {
INFOF("deserialize failed\n");
INFOF("Deserialize failed\n");
}
g_iris_kit_status = IRIS_KIT_STATUS_IDLE;
return 0;
}
static int handleNotifyStatus(String product_key, String device_name, String content) {
INFOF("received status change notification : %s, %s, %s\n", product_key.c_str(), device_name.c_str(), content.c_str());
INFOF("Received status change notification : %s, %s, %s\n", product_key.c_str(), device_name.c_str(), content.c_str());
status_notify_doc.clear();
if (DeserializationError::Ok == deserializeJson(status_notify_doc, content)) {
String remote_index = status_notify_doc["remoteIndex"];
int key_id = status_notify_doc["keyId"];
String key_name = status_notify_doc["keyName"];
int status = status_notify_doc["status"];
int console_id = status_notify_doc["consoleId"];
INFOF("will enter status : %d for %s(%d)\n", status, key_name.c_str(), key_id);
INFOF("Entering status : %d for %s(%d)\n", status, key_name.c_str(), key_id);
processStatusChange(status, console_id, key_id, key_name);
processStatusChange(status, console_id, key_id, key_name, remote_index);
} else {
INFOF("deserialize failed\n");
INFOF("Deserialize failed\n");
}
return 0;
}
static int processStatusChange(int status, int console_id, int key_id, String key_name) {
static int processStatusChange(int status, int console_id, int key_id, String key_name, String remote_index) {
switch(status) {
case RECIPIENT_STATUS_TEST:
case IRIS_KIT_STATUS_TEST:
{
// send response for test notification
String testResponseData = buildTestResponse(console_id);
sendData(g_upstream_topic.c_str(), (uint8_t*) testResponseData.c_str(), testResponseData.length());
break;
}
case RECIPIENT_STATUS_READY_TO_STUDY:
case IRIS_KIT_STATUS_READY_TO_STUDY:
{
// enter into IR receive mode and send response
prepareRecvIR(key_id, key_name);
prepareRecvIR(key_id, key_name, remote_index);
String recvPreparedResponseData = buildRecvPreparedResponse(console_id);
sendData(g_upstream_topic.c_str(), (uint8_t*) recvPreparedResponseData.c_str(), recvPreparedResponseData.length());
break;
}
case RECIPIENT_STATUS_CANCEL_STUDY:
case IRIS_KIT_STATUS_CANCEL_STUDY:
{
// cancel IR receiving and reset
cancelRecvIR();
String studyCancelledResponseData = buildStudyCancelledResponse(console_id);
sendData(g_upstream_topic.c_str(), (uint8_t*) studyCancelledResponseData.c_str(), studyCancelledResponseData.length());

View File

@@ -29,14 +29,17 @@
#define PASSWORD_MAX (64)
typedef enum {
RECIPIENT_STATUS_IDLE = 0,
RECIPIENT_STATUS_READY_TO_STUDY = 1,
RECIPIENT_STATUS_STUDIED = 2,
RECIPIENT_STATUS_UPLOADED = 3,
RECIPIENT_STATUS_CANCEL_STUDY = 4,
RECIPIENT_STATUS_TEST = 10,
RECIPIENT_STATUS_MAX = 63,
} kit_status_t;
IRIS_KIT_STATUS_IDLE = 0,
IRIS_KIT_STATUS_READY_TO_STUDY = 1,
IRIS_KIT_STATUS_STUDIED = 2,
IRIS_KIT_STATUS_UPLOADED = 3,
IRIS_KIT_STATUS_CANCEL_STUDY = 4,
IRIS_KIT_STATUS_EMITTING = 5,
IRIS_KIT_STATUS_TEST = 10,
IRIS_KIT_STATUS_NOT_CONNECTED = 62,
IRIS_KIT_STATUS_MAX = 63,
} iris_kit_status_t;
// web http call URL list
#define GET_IRIS_KIT_ACCOUNT_SUFFIX "/irext-collect/credentials/auth_iris_kit"
@@ -44,8 +47,9 @@ typedef enum {
#define DOWNLOAD_BIN_SUFFIX "/irext-collect/download"
#define DOWNLOAD_PREFIX "http://irext-debug.oss-cn-hangzhou.aliyuncs.com/irda_"
#define DOWNLOAD_SUFFIX ".bin"
#define RECEIVED_SUFFIX ".rcv"
// IRext bin code storage
// IR bin code storage
#define SAVE_PATH "/ir/"
// IRIS communication

View File

@@ -53,7 +53,6 @@ extern String g_device_token;
extern String g_mqtt_client_id;
extern String g_mqtt_password;
extern int g_app_id;
extern int g_ready_to_study;
// public variable definitions
const unsigned long utcOffsetInMilliSeconds = 3600 * 1000;
@@ -62,10 +61,11 @@ int credential_init_retry = 0;
int g_runtime_env = RUNTIME_RELEASE;
iris_kit_settings_t iriskit_settings;
bool iris_kit_settings_loaded = false;
iris_kit_status_t g_iris_kit_status = IRIS_KIT_STATUS_NOT_CONNECTED;
// private variable definitions
static Ticker iotCheckTask; // IRext IoT MQTT check timer
static Ticker iotCheckTask; // IoT MQTT check timer
static Ticker disableIRTask; // disable IR receive
static Ticker disableRFTask; // disable RF receive
static Ticker saveDataTask; // save data
@@ -87,14 +87,14 @@ void setup() {
delay(SYSTEM_DELAY);
Serial.clearWriteError();
INFOLN();
INFOLN("██╗██████╗ ██╗███████╗");
INFOLN("██║██╔══██╗██║██╔════╝");
INFOLN("██║██████╔╝██║███████╗");
INFOLN("██║██╔══██╗██║╚════██║");
INFOLN("██║██║ ██║██║███████║");
INFOLN("╚═╝╚═╝ ╚═╝╚═╝╚══════╝");
INFOLN("== IRIS Kit [1.3.0_r1] Powered by AliyunIoT ==");
INFOF("\n");
INFOF("██╗██████╗ ██╗███████╗\n");
INFOF("██║██╔══██╗██║██╔════╝\n");
INFOF("██║██████╔╝██║███████╗\n");
INFOF("██║██╔══██╗██║╚════██║\n");
INFOF("██║██║ ██║██║███████║\n");
INFOF("╚═╝╚═╝ ╚═╝╚═╝╚══════╝\n");
INFOF("== IRIS Kit [1.3.1_r1] Powered by AliyunIoT ==\n");
// try loading saved iriskit settings
iriskit_settings.credential_token.clear();
@@ -103,10 +103,10 @@ void setup() {
if (loadSettings()) {
iriskit_settings = getIrisKitSettings();
INFOLN("saved credentials loaded");
INFOF("server address is empty ? %s\n", iriskit_settings.server_address.isEmpty() ? "yes" : "no");
INFOF("credential is empty ? %s\n", iriskit_settings.credential_token.isEmpty() ? "yes" : "no");
INFOF("password is empty ? %s\n", iriskit_settings.password.isEmpty() ? "yes" : "no");
INFOF("Saved credentials loaded\n");
INFOF("Server address is empty ? %s\n", iriskit_settings.server_address.isEmpty() ? "yes" : "no");
INFOF("Credential is empty ? %s\n", iriskit_settings.credential_token.isEmpty() ? "yes" : "no");
INFOF("Password is empty ? %s\n", iriskit_settings.password.isEmpty() ? "yes" : "no");
}
if (!iriskit_settings.credential_token.isEmpty() &&
!iriskit_settings.credential_token.equalsIgnoreCase("NULL") &&
@@ -117,7 +117,7 @@ void setup() {
iris_kit_settings_loaded = true;
}
INFOF("iriskit_settings_loaded ? %s\n", iris_kit_settings_loaded ? "yes" : "no");
INFOF("Setting loaded = %s\n", iris_kit_settings_loaded ? "successfully" : "failed");
// custom parameter for iris credentials
WiFiManagerParameter* server_address = NULL;
@@ -129,12 +129,12 @@ void setup() {
memset(iris_password, 0, PASSWORD_MAX);
if (iris_kit_settings_loaded) {
INFOLN("iriskit settings loaded");
INFOF("Settings loaded\n");
strncpy(iris_server_address, iriskit_settings.server_address.c_str(), URL_SHORT_MAX - 1);
strncpy(iris_credential_token, iriskit_settings.credential_token.c_str(), CREDENTIAL_MAX - 1);
strncpy(iris_password, iriskit_settings.password.c_str(), PASSWORD_MAX - 1);
}
INFOLN("iriskit settings not loaded, set it from WifiManager");
INFOF("Settings not loaded, set it from WifiManager\n");
server_address =
new WiFiManagerParameter("server_address", "Server Address", "iris.irext.net", URL_SHORT_MAX);
credential_token =
@@ -143,7 +143,7 @@ void setup() {
new WiFiManagerParameter("password", "User Password", "", PASSWORD_MAX, "type='password'");
if (NULL == server_address || NULL == credential_token || NULL == password) {
ERRORLN("not enough memory to create settings");
ERRORF("Not enough memory to create settings\n");
factoryReset();
}
wifi_manager.addParameter(server_address);
@@ -177,18 +177,20 @@ void setup() {
}
credential_init_retry++;
if (credential_init_retry >= CREDENTIAL_INIT_RETRY_MAX) {
ERRORLN("retried fetch credential for 3 times, reset WiFi");
ERRORF("Retried fetch credential for 3 times, reset WiFi\n");
wifiReset();
}
delay(SYSTEM_DELAY);
delay(AUTH_RETRY_DELAY);
} while (1);
INFOF("credential get : %s\n", iris_credential_token);
INFOF("Credential get : %s\n", iris_credential_token);
iriskit_settings.server_address = String(iris_server_address);
iriskit_settings.credential_token = String(iris_credential_token);
iriskit_settings.password = String(iris_password);
setIrisKitSettings(iriskit_settings);
g_iris_kit_status = IRIS_KIT_STATUS_IDLE;
saveSettings();
delay(SYSTEM_DELAY);
@@ -221,17 +223,19 @@ void setup() {
g_mqtt_client_id = g_device_name;
g_mqtt_password = iriskit_settings.password;
connectToIrextIoT();
if (0 != connectIot()) {
INFOF("Failed to connect IoT at startup\n");
}
iotCheckTask.attach_scheduled(MQTT_CHECK_INTERVALS, checkIrisIoT);
iotCheckTask.attach_scheduled(MQTT_CHECK_INTERVALS, checkIot);
disableIRTask.attach_scheduled(DISABLE_SIGNAL_INTERVALS, disableIRIn);
}
void loop() {
if (g_ready_to_study) {
if (IRIS_KIT_STATUS_READY_TO_STUDY == g_iris_kit_status) {
recvIR();
}
irextIoTKeepAlive();
keepAliveIot();
yield();
}
@@ -251,7 +255,7 @@ void factoryReset() {
// private function defitions
static void wifiReset() {
DEBUGLN("Reset settings");
INFOF("Reset settings\n");
LittleFS.format();
wifi_manager.resetSettings();
WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode !

View File

@@ -42,12 +42,12 @@ StaticJsonDocument<1024> ACStatus;
StaticJsonDocument<1024> IrisKitSettings;
bool saveSettings() {
DEBUGLN("save configs for IRIS Kit");
INFOF("Save configs\n");
// generic config partial
File cache = LittleFS.open(FILE_GENERIC_CONFIG, "w");
if (!cache || (serializeJson(ConfigData, cache) == 0)) {
ERRORLN("failed to save config file");
ERRORF("Failed to save config file\n");
cache.close();
return false;
}
@@ -56,7 +56,7 @@ bool saveSettings() {
// AC status partial
cache = LittleFS.open(FILE_AC_STATUS, "w");
if (!cache || (serializeJson(ACStatus, cache) == 0)) {
ERRORLN("ERROR: failed to save AC status file");
ERRORF("ERROR: failed to save AC status file\n");
cache.close();
return false;
}
@@ -65,7 +65,7 @@ bool saveSettings() {
// credential partial
cache = LittleFS.open(IRISKIT_SETTINGS, "w");
if (!cache || (serializeJson(IrisKitSettings, cache) == 0)) {
ERRORLN("ERROR: failed to save credentials file");
ERRORF("ERROR: failed to save credentials file\n");
cache.close();
return false;
}
@@ -78,45 +78,45 @@ bool loadSettings() {
int ret = false;
FSInfo64 info;
LittleFS.info64(info);
DEBUGF("fsstats: total bytes = %llu, used = %llu\n", info.totalBytes, info.usedBytes);
INFOF("Load settings, total bytes = %llu, used = %llu\n", info.totalBytes, info.usedBytes);
// generic config partial
if (LittleFS.exists(FILE_GENERIC_CONFIG)) {
File cache = LittleFS.open(FILE_GENERIC_CONFIG, "r");
if (!cache) {
ERRORLN("failed to read config file");
ERRORF("Failed to read config file\n");
return ret;
}
if (cache.size() > 0) {
DeserializationError error = deserializeJson(ConfigData, cache);
if (error) {
ERRORLN("failed to load config settings");
ERRORF("Failed to load config settings\n");
return ret;
}
INFOLN("generic config loaded");
INFOF("Generic config loaded\n");
ConfigData["version"] = FIRMWARE_VERSION;
serializeJsonPretty(ConfigData, Serial);
Serial.println();
}
cache.close();
} else {
DEBUGLN("config does not exist");
ERRORF("Config does not exist\n");
}
// AC status partial
if (LittleFS.exists(FILE_AC_STATUS)) {
File cache = LittleFS.open(FILE_AC_STATUS, "r");
if (!cache) {
ERRORLN("failed to read AC status file");
ERRORF("Failed to read AC status file\n");
return ret;
}
if (cache.size() > 0) {
DeserializationError error = deserializeJson(ACStatus, cache);
if (error) {
ERRORLN("failed to load AC status settings");
ERRORF("Failed to load AC status settings\n");
return ret;
}
INFOLN("AC status loaded");
INFOF("AC status loaded\n");
}
cache.close();
}
@@ -125,16 +125,16 @@ bool loadSettings() {
if (LittleFS.exists(IRISKIT_SETTINGS)) {
File cache = LittleFS.open(IRISKIT_SETTINGS, "r");
if (!cache) {
ERRORLN("failed to read acstatus file");
ERRORF("Failed to read acstatus file\n");
return ret;
}
if (cache.size() > 0) {
DeserializationError error = deserializeJson(IrisKitSettings, cache);
if (error) {
ERRORLN("failed to load credentials settings");
ERRORF("Failed to load credentials settings\n");
return ret;
}
INFOLN("credentials loaded");
INFOF("Credentials loaded\n");
}
cache.close();
}