98 lines
2.7 KiB
C
Raw Normal View History

2020-11-13 12:38:08 +01:00
#include <mqttTest.h>
#include <logger.h>
#include <pubsubc.h>
#include <platformAdaption.h>
2020-11-13 13:08:12 +01:00
#include <PontCoopScheduler.h>
2020-11-13 13:08:56 +01:00
#include <wizHelper.h>
2020-11-13 12:38:08 +01:00
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
2020-11-13 14:22:26 +01:00
#include <string.h>
2020-11-13 12:38:08 +01:00
extern const uint8_t MQTT_SOCK;
client_t client;
mqttClient_t mqttClient;
2020-11-13 13:08:12 +01:00
uint8_t brokerAddress[] = { 172, 16, 2, 16 };
uint16_t brokerPort = 1883;
2020-11-13 12:38:08 +01:00
// typedef void (*callback_t)(char*, uint8_t*, uint16_t);
static void mqttCallback(char *topic, uint8_t *payload, uint16_t payloadLength) {
2020-11-13 14:30:41 +01:00
logMsg("mcb: %s : %*s", topic, payloadLength, payload);
2020-11-13 12:38:08 +01:00
}
2020-11-13 13:08:12 +01:00
2020-11-13 14:22:26 +01:00
void mqttLoopHandler(void *handle) {
mqttLoop(&mqttClient);
}
2020-11-13 13:08:12 +01:00
void mqttTestHandler(void *handle) {
static uint8_t state = 0;
static uint8_t message[] = "Hello world\n\r";
if (isNetworkAvailable()) {
switch (state) {
case 0:
coloredMsg(LOG_YELLOW, "mth, initializing mqtt client");
client.sockNum = MQTT_SOCK;
mqttClientInit(&mqttClient, &client, mqttCallback);
coloredMsg(LOG_YELLOW, "mth: mqtt client initialized");
state = 1;
break;
case 1:
coloredMsg(LOG_YELLOW, "mth, connecting to broker ");
bool res = mqttConnect(&mqttClient, brokerAddress, 1883, "mbv3gw-client", NULL, NULL, NULL, 0, false, NULL, false);
coloredMsg(LOG_YELLOW, "mth, mqttConnect returns %d", res);
if (res) {
coloredMsg(LOG_YELLOW, "mth, ok, connected");
state = 2;
} else {
state = 255;
}
break;
case 2:
2020-11-13 14:22:26 +01:00
coloredMsg(LOG_YELLOW, "mth, start mqtt loop");
schAdd(mqttLoopHandler, NULL, 0, 100);
state = 3;
break;
2020-11-13 13:08:12 +01:00
2020-11-13 14:22:26 +01:00
case 3:
coloredMsg(LOG_YELLOW, "mth, publish something");
res = publish(&mqttClient, "wiznet/hello", message, strlen(message), false);
coloredMsg(LOG_YELLOW, "mth, publish returned %d", res);
state = 4;
2020-11-13 13:08:12 +01:00
break;
2020-11-13 14:22:26 +01:00
case 4:
2020-11-13 14:25:48 +01:00
coloredMsg(LOG_YELLOW, "mth, subscribe something");
res = subscribe(&mqttClient, "wiznet/helloback", MQTTQOS0);
coloredMsg(LOG_YELLOW, "mth, subscribe returned %d", res);
state = 5;
break;
case 5:
2020-11-13 14:30:41 +01:00
// coloredMsg(LOG_YELLOW, "mth, waiting");
2020-11-13 14:22:26 +01:00
break;
2020-11-13 13:08:12 +01:00
case 255:
coloredMsg(LOG_YELLOW, "mth, error state, will stop here");
schDel(mqttTestHandler, NULL);
2020-11-13 14:22:26 +01:00
schDel(mqttLoopHandler, NULL);
2020-11-13 13:08:12 +01:00
break;
}
} else {
coloredMsg(LOG_YELLOW, "mth, network not yet ready");
}
2020-11-13 12:38:08 +01:00
}
2020-11-13 13:08:12 +01:00
void mqttTestInit() {
schAdd(mqttTestHandler, NULL, 0, 100);
}