Created
January 15, 2015 07:03
-
-
Save tuanpmt/2f84d61bb20352a6aaa6 to your computer and use it in GitHub Desktop.
esp_mqtt-usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ets_sys.h" | |
#include "driver/uart.h" | |
#include "osapi.h" | |
#include "mqtt.h" | |
#include "wifi.h" | |
#include "config.h" | |
#include "debug.h" | |
#include "gpio.h" | |
#include "user_interface.h" | |
MQTT_Client mqttClient; | |
void wifiConnectCb(uint8_t status) | |
{ | |
if(status == STATION_GOT_IP){ | |
MQTT_Connect(&mqttClient); | |
} | |
} | |
void mqttConnectedCb(uint32_t *args) | |
{ | |
MQTT_Client* client = (MQTT_Client*)args; | |
INFO("MQTT: Connected\r\n"); | |
MQTT_Subscribe(client, "/mqtt/topic/1", 0); | |
MQTT_Subscribe(client, "/mqtt/topic/2", 0); | |
MQTT_Publish(client, "/mqtt/topic/2", "hello2", 6, 0, 0); | |
MQTT_Publish(client, "/mqtt/topic/1", "hello1", 6, 0, 0); | |
} | |
void mqttDisconnectedCb(uint32_t *args) | |
{ | |
MQTT_Client* client = (MQTT_Client*)args; | |
INFO("MQTT: Disconnected\r\n"); | |
} | |
void mqttPublishedCb(uint32_t *args) | |
{ | |
MQTT_Client* client = (MQTT_Client*)args; | |
INFO("MQTT: Published\r\n"); | |
} | |
void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len) | |
{ | |
char topicBuf[64], dataBuf[64]; | |
MQTT_Client* client = (MQTT_Client*)args; | |
os_memcpy(topicBuf, topic, topic_len); | |
topicBuf[topic_len] = 0; | |
os_memcpy(dataBuf, data, data_len); | |
dataBuf[data_len] = 0; | |
INFO("MQTT topic: %s, data: %s \r\n", topicBuf, dataBuf); | |
} | |
void user_init(void) | |
{ | |
uart_init(BIT_RATE_115200, BIT_RATE_115200); | |
os_delay_us(1000000); | |
CFG_Load(); | |
MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, sysCfg.security); | |
MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive); | |
MQTT_OnConnected(&mqttClient, mqttConnectedCb); | |
MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb); | |
MQTT_OnPublished(&mqttClient, mqttPublishedCb); | |
MQTT_OnData(&mqttClient, mqttDataCb); | |
WIFI_Connect(sysCfg.sta_ssid, sysCfg.sta_pwd, wifiConnectCb); | |
INFO("\r\nSystem started ...\r\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment