diff options
| author | Oskari Timperi <oskari.timperi@iki.fi> | 2017-02-12 17:12:52 +0200 |
|---|---|---|
| committer | Oskari Timperi <oskari.timperi@iki.fi> | 2017-02-12 17:12:52 +0200 |
| commit | cd2faf64b2e995dee42e7e3911325d372c6604a1 (patch) | |
| tree | e0ab608cdd7005e759b570a5a4ec2031191bafb5 /tools/pub.c | |
| parent | 54f78d73ec378fe1d62a696edeb2ddc5a59e2669 (diff) | |
| download | mqtt-cd2faf64b2e995dee42e7e3911325d372c6604a1.tar.gz mqtt-cd2faf64b2e995dee42e7e3911325d372c6604a1.zip | |
Add all the stuff
Diffstat (limited to 'tools/pub.c')
| -rw-r--r-- | tools/pub.c | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/tools/pub.c b/tools/pub.c new file mode 100644 index 0000000..9b5af82 --- /dev/null +++ b/tools/pub.c @@ -0,0 +1,96 @@ +#include <stdlib.h> +#include <stdio.h> + +#include "mqtt.h" +#include "getopt.h" + +struct options +{ + int qos; + int retain; + const char *topic; + const char *message; +}; + +void onConnect(MqttClient *client, MqttConnectionStatus status, + int sessionPresent) +{ + struct options *options = (struct options *) MqttClientGetUserData(client); + (void) client; + printf("onConnect rv=%d sessionPresent=%d\n", status, sessionPresent); + MqttClientPublishCString(client, options->qos, options->retain, + options->topic, options->message); + if (options->qos == 0) + MqttClientDisconnect(client); +} + +void onPublish(MqttClient *client, int id) +{ + printf("onPublish id=%d\n", id); + MqttClientDisconnect(client); +} + +void usage(const char *prog) +{ + fprintf(stderr, "%s [--qos QOS] [--retain] [--topic TOPIC] [--message MESSAGE]\n", + prog); + exit(1); +} + +int main(int argc, char **argv) +{ + MqttClient *client; + const char *opt; + struct options options; + + options.qos = 0; + options.retain = 0; + options.topic = "my/topic"; + options.message = "hello, world!"; + + while ((opt = GETOPT(argc, argv)) != NULL) + { + GETOPT_SWITCH(opt) + { + GETOPT_OPTARG("--qos"): + options.qos = strtol(optarg, NULL, 10); + if (options.qos < 0 || options.qos > 2) + { + fprintf(stderr, "invalid qos: %s\n", optarg); + return 1; + } + break; + + GETOPT_OPT("--retain"): + options.retain = 1; + break; + + GETOPT_OPTARG("--topic"): + options.topic = optarg; + break; + + GETOPT_OPTARG("--message"): + options.message = optarg; + break; + + GETOPT_MISSING_ARG: + fprintf(stderr, "missing argument to: %s\n", opt); + + GETOPT_DEFAULT: + usage(argv[0]); + break; + } + } + + client = MqttClientNew(NULL, 1); + + MqttClientSetOnConnect(client, onConnect); + MqttClientSetOnPublish(client, onPublish); + MqttClientSetUserData(client, &options); + + MqttClientConnect(client, "test.mosquitto.org", 1883, 60); + + MqttClientRun(client); + + return 0; +} |
