move to new skeleton

This commit is contained in:
Sergio R. Caprile committed 2024-04-26 13:46:18 -03:00
1 parent 290d48e1aa
commit 8c5dfa4227
82 files changed
+34 -34

No files matched your search

@@ -0,0 +1,32 @@
PROG ?= example # Program we are building
DELETE = rm -rf # Command to remove files
OUT ?= -o $(PROG) # Compiler argument for output file
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
CFLAGS = -W -Wall -Wextra -g -I. # Build options
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
PROG ?= example.exe # Use .exe suffix for the binary
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
OUT ?= -o $(PROG) # Build output
MAKE += WINDOWS=1 CC=$(CC)
endif
all: $(PROG) # Default target. Build and run program
$(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) # Build program from sources
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
clean: # Cleanup. Delete built program and all build artifacts
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
mbedtls: # Pull and build mbedTLS library
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
$(MAKE) -C mbedtls/library
@@ -0,0 +1,2 @@
- This example requires generating AWS and user credentials and downloading certificates
- This example requires building with TLS support; before running, see detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-client-aws-iot/
+101
View File
@@ -0,0 +1,101 @@
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
// Example MQTT client. It performs the following steps:
// 1. Connects to the AWS IoT MQTT server
// 2. When connected, subscribes to the topic `s_rx_topic`
// 3. Publishes message `hello` to the `s_tx_topic` periodically
//
// This example requires TLS support. By default, it is built with mbedTLS,
// therefore make sure mbedTLS is installed. To build with OpenSSL, execute:
// make clean all CFLAGS="-W -Wall -DMG_ENABLE_OPENSSL=1 -lssl"
// In order to get MQTT URL, login to AWS IoT, click on "Settings" on the left
// bar, copy the "Endpoint" URL.
static const char *s_url =
"mqtts://a1pjwh2bop1ojt-ats.iot.eu-west-1.amazonaws.com";
// To create certificates:
// 1. Click Policies -> Create, fill fields:
// Name : Policy1
// Action : iot:*
// Resource ARN: *
// Effect : allow
// then, click "Create"
// 2. Click Manage -> Things -> Create things -> Create single thing -> Next
// Thing name: t1, no shadow, Next
// Auto-generate new certificate, Next
// Select policy Policy1, Create thing
// 3. From the dialog box that appears, download:
// xxx-certificate.pem.crt as cert.pem to the example directory
// xxx-private.pem.key as key.pem to the example directory
// static const char *s_cert = "cert.pem";
// static const char *s_key = "key.pem";
static const char *s_rx_topic = "d/rx";
static const char *s_tx_topic = "d/tx";
static int s_qos = 1;
#include "mongoose.h"
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_OPEN) {
// c->is_hexdumping = 1;
} else if (ev == MG_EV_CONNECT) {
if (mg_url_is_ssl(s_url)) {
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
.name = mg_url_host(s_url)};
mg_tls_init(c, &opts);
}
} else if (ev == MG_EV_ERROR) {
// On error, log error message
MG_ERROR(("%p %s", c->fd, (char *) ev_data));
} else if (ev == MG_EV_MQTT_OPEN) {
// MQTT connect is successful
struct mg_str topic = mg_str(s_rx_topic);
MG_INFO(("Connected to %s", s_url));
MG_INFO(("Subscribing to %s", s_rx_topic));
struct mg_mqtt_opts sub_opts;
memset(&sub_opts, 0, sizeof(sub_opts));
sub_opts.topic = topic;
sub_opts.qos = s_qos;
mg_mqtt_sub(c, &sub_opts);
c->data[0] = 'X'; // Set a label that we're logged in
} else if (ev == MG_EV_MQTT_MSG) {
// When we receive MQTT message, print it
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
MG_INFO(("Received on %.*s : %.*s", (int) mm->topic.len, mm->topic.buf,
(int) mm->data.len, mm->data.buf));
} else if (ev == MG_EV_POLL && c->data[0] == 'X') {
static unsigned long prev_second;
unsigned long now_second = (*(unsigned long *) ev_data) / 1000;
if (now_second != prev_second) {
struct mg_str topic = mg_str(s_tx_topic), data = mg_str("{\"a\":123}");
MG_INFO(("Publishing to %s", s_tx_topic));
struct mg_mqtt_opts pub_opts;
memset(&pub_opts, 0, sizeof(pub_opts));
pub_opts.topic = topic;
pub_opts.message = data;
pub_opts.qos = s_qos, pub_opts.retain = false;
mg_mqtt_pub(c, &pub_opts);
prev_second = now_second;
}
}
if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE) {
MG_INFO(("Got event %d, stopping...", ev));
*(bool *) c->fn_data = true; // Signal that we're done
}
}
int main(void) {
struct mg_mgr mgr;
struct mg_mqtt_opts opts = {.clean = true};
bool done = false;
mg_mgr_init(&mgr); // Initialise event manager
MG_INFO(("Connecting to %s", s_url)); // Inform that we're starting
mg_mqtt_connect(&mgr, s_url, &opts, fn, &done); // Create client connection
while (!done) mg_mgr_poll(&mgr, 1000); // Loop until done
mg_mgr_free(&mgr); // Finished, cleanup
return 0;
}
+1
View File
@@ -0,0 +1 @@
../../../mongoose.c
+1
View File
@@ -0,0 +1 @@
../../../mongoose.h
+1
View File
@@ -0,0 +1 @@
../../http/http-client/packed_fs.c
+32
View File
@@ -0,0 +1,32 @@
PROG ?= example # Program we are building
DELETE = rm -rf # Command to remove files
OUT ?= -o $(PROG) # Compiler argument for output file
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
CFLAGS = -W -Wall -Wextra -g -I. # Build options
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
PROG ?= example.exe # Use .exe suffix for the binary
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
OUT ?= -o $(PROG) # Build output
MAKE += WINDOWS=1 CC=$(CC)
endif
all: $(PROG) # Default target. Build and run program
$(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) # Build program from sources
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
clean: # Cleanup. Delete built program and all build artifacts
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
mbedtls: # Pull and build mbedTLS library
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
$(MAKE) -C mbedtls/library
+1
View File
@@ -0,0 +1 @@
See detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-client/
+114
View File
@@ -0,0 +1,114 @@
// Copyright (c) 2023 Cesanta Software Limited
// All rights reserved
//
// Example MQTT client. It performs the following steps:
// 1. Connects to the MQTT server specified by `s_url` variable
// 2. When connected, subscribes to the topic `s_sub_topic`
// 3. Publishes message `hello` to the `s_pub_topic`
// 4. Receives that message back from the subscribed topic and closes
// 5. Timer-based reconnection logic revives the connection when it is down
//
// To enable SSL/TLS, see https://mongoose.ws/tutorials/tls/#how-to-build
#include "mongoose.h"
static const char *s_url = "mqtt://broker.hivemq.com:1883";
static const char *s_sub_topic = "mg/+/test"; // Publish topic
static const char *s_pub_topic = "mg/clnt/test"; // Subscribe topic
static int s_qos = 1; // MQTT QoS
static struct mg_connection *s_conn; // Client connection
// Handle interrupts, like Ctrl-C
static int s_signo;
static void signal_handler(int signo) {
s_signo = signo;
}
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_OPEN) {
MG_INFO(("%lu CREATED", c->id));
// c->is_hexdumping = 1;
} else if (ev == MG_EV_CONNECT) {
if (mg_url_is_ssl(s_url)) {
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
.name = mg_url_host(s_url)};
mg_tls_init(c, &opts);
}
} else if (ev == MG_EV_ERROR) {
// On error, log error message
MG_ERROR(("%lu ERROR %s", c->id, (char *) ev_data));
} else if (ev == MG_EV_MQTT_OPEN) {
// MQTT connect is successful
struct mg_str subt = mg_str(s_sub_topic);
struct mg_str pubt = mg_str(s_pub_topic), data = mg_str("hello");
MG_INFO(("%lu CONNECTED to %s", c->id, s_url));
struct mg_mqtt_opts sub_opts;
memset(&sub_opts, 0, sizeof(sub_opts));
sub_opts.topic = subt;
sub_opts.qos = s_qos;
mg_mqtt_sub(c, &sub_opts);
MG_INFO(("%lu SUBSCRIBED to %.*s", c->id, (int) subt.len, subt.buf));
struct mg_mqtt_opts pub_opts;
memset(&pub_opts, 0, sizeof(pub_opts));
pub_opts.topic = pubt;
pub_opts.message = data;
pub_opts.qos = s_qos, pub_opts.retain = false;
mg_mqtt_pub(c, &pub_opts);
MG_INFO(("%lu PUBLISHED %.*s -> %.*s", c->id, (int) data.len, data.buf,
(int) pubt.len, pubt.buf));
} else if (ev == MG_EV_MQTT_MSG) {
// When we get echo response, print it
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
MG_INFO(("%lu RECEIVED %.*s <- %.*s", c->id, (int) mm->data.len,
mm->data.buf, (int) mm->topic.len, mm->topic.buf));
} else if (ev == MG_EV_CLOSE) {
MG_INFO(("%lu CLOSED", c->id));
s_conn = NULL; // Mark that we're closed
}
}
// Timer function - recreate client connection if it is closed
static void timer_fn(void *arg) {
struct mg_mgr *mgr = (struct mg_mgr *) arg;
struct mg_mqtt_opts opts = {.clean = true,
.qos = s_qos,
.topic = mg_str(s_pub_topic),
.version = 4,
.message = mg_str("bye")};
if (s_conn == NULL) s_conn = mg_mqtt_connect(mgr, s_url, &opts, fn, NULL);
}
int main(int argc, char *argv[]) {
struct mg_mgr mgr;
int i;
// Parse command-line flags
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-u") == 0 && argv[i + 1] != NULL) {
s_url = argv[++i];
} else if (strcmp(argv[i], "-p") == 0 && argv[i + 1] != NULL) {
s_pub_topic = argv[++i];
} else if (strcmp(argv[i], "-s") == 0 && argv[i + 1] != NULL) {
s_sub_topic = argv[++i];
} else if (strcmp(argv[i], "-v") == 0 && argv[i + 1] != NULL) {
mg_log_set(atoi(argv[++i]));
} else {
MG_ERROR(("Unknown option: %s. Usage:", argv[i]));
MG_ERROR(
("%s [-u mqtts://SERVER:PORT] [-p PUB_TOPIC] [-s SUB_TOPIC] "
"[-v DEBUG_LEVEL]",
argv[0], argv[i]));
return 1;
}
}
signal(SIGINT, signal_handler); // Setup signal handlers - exist event
signal(SIGTERM, signal_handler); // manager loop on SIGINT and SIGTERM
mg_mgr_init(&mgr);
mg_timer_add(&mgr, 3000, MG_TIMER_REPEAT | MG_TIMER_RUN_NOW, timer_fn, &mgr);
while (s_signo == 0) mg_mgr_poll(&mgr, 1000); // Event loop, 1s timeout
mg_mgr_free(&mgr); // Finished, cleanup
return 0;
}
+1
View File
@@ -0,0 +1 @@
../../../mongoose.c
+1
View File
@@ -0,0 +1 @@
../../../mongoose.h
+1
View File
@@ -0,0 +1 @@
../../http/http-client/packed_fs.c
@@ -0,0 +1,32 @@
PROG ?= example # Program we are building
DELETE = rm -rf # Command to remove files
OUT ?= -o $(PROG) # Compiler argument for output file
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
CFLAGS = -W -Wall -Wextra -g -I. # Build options
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
PROG ?= example.exe # Use .exe suffix for the binary
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
OUT ?= -o $(PROG) # Build output
MAKE += WINDOWS=1 CC=$(CC)
endif
all: $(PROG) # Default target. Build and run program
$(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) # Build program from sources
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
clean: # Cleanup. Delete built program and all build artifacts
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
mbedtls: # Pull and build mbedTLS library
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
$(MAKE) -C mbedtls/library
@@ -0,0 +1 @@
See detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-over-ws-client/
+106
View File
@@ -0,0 +1,106 @@
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
// Example MQTT client. It performs the following steps:
// 1. Connects to the MQTT server specified by `s_url` variable
// 2. When connected, subscribes to the topic `s_topic`
// 3. Publishes message `hello` to the `s_topic`
// 4. Receives that message back from the subscribed topic and exits
//
// To enable SSL/TLS, see https://mongoose.ws/tutorials/tls/#how-to-build
#include "mongoose.h"
static const char *s_url =
#if MG_TLS
"wss://broker.hivemq.com:8884/mqtt";
#else
"ws://broker.hivemq.com:8000/mqtt";
#endif
static const char *s_topic = "mg/test";
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_ERROR) {
// On error, log error message
MG_ERROR(("%p %s", c->fd, (char *) ev_data));
} else if (ev == MG_EV_CONNECT) {
if (mg_url_is_ssl(s_url)) {
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
.name = mg_url_host(s_url)};
mg_tls_init(c, &opts);
}
} else if (ev == MG_EV_WS_OPEN) {
// WS connection established. Perform MQTT login
MG_INFO(("Connected to WS. Logging in to MQTT..."));
struct mg_mqtt_opts opts = {
.qos = 1, .topic = mg_str(s_topic), .message = mg_str("goodbye")};
size_t len = c->send.len;
mg_mqtt_login(c, &opts);
mg_ws_wrap(c, c->send.len - len, WEBSOCKET_OP_BINARY);
c->is_hexdumping = 1;
} else if (ev == MG_EV_WS_MSG) {
struct mg_mqtt_message mm;
struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
uint8_t version = c->is_mqtt5 ? 5 : 4;
MG_INFO(("GOT %d bytes WS msg", (int) wm->data.len));
while ((mg_mqtt_parse((uint8_t *) wm->data.buf, wm->data.len, version,
&mm)) == MQTT_OK) {
switch (mm.cmd) {
case MQTT_CMD_CONNACK:
mg_call(c, MG_EV_MQTT_OPEN, &mm.ack);
if (mm.ack == 0) {
struct mg_str topic = mg_str(s_topic), data = mg_str("hello");
size_t len = c->send.len;
MG_INFO(("CONNECTED to %s", s_url));
struct mg_mqtt_opts sub_opts;
memset(&sub_opts, 0, sizeof(sub_opts));
sub_opts.topic = topic;
sub_opts.qos = 1;
mg_mqtt_sub(c, &sub_opts);
len = mg_ws_wrap(c, c->send.len - len, WEBSOCKET_OP_BINARY);
MG_INFO(("SUBSCRIBED to %.*s", (int) topic.len, topic.buf));
struct mg_mqtt_opts pub_opts;
memset(&pub_opts, 0, sizeof(pub_opts));
pub_opts.topic = topic;
pub_opts.message = data;
pub_opts.qos = 1, pub_opts.retain = false;
mg_mqtt_pub(c, &pub_opts);
MG_INFO(("PUBLISHED %.*s -> %.*s", (int) data.len, data.buf,
(int) topic.len, topic.buf));
len = mg_ws_wrap(c, c->send.len - len, WEBSOCKET_OP_BINARY);
} else {
MG_ERROR(("%lu MQTT auth failed, code %d", c->id, mm.ack));
c->is_draining = 1;
}
break;
case MQTT_CMD_PUBLISH: {
MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) mm.topic.len,
mm.topic.buf, (int) mm.data.len, mm.data.buf));
MG_INFO(("RECEIVED %.*s <- %.*s", (int) mm.data.len, mm.data.buf,
(int) mm.topic.len, mm.topic.buf));
c->is_draining = 1;
break;
}
}
wm->data.buf += mm.dgram.len;
wm->data.len -= mm.dgram.len;
}
}
if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE) {
*(bool *) c->fn_data = true; // Signal that we're done
}
}
int main(void) {
struct mg_mgr mgr; // Event manager
bool done = false; // Event handler flips it to true when done
mg_mgr_init(&mgr); // Initialise event manager
mg_log_set(MG_LL_DEBUG); // Set log level
mg_ws_connect(&mgr, s_url, fn, &done, "%s", // Create client connection
"Sec-Websocket-Protocol: mqtt\r\n"); // Request MQTT protocol
while (done == false) mg_mgr_poll(&mgr, 1000); // Event loop
mg_mgr_free(&mgr); // Finished, cleanup
return 0;
}
+1
View File
@@ -0,0 +1 @@
../../../mongoose.c
+1
View File
@@ -0,0 +1 @@
../../../mongoose.h
+1
View File
@@ -0,0 +1 @@
../../http/http-client/packed_fs.c
+25
View File
@@ -0,0 +1,25 @@
PROG ?= example # Program we are building
DELETE = rm -rf # Command to remove files
OUT ?= -o $(PROG) # Compiler argument for output file
SOURCES = main.c mongoose.c # Source code files
CFLAGS = -W -Wall -Wextra -g -I. # Build options
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
PROG ?= example.exe # Use .exe suffix for the binary
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
OUT ?= -o $(PROG) # Build output
endif
all: $(PROG) # Default target. Build and run program
$(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) # Build program from sources
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
clean: # Cleanup. Delete built program and all build artifacts
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM
+1
View File
@@ -0,0 +1 @@
See detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-server/
+146
View File
@@ -0,0 +1,146 @@
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
// Example MQTT server. Usage:
// 1. Start this server, type `make`
// 2. Install mosquitto MQTT client
// 3. In one terminal, run: mosquitto_sub -h localhost -t foo -t bar
// 4. In another, run: mosquitto_pub -h localhost -t foo -m hi
#include "mongoose.h"
static const char *s_listen_on = "mqtt://0.0.0.0:1883";
// A list of subscription, held in memory
struct sub {
struct sub *next;
struct mg_connection *c;
struct mg_str topic;
uint8_t qos;
};
static struct sub *s_subs = NULL;
// Handle interrupts, like Ctrl-C
static int s_signo;
static void signal_handler(int signo) {
s_signo = signo;
}
static size_t mg_mqtt_next_topic(struct mg_mqtt_message *msg,
struct mg_str *topic, uint8_t *qos,
size_t pos) {
unsigned char *buf = (unsigned char *) msg->dgram.buf + pos;
size_t new_pos;
if (pos >= msg->dgram.len) return 0;
topic->len = (size_t) (((unsigned) buf[0]) << 8 | buf[1]);
topic->buf = (char *) buf + 2;
new_pos = pos + 2 + topic->len + (qos == NULL ? 0 : 1);
if ((size_t) new_pos > msg->dgram.len) return 0;
if (qos != NULL) *qos = buf[2 + topic->len];
return new_pos;
}
size_t mg_mqtt_next_sub(struct mg_mqtt_message *msg, struct mg_str *topic,
uint8_t *qos, size_t pos) {
uint8_t tmp;
return mg_mqtt_next_topic(msg, topic, qos == NULL ? &tmp : qos, pos);
}
size_t mg_mqtt_next_unsub(struct mg_mqtt_message *msg, struct mg_str *topic,
size_t pos) {
return mg_mqtt_next_topic(msg, topic, NULL, pos);
}
// Event handler function
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_MQTT_CMD) {
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
MG_DEBUG(("cmd %d qos %d", mm->cmd, mm->qos));
switch (mm->cmd) {
case MQTT_CMD_CONNECT: {
// Client connects
if (mm->dgram.len < 9) {
mg_error(c, "Malformed MQTT frame");
} else if (mm->dgram.buf[8] != 4) {
mg_error(c, "Unsupported MQTT version %d", mm->dgram.buf[8]);
} else {
uint8_t response[] = {0, 0};
mg_mqtt_send_header(c, MQTT_CMD_CONNACK, 0, sizeof(response));
mg_send(c, response, sizeof(response));
}
break;
}
case MQTT_CMD_SUBSCRIBE: {
// Client subscribes
size_t pos = 4; // Initial topic offset, where ID ends
uint8_t qos, resp[256];
struct mg_str topic;
int num_topics = 0;
while ((pos = mg_mqtt_next_sub(mm, &topic, &qos, pos)) > 0) {
struct sub *sub = calloc(1, sizeof(*sub));
sub->c = c;
sub->topic = mg_strdup(topic);
sub->qos = qos;
LIST_ADD_HEAD(struct sub, &s_subs, sub);
MG_INFO(
("SUB %p [%.*s]", c->fd, (int) sub->topic.len, sub->topic.buf));
// Change '+' to '*' for topic matching using mg_match
for (size_t i = 0; i < sub->topic.len; i++) {
if (sub->topic.buf[i] == '+') ((char *) sub->topic.buf)[i] = '*';
}
resp[num_topics++] = qos;
}
mg_mqtt_send_header(c, MQTT_CMD_SUBACK, 0, num_topics + 2);
uint16_t id = mg_htons(mm->id);
mg_send(c, &id, 2);
mg_send(c, resp, num_topics);
break;
}
case MQTT_CMD_PUBLISH: {
// Client published message. Push to all subscribed channels
MG_INFO(("PUB %p [%.*s] -> [%.*s]", c->fd, (int) mm->data.len,
mm->data.buf, (int) mm->topic.len, mm->topic.buf));
for (struct sub *sub = s_subs; sub != NULL; sub = sub->next) {
if (mg_match(mm->topic, sub->topic, NULL)) {
struct mg_mqtt_opts pub_opts;
memset(&pub_opts, 0, sizeof(pub_opts));
pub_opts.topic = mm->topic;
pub_opts.message = mm->data;
pub_opts.qos = 1, pub_opts.retain = false;
mg_mqtt_pub(sub->c, &pub_opts);
}
}
break;
}
case MQTT_CMD_PINGREQ: {
// The server must send a PINGRESP packet in response to a PINGREQ packet [MQTT-3.12.4-1]
MG_INFO(("PINGREQ %p -> PINGRESP", c->fd));
mg_mqtt_send_header(c, MQTT_CMD_PINGRESP, 0, 0);
break;
}
}
} else if (ev == MG_EV_ACCEPT) {
// c->is_hexdumping = 1;
} else if (ev == MG_EV_CLOSE) {
// Client disconnects. Remove from the subscription list
for (struct sub *next, *sub = s_subs; sub != NULL; sub = next) {
next = sub->next;
if (c != sub->c) continue;
MG_INFO(("UNSUB %p [%.*s]", c->fd, (int) sub->topic.len, sub->topic.buf));
LIST_DELETE(struct sub, &s_subs, sub);
}
}
}
int main(void) {
struct mg_mgr mgr; // Event manager
signal(SIGINT, signal_handler); // Setup signal handlers - exist event
signal(SIGTERM, signal_handler); // manager loop on SIGINT and SIGTERM
mg_mgr_init(&mgr); // Initialise event manager
MG_INFO(("Starting on %s", s_listen_on)); // Inform that we're starting
mg_mqtt_listen(&mgr, s_listen_on, fn, NULL); // Create MQTT listener
while (s_signo == 0) mg_mgr_poll(&mgr, 1000); // Event loop, 1s timeout
mg_mgr_free(&mgr); // Cleanup
return 0;
}
+1
View File
@@ -0,0 +1 @@
../../../mongoose.c
+1
View File
@@ -0,0 +1 @@
../../../mongoose.h