Create IoT project and connect to MQTT server
This commit is contained in:
parent
b194766464
commit
8c811729b1
3
iot/.gitignore
vendored
Normal file
3
iot/.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
a.out
|
||||
config.h
|
||||
|
3
iot/Makefile
Normal file
3
iot/Makefile
Normal file
@ -0,0 +1,3 @@
|
||||
all: main.c
|
||||
$(CC) -lmosquitto main.c
|
||||
|
5
iot/config.example.h
Normal file
5
iot/config.example.h
Normal file
@ -0,0 +1,5 @@
|
||||
#define MQTT_IP "127.0.0.1"
|
||||
#define MQTT_PORT 1883
|
||||
#define MQTT_USER "user"
|
||||
#define MQTT_PASSWORD "password"
|
||||
|
44
iot/main.c
Normal file
44
iot/main.c
Normal file
@ -0,0 +1,44 @@
|
||||
#include <mosquitto.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "config.h"
|
||||
|
||||
void on_connect(struct mosquitto *client, void *obj, int rc)
|
||||
{
|
||||
if (rc != 0) {
|
||||
fprintf(stderr, "%s\n", mosquitto_connack_string(rc));
|
||||
return;
|
||||
}
|
||||
|
||||
puts("Connected to " MQTT_IP);
|
||||
}
|
||||
|
||||
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
|
||||
{
|
||||
printf("Received message on topic %s\n", message->topic);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int version[3];
|
||||
mosquitto_lib_init();
|
||||
mosquitto_lib_version(&version[0], &version[1], &version[2]);
|
||||
printf("Using mosquitto library version %i.%i.%i\n", version[0], version[1], version[2]);
|
||||
|
||||
struct mosquitto *mosq = mosquitto_new(NULL, true, NULL);
|
||||
|
||||
mosquitto_connect_callback_set(mosq, on_connect);
|
||||
mosquitto_message_callback_set(mosq, on_message);
|
||||
|
||||
mosquitto_username_pw_set(mosq, MQTT_USER, MQTT_PASSWORD);
|
||||
mosquitto_connect(mosq, MQTT_IP, MQTT_PORT, 60);
|
||||
|
||||
mosquitto_loop_forever(mosq, -1, 1);
|
||||
|
||||
mosquitto_destroy(mosq);
|
||||
mosquitto_lib_cleanup();
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user