diff options
Diffstat (limited to 'tools/pub.c')
| -rw-r--r-- | tools/pub.c | 81 |
1 files changed, 55 insertions, 26 deletions
diff --git a/tools/pub.c b/tools/pub.c index 781509c..f2107ae 100644 --- a/tools/pub.c +++ b/tools/pub.c @@ -2,7 +2,7 @@ #include <stdio.h> #include "mqtt.h" -#include "getopt.h" +#include "optparse.h" struct options { @@ -10,6 +10,7 @@ struct options int retain; const char *topic; const char *message; + const char *client_id; }; void onConnect(MqttClient *client, MqttConnectionStatus status, @@ -37,52 +38,80 @@ void usage(const char *prog) exit(1); } -int main(int argc, char **argv) +static void parse_args(struct options *options, int argc, char **argv) { - MqttClient *client; - const char *opt; - struct options options; + int option; - options.qos = 0; - options.retain = 0; - options.topic = "my/topic"; - options.message = "hello, world!"; + struct optparse_long longopts[] = + { + { "qos", 'q', OPTPARSE_REQUIRED }, + { "topic", 't', OPTPARSE_REQUIRED }, + { "message", 'm', OPTPARSE_REQUIRED }, + { "id", 'i', OPTPARSE_REQUIRED }, + { "retain", 'r', OPTPARSE_NONE }, + { "help", 'h', OPTPARSE_NONE }, + { NULL } + }; + + struct optparse parser; + + optparse_init(&parser, argv); - while ((opt = GETOPT(argc, argv)) != NULL) + while ((option = optparse_long(&parser, longopts, NULL)) != -1) { - GETOPT_SWITCH(opt) + switch (option) { - GETOPT_OPTARG("--qos"): - options.qos = strtol(optarg, NULL, 10); - if (options.qos < 0 || options.qos > 2) + case 'q': + options->qos = strtol(parser.optarg, NULL, 10); + if (options->qos < 0 || options->qos > 2) { - fprintf(stderr, "invalid qos: %s\n", optarg); - return 1; + fprintf(stderr, "invalid qos: %s\n", parser.optarg); + exit(1); } break; - GETOPT_OPT("--retain"): - options.retain = 1; + case 't': + options->topic = parser.optarg; break; - GETOPT_OPTARG("--topic"): - options.topic = optarg; + case 'm': + options->message = parser.optarg; break; - GETOPT_OPTARG("--message"): - options.message = optarg; + case 'r': + options->retain = 1; break; - GETOPT_MISSING_ARG: - fprintf(stderr, "missing argument to: %s\n", opt); + case 'i': + options->client_id = parser.optarg; + break; + + case 'h': + usage(argv[0]); + break; - GETOPT_DEFAULT: + case '?': + fprintf(stderr, "%s: %s\n", argv[0], parser.errmsg); usage(argv[0]); break; } } +} + +int main(int argc, char **argv) +{ + MqttClient *client; + struct options options; + + options.qos = 0; + options.retain = 0; + options.topic = "my/topic"; + options.message = "hello, world!"; + options.client_id = NULL; + + parse_args(&options, argc, argv); - client = MqttClientNew(NULL, 1); + client = MqttClientNew(options.client_id, 1); MqttClientSetOnConnect(client, onConnect); MqttClientSetOnPublish(client, onPublish); |
