Simplify MQTT code

This commit is contained in:
Mathieu Maret 2016-09-27 23:44:52 +02:00
parent ad7b6b3213
commit 20e4869a21

View File

@ -29,8 +29,6 @@ const int gpioWatched[] = CONFIG_MQTT_CONTROLLED_GPIO;
#define IP_FEED_FORMAT "/feeds/%s/%s/configuration/ip/addr" #define IP_FEED_FORMAT "/feeds/%s/%s/configuration/ip/addr"
char *mqttId; char *mqttId;
char GPIO_FEED[MAXSUBSCRIPTIONS][FEED_MAX_SIZE] = {};
char GPIO_SET_FEED[MAXSUBSCRIPTIONS][FEED_MAX_SIZE] = {};
Adafruit_MQTT_Publish * mqttGpio[MAXSUBSCRIPTIONS] = {}; Adafruit_MQTT_Publish * mqttGpio[MAXSUBSCRIPTIONS] = {};
@ -58,14 +56,8 @@ int MqttSetup(char *server, char *user, char *passwd, int port, char * hostname)
mqtt_ip = MqttCreatePublisher(IP_FEED_FORMAT, user, mqttId); mqtt_ip = MqttCreatePublisher(IP_FEED_FORMAT, user, mqttId);
for (uint i = 0 ; i < NB_ELEMENTS(gpioWatched) && i < MAXSUBSCRIPTIONS; i++) { for (uint i = 0 ; i < NB_ELEMENTS(gpioWatched) && i < MAXSUBSCRIPTIONS; i++) {
snprintf(GPIO_FEED[i], FEED_MAX_SIZE, GPIO_FEED_FORMAT, user, mqttId, gpioWatched[i]); mqtt->subscribe(MqttCreateSubscribe(GPIO_SET_FEED_FORMAT, user, mqttId, gpioWatched[i]));
snprintf(GPIO_SET_FEED[i], FEED_MAX_SIZE, GPIO_SET_FEED_FORMAT, user, mqttId, gpioWatched[i]); mqttGpio[i] = MqttCreatePublisher(GPIO_FEED_FORMAT, user, mqttId, gpioWatched[i]);
Adafruit_MQTT_Subscribe *gpioSet = new Adafruit_MQTT_Subscribe(mqtt, GPIO_SET_FEED[i]);
mqtt->subscribe(gpioSet);
Adafruit_MQTT_Publish *gpio = new Adafruit_MQTT_Publish(mqtt, GPIO_FEED[i]);
mqttGpio[i] = gpio;
} }
return 0; return 0;
} }
@ -76,12 +68,16 @@ Adafruit_MQTT_Publish *MqttCreatePublisher(const char *fmt, ...){
va_start (args, fmt); va_start (args, fmt);
vsnprintf(buf, sizeof(buf), (const char *)fmt, args); vsnprintf(buf, sizeof(buf), (const char *)fmt, args);
va_end(args); va_end(args);
String *url = new String(buf); return new Adafruit_MQTT_Publish(mqtt, strdup(buf));
return new Adafruit_MQTT_Publish(mqtt, url->c_str());
} }
bool MqttIsConfigured() { Adafruit_MQTT_Subscribe *MqttCreateSubscribe(const char *fmt, ...){
return isMqttConfigured; char buf[FEED_MAX_SIZE];
va_list args;
va_start (args, fmt);
vsnprintf(buf, sizeof(buf), (const char *)fmt, args);
va_end(args);
return new Adafruit_MQTT_Subscribe(mqtt, strdup(buf));
} }
int MqttIsConnected() { int MqttIsConnected() {