implemented MQTT connection to EMQX dev

This commit is contained in:
strawmanbobi
2024-01-11 13:00:45 +08:00
parent 34259c8023
commit f81a3f6b2e
15 changed files with 162 additions and 149 deletions

View File

@@ -39,28 +39,27 @@
#include "IRISKit.h"
#define CREDENTIAL_INIT_RETRY_MAX (3)
#define SYSTEM_DELAY (2000)
// external variable declarations
extern char iris_server_address[];
extern char iris_credential_token[];
extern char iris_password[];
extern String g_mqtt_server;
extern String g_product_key;
extern String g_device_name;
extern String g_device_secret;
extern String g_mqtt_client_id;
extern String g_mqtt_password;
extern int g_app_id;
// public variable definitions
int credential_init_retry = 0;
t_iriskit_settings iriskit_settings;
bool iriskit_settings_loaded = false;
iris_kit_settings_t iriskit_settings;
bool iris_kit_settings_loaded = false;
// private variable definitions
static Ticker alinkCheckTask; // Aliyun IoT MQTT check timer
static Ticker iotCheckTask; // IRext IoT MQTT check timer
static Ticker disableIRTask; // disable IR receive
static Ticker disableRFTask; // disable RF receive
static Ticker saveDataTask; // save data
@@ -108,10 +107,10 @@ void setup() {
!iriskit_settings.server_address.equalsIgnoreCase("NULL") &&
!iriskit_settings.password.isEmpty() &&
!iriskit_settings.password.equalsIgnoreCase("NULL")) {
iriskit_settings_loaded = true;
iris_kit_settings_loaded = true;
}
INFOF("iriskit_settings_loaded ? %s\n", iriskit_settings_loaded ? "yes" : "no");
INFOF("iriskit_settings_loaded ? %s\n", iris_kit_settings_loaded ? "yes" : "no");
// custom parameter for iris credentials
WiFiManagerParameter* server_address = NULL;
@@ -122,7 +121,7 @@ void setup() {
memset(iris_credential_token, 0, CREDENTIAL_MAX);
memset(iris_password, 0, PASSWORD_MAX);
if (iriskit_settings_loaded) {
if (iris_kit_settings_loaded) {
INFOLN("iriskit settings loaded");
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);
@@ -147,15 +146,13 @@ void setup() {
wifi_manager.autoConnect();
if (!iriskit_settings_loaded) {
if (!iris_kit_settings_loaded) {
strncpy(iris_server_address, server_address->getValue(), URL_SHORT_MAX - 1);
strncpy(iris_credential_token, credential_token->getValue(), CREDENTIAL_MAX - 1);
String rawPassword = String(password->getValue());
strncpy(iris_password, md5(rawPassword).c_str(), PASSWORD_MAX - 1);
}
// digest password
// TODO: fix the logic without settings loaded
INFOF("Wifi Connected, IRIS server = %s, credential token = %s, password = %s\n",
iris_server_address, iris_credential_token, iris_password);
@@ -198,9 +195,26 @@ void setup() {
}
INFOF("IR pin config get : %d, %d\n", send_pin, recv_pin);
loadIRPin(send_pin, recv_pin);
// prepare MQTT connection params
if (NULL != strstr(iris_server_address, "iris.irext.net")) {
g_mqtt_server = String(MQTT_HOST_REL);
} else {
String iris_server_address_dev = iriskit_settings.server_address;
int delim = iris_server_address_dev.indexOf(':');
if (delim != -1) {
g_mqtt_server = iris_server_address_dev.substring(0, delim);
} else {
g_mqtt_server = iris_server_address_dev;
}
}
g_mqtt_client_id = g_device_name;
g_mqtt_password = iriskit_settings.password;
connectToIrextIoT();
alinkCheckTask.attach_scheduled(MQTT_CHECK_INTERVALS, checkIrextIoT);
iotCheckTask.attach_scheduled(MQTT_CHECK_INTERVALS, checkIrextIoT);
disableIRTask.attach_scheduled(DISABLE_SIGNAL_INTERVALS, disableIR);
}

View File

@@ -21,16 +21,16 @@
* SOFTWARE.
*/
#ifndef IRBABY_H
#define IRBABY_H
#ifndef IRIS_KIT_H
#define IRIS_KIT_H
typedef struct {
String server_address;
String credential_token;
String password;
} t_iriskit_settings;
} iris_kit_settings_t;
void IRAM_ATTR factoryReset();
#endif // IRBABY_H
#endif // IRIS_KIT_H

View File

@@ -21,8 +21,8 @@
* SOFTWARE.
*/
#ifndef IRBABY_GLOBAL_H
#define IRBABY_GLOBAL_H
#ifndef IRIS_KIT_GLOBAL_H
#define IRIS_KIT_GLOBAL_H
#include <ArduinoJson.h>
#include <WiFiManager.h>
@@ -44,4 +44,4 @@ extern uint8_t ir_receive_pin;
extern uint8_t rf433_receive_pin;
#endif
#endif // IRBABY_GLOBAL_H
#endif // IRIS_KIT_GLOBAL_H

View File

@@ -21,8 +21,8 @@
* SOFTWARE.
*/
#ifndef IRBABY_HA_H
#define IRBABY_HA_H
#ifndef IRIS_KIT_HA_H
#define IRIS_KIT_HA_H
#include <WString.h>
@@ -32,4 +32,4 @@ void returnACStatus(String filename, t_remote_ac_status ac_status);
void registAC(String filename, bool flag);
#endif // IRBABY_HA_H
#endif // IRIS_KIT_HA_H

View File

@@ -21,8 +21,8 @@
* SOFTWARE.
*/
#ifndef IRBABY_HTTP_H
#define IRBABY_HTTP_H
#ifndef IRIS_KIT_HTTP_H
#define IRIS_KIT_HTTP_H
#include <WString.h>
@@ -45,4 +45,4 @@ http_error_t httpPost(String url, String request_data, String& result);
http_error_t downLoadFile(String url, String file, String path);
#endif // IRBABY_HTTP_H
#endif // IRIS_KIT_HTTP_H

View File

@@ -21,8 +21,8 @@
* SOFTWARE.
*/
#ifndef IRBABY_IR_H
#define IRBABY_IR_H
#ifndef IRIS_KIT_IR_H
#define IRIS_KIT_IR_H
#include <Arduino.h>
#include <IRsend.h>
@@ -54,4 +54,4 @@ bool saveIR(String file_name);
void initAC(String);
#endif // IRBABY_IR_H
#endif // IRIS_KIT_IR_H

View File

@@ -65,6 +65,8 @@ 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 hb_count = 0;
// private variable definitions
event_handler_t event_handler_table[] = {
{
@@ -91,14 +93,10 @@ int getIRISKitVersion(char *buffer, int buffer_size) {
return strlen(buffer);
}
int getDeviceID(char* buffer, int buffer_size) {
if (NULL == buffer) {
return -1;
}
String chipId = String(ESP.getChipId(), HEX);
memset(buffer, 0, buffer_size);
snprintf(buffer, buffer_size - 1, "%s", chipId.c_str());
return strlen(buffer);
String getDeviceID() {
String device_id("IRISKit_");
device_id.concat(String(ESP.getChipId(), HEX));
return device_id;
}
int authIrisKitAccount(String credential_token,
@@ -113,7 +111,7 @@ int authIrisKitAccount(String credential_token,
String fetch_credential_url;
String request_data = "";
String response_data = "";
String device_id("IRbaby_");
http_error_t http_ret = HTTP_ERROR_GENERIC;
if (NULL != strstr(iris_server_address, "http://")) {
@@ -126,7 +124,6 @@ int authIrisKitAccount(String credential_token,
fetch_credential_url.concat(iris_server_address);
}
fetch_credential_url.concat(String(GET_IRIS_KIT_ACCOUNT_SUFFIX));
device_id.concat(String(ESP.getChipId(), HEX));
INFOF("fetch credential URL = %s\n", fetch_credential_url.c_str());
if (credential_token.isEmpty()) {
@@ -141,7 +138,7 @@ int authIrisKitAccount(String credential_token,
product_key = credential_token.substring(0, tsi);
device_name = credential_token.substring(tsi + 1);
http_request_doc.clear();
http_request_doc["deviceID"] = device_id;
http_request_doc["deviceID"] = getDeviceID();
http_request_doc["credentialToken"] = credential_token;
http_request_doc["password"] = password;
serializeJson(http_request_doc, request_data);
@@ -205,6 +202,7 @@ void sendIrisKitConnect() {
}
void sendIrisKitHeartBeat() {
INFOLN("send iris kit heart beat[%d]", hb_count++);
String heartBeatMessage = buildHeartBeat();
sendData(g_upstream_topic.c_str(), (uint8_t*) heartBeatMessage.c_str(), heartBeatMessage.length());
}

View File

@@ -21,8 +21,8 @@
* SOFTWARE.
*/
#ifndef IRBABY_IRIS_H
#define IRBABY_IRIS_H
#ifndef IRIS_KIT_IR_BABY_H
#define IRIS_KIT_IR_BABY_H
#define CREDENTIAL_MAX (40)
#define USER_NAME_MAX (64)
@@ -50,7 +50,7 @@ typedef struct {
int getIRISKitVersion(char *buffer, int buffer_size);
int getDeviceID(char* buffer, int buffer_size);
String getDeviceID();
int authIrisKitAccount(String credential_token,
String password,
@@ -65,4 +65,4 @@ void sendIrisKitHeartBeat();
void handleIrisKitMessage(const char* data, int length);
#endif // IRBABY_IRIS_H
#endif // IRIS_KIT_IR_BABY_H

View File

@@ -23,6 +23,7 @@
#include <Arduino.h>
#include <WString.h>
#include <PubSubClient.h>
#include "IRISKitSerials.h"
#include "IRISKitIoT.h"
@@ -31,35 +32,41 @@
#include "IRISKit.h"
#define TOPIC_NAME_MAX (64)
#define IOT_RETRY_MAX (3)
#define IRIS_KIT_PK_DEV "a1WlzsJh50b"
#define IRIS_KIT_PK_REL "a1ihYt1lqGH"
#define TOPIC_DOWNSTREAM_DEV "/user/iris/downstream_dev"
#define TOPIC_UPSTREAM_DEV "/user/iris/upstream_dev"
#define TOPIC_DOWNSTREAM_REL "/user/iris/downstream"
#define TOPIC_UPSTREAM_REL "/user/iris/upstream"
#define TOPIC_DOWNSTREAM_DEV "/user/iris_kit_downstream_dev"
#define TOPIC_UPSTREAM_DEV "/user/iris_kit_upstream_dev"
#define TOPIC_DOWNSTREAM_REL "/user/iris_kit_downstream"
#define TOPIC_UPSTREAM_REL "/user/iris_kit_upstream"
String g_mqtt_server = "";
String g_product_key = "";
String g_device_name = "";
String g_device_secret = "";
String g_region_id = "cn-shanghai";
String g_mqtt_client_id = "";
String g_mqtt_user_name = "";
String g_mqtt_password = "";
String g_upstream_topic = "";
String g_downstream_topic = "";
int g_app_id = 0;
int g_mqtt_port = 1883;
int g_app_id = 0;
static bool downstream_topic_subscribed = false;
static ep_state_t endpoint_state = FSM_IDLE;
static void registerCallback(const char* topic, int qos);
static void irisIrextIoTCallback(const char *topic, uint8_t *data, int length);
static int connectToMQTTBroker();
static void irisIrextIoTCallback(char *topic, uint8_t *data, uint32_t length);
static int iot_retry = 0;
void connectToIrextIoT() {
static PubSubClient mqtt_client(wifi_client);
int connectToIrextIoT() {
downstream_topic_subscribed = false;
int conn_ret = -1;
if (g_product_key.equals(IRIS_KIT_PK_DEV)) {
g_upstream_topic = "/" + g_product_key + "/" + g_device_name + TOPIC_UPSTREAM_DEV;
@@ -69,70 +76,77 @@ void connectToIrextIoT() {
g_downstream_topic = "/" + g_product_key + "/" + g_device_name + TOPIC_DOWNSTREAM_REL;
} else {
ERRORF("IRIS Kit release key is not supported yet\n");
return;
factoryReset();
return -1;
}
INFOF("Try connecting to Aliyun IoT : %s, %s, %s, %s\n",
g_product_key.c_str(), g_device_name.c_str(), g_device_secret.c_str(), g_region_id.c_str());
g_mqtt_user_name = getDeviceID();
/*
if (0 == iot.begin(wifi_client, g_product_key.c_str(), g_device_name.c_str(), g_device_secret.c_str(),
g_region_id.c_str())) {
INFOF("Try connecting to IRext 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());
mqtt_client.setServer(g_mqtt_server.c_str(), g_mqtt_port);
mqtt_client.setCallback(irisIrextIoTCallback);
conn_ret = connectToMQTTBroker();
if (0 != conn_ret) {
ERRORLN("Something may went wrong with your credential, please retry connect to Wifi...");
factoryReset();
return -1;
}
// send connect request
sendIrisKitConnect();
}
*/
INFOLN("Aliyun IoT connect done");
return 0;
}
void irextIoTKeepAlive() {
/*
iot.loop();
*/
if (!mqtt_client.connected()) {
connectToMQTTBroker();
}
mqtt_client.loop();
}
// not only for IRIS related topic based session
void sendData(const char* topic, const uint8_t *data, int length) {
/*
iot.sendCustomData(topic, data, length);
*/
mqtt_client.publish(topic, data, length);
}
void* getSession() {
return NULL;
return &mqtt_client;
}
void checkIrextIoT() {
int mqttStatus = 0;
if (0 == mqttStatus) {
iot_retry = 0;
if (false == downstream_topic_subscribed) {
INFOF("subscribe topic : %s\n", g_downstream_topic.c_str());
registerCallback(g_downstream_topic.c_str(), 0);
downstream_topic_subscribed = true;
} else {
sendIrisKitHeartBeat();
}
static int connectToMQTTBroker() {
int retry_times = 0;
while (!mqtt_client.connected() && retry_times < MQTT_RETRY_MAX) {
INFOF("Connecting to MQTT Broker as %s.....\n", g_mqtt_client_id.c_str());
if (mqtt_client.connect(g_mqtt_client_id.c_str(), g_mqtt_user_name.c_str(), g_mqtt_password.c_str())) {
INFOF("Connected to MQTT broker\n");
mqtt_client.subscribe(g_downstream_topic.c_str());
} else {
INFOF("Alink MQTT check failed, retry = %d\n", iot_retry);
iot_retry++;
ERRORF("Failed to connect to MQTT broker, rc = %d\n", mqtt_client.state());
INFOF(" try again in 5 seconds\n");
retry_times++;
delay(MQTT_RETRY_DELAY);
}
if (iot_retry >= IOT_RETRY_MAX) {
ERRORLN("Alink could not established, something went wrong, reset...");
factoryReset();
}
if (mqtt_client.connected()) {
INFOF("IRext IoT connect done\n");
return 0;
} else {
ERRORF("IRext IoT failed to connect\n");
return -1;
}
}
static void registerCallback(const char* topic, int qos) {
/*
if (iot.subscribe(topic, qos)) {
INFOLN("topic subscribed");
iot.registerCustomCallback(irisIrextIoTCallback);
}
*/
}
static void irisIrextIoTCallback(const char *topic, uint8_t *data, int length) {
static void irisIrextIoTCallback(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

@@ -21,8 +21,8 @@
* SOFTWARE.
*/
#ifndef IRBABY_ALINK_H
#define IRBABY_ALINK_H
#ifndef IRIS_KIT_IOT_H
#define IRIS_KIT_IOT_H
#include <stdint.h>
@@ -34,7 +34,7 @@ typedef enum {
FSM_MAX = 7,
} ep_state_t;
void connectToIrextIoT();
int connectToIrextIoT();
void irextIoTKeepAlive();
@@ -46,4 +46,4 @@ void sendData(const char* topic, const uint8_t *data, int length);
int securityPublish(const char *topic, const uint8_t *message, size_t msg_size, void *channel);
#endif // IRBABY_ALINK_H
#endif // IRIS_KIT_IOT_H

View File

@@ -21,8 +21,8 @@
* SOFTWARE.
*/
#ifndef IRBABY_SERIAL_H
#define IRBABY_SERIAL_H
#ifndef IRIS_KIT_SERIALS_H
#define IRIS_KIT_SERIALS_H
#include <Arduino.h>
@@ -51,4 +51,4 @@
#define ERROR(...) \
{if (LOG_ERROR) { Serial.printf("ERROR:\t"); Serial.print(__VA_ARGS__);}}
#endif // IREASY_SERIAL_H
#endif // IRIS_KIT_SERIALS_H

View File

@@ -168,15 +168,15 @@ t_remote_ac_status getACStatus(String file) {
return status;
}
bool setIrisKitSettings(t_iriskit_settings& iriskit_settings) {
bool setIrisKitSettings(iris_kit_settings_t& iriskit_settings) {
IrisKitSettings["server_address"] = iriskit_settings.server_address;
IrisKitSettings["token"] = iriskit_settings.credential_token;
IrisKitSettings["password"] = iriskit_settings.password;
return true;
}
t_iriskit_settings getIrisKitSettings() {
t_iriskit_settings iriskit_settings;
iris_kit_settings_t getIrisKitSettings() {
iris_kit_settings_t iriskit_settings;
iriskit_settings.server_address = (String)IrisKitSettings["server_address"];
iriskit_settings.credential_token = (String)IrisKitSettings["token"];
iriskit_settings.password = (String)IrisKitSettings["password"];

View File

@@ -21,8 +21,8 @@
* SOFTWARE.
*/
#ifndef IRBABY_USER_SETTINGS_H
#define IRBABY_USER_SETTINGS_H
#ifndef IRIS_KIT_USER_SETTINGS_H
#define IRIS_KIT_USER_SETTINGS_H
#include <ArduinoJson.h>
@@ -39,11 +39,11 @@ bool loadSettings();
bool saveACStatus(String file, t_remote_ac_status status);
t_remote_ac_status getACStatus(String file);
bool setIrisKitSettings(t_iriskit_settings& iriskit_settings);
t_iriskit_settings getIrisKitSettings();
bool setIrisKitSettings(iris_kit_settings_t& iriskit_settings);
iris_kit_settings_t getIrisKitSettings();
extern StaticJsonDocument<1024> ConfigData;
extern StaticJsonDocument<1024> ACStatus;
extern StaticJsonDocument<1024> IrisKitSettings;
#endif // IRBABY_USER_SETTINGS_H
#endif // IRIS_KIT_USER_SETTINGS_H

View File

@@ -23,12 +23,12 @@
#include "WString.h"
#ifndef IRBABY_IRIS_UTILS_H
#define IRBABY_IRIS_UTILS_H
#ifndef IRIS_KIT_UTILS_H
#define IRIS_KIT_UTILS_H
int split_string(const String source, char* parts[], const char* delimiter);
String md5(String str);
#endif //IRBABY_IRIS_UTILS_H
#endif // IRIS_KIT_UTILS_H

View File

@@ -30,11 +30,12 @@ typedef unsigned short uint16_t;
typedef short int16_t;
typedef unsigned char uint8_t;
#define FIRMWARE_VERSION "1.2.7" // version name
#define VERSION_CODE 1 // version code
/* ----------------- version defs ----------------- */
#define FIRMWARE_VERSION "1.3.0"
#define VERSION_CODE (2)
/* log settings */
#define BAUD_RATE 115200
/* ----------------- log settings ----------------- */
#define BAUD_RATE (115200)
#ifndef LOG_DEBUG
#define LOG_DEBUG false
#endif
@@ -45,39 +46,25 @@ typedef unsigned char uint8_t;
#define LOG_ERROR true
#endif
/* ----------------- user settings ----------------- */
/* mqtt settings */
#define MQTT_CHECK_INTERVALS 30 // seconds
#define MQTT_CONNECT_WAIT_TIME 20000 // MQTT 连接等待时间
/* ----------------- auth settings ----------------- */
#define CREDENTIAL_INIT_RETRY_MAX (3)
#define SYSTEM_DELAY (2000)
/* receive disable */
#define DISABLE_SIGNAL_INTERVALS 600 // seconds
/* ----------------- iot settings -----------------*/
#define MQTT_HOST_REL "iot.irext.net"
#define MQTT_CHECK_INTERVALS (30)
#define MQTT_CONNECT_WAIT_TIME (20000)
#define MQTT_RETRY_DELAY (5000)
#define MQTT_RETRY_MAX (5)
#define SAVE_DATA_INTERVALS 300 // seconds
// uncomment below to enable RF
// #define USE_RF
// uncomment below to enable upload chip id to remote server
// #define USE_INFO_UPLOAD
/* ----------------- storage settings ----------------- */
#define DISABLE_SIGNAL_INTERVALS (600)
#define SAVE_DATA_INTERVALS (300)
/* ----------------- default pin setting --------------- */
/* reset pin */
#define RESET_PIN 2
/* 315 RF pin */
// #define T_315 5
// #define R_315 4
/* 433 RF pin */
#define T_433 14
#define R_433 12
/* IR pin */
#define T_IR 4
#define R_IR 14
/* ----------------- lsoc setting --------------- */
/* lsoc heart beat cycle */
#define LSOC_HB_CYCLE 1800
/* ----------------- pin settings --------------- */
#define RESET_PIN (2)
#define T_IR (4)
#define R_IR (14)
#endif // _DEFINES_H