diff options
Diffstat (limited to 'tools/sub.c')
| -rw-r--r-- | tools/sub.c | 72 |
1 files changed, 47 insertions, 25 deletions
diff --git a/tools/sub.c b/tools/sub.c index 4489b5c..4937584 100644 --- a/tools/sub.c +++ b/tools/sub.c @@ -2,7 +2,7 @@ #include <stdio.h> #include "mqtt.h" -#include "getopt.h" +#include "optparse.h" struct options { @@ -43,50 +43,72 @@ 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.topic = "$SYS/broker/load/messages/#"; - options.clean = 1; - options.client_id = NULL; + struct optparse_long longopts[] = + { + { "qos", 'q', OPTPARSE_REQUIRED }, + { "topic", 't', OPTPARSE_REQUIRED }, + { "no-clean", 'n', OPTPARSE_NONE }, + { "id", 'i', OPTPARSE_REQUIRED }, + { "help", 'h', OPTPARSE_NONE }, + { NULL } + }; + + struct optparse parser; - while ((opt = GETOPT(argc, argv)) != NULL) + optparse_init(&parser, argv); + + 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_OPTARG("--topic"): - options.topic = optarg; + case 't': + options->topic = parser.optarg; break; - GETOPT_OPT("--no-clean"): - options.clean = 0; + case 'n': + options->clean = 0; break; - GETOPT_OPTARG("--id"): - options.client_id = optarg; + case 'i': + options->client_id = parser.optarg; break; - GETOPT_MISSING_ARG: - fprintf(stderr, "missing argument to: %s\n", opt); + 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.topic = "$SYS/broker/load/messages/#"; + options.clean = 1; + options.client_id = NULL; + + parse_args(&options, argc, argv); client = MqttClientNew(options.client_id, options.clean); |
