123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- #include "mainclass.hh"
- #include <iostream>
- #include <libgen.h>
- #include <sysexits.h>
- #include <climits>
- #include <getopt.h>
-
- MainClass::MainClass(int argc, char* argv[])
- : argc_(argc)
- , argv_(argv)
- {
- }
-
- int MainClass::usage()
- {
- std::cerr << "Usage: " << basename(argv_[0]) << std::endl <<
- " [--device DEVICE|--device=DEVICE|-e DEVICE]" << std::endl <<
- " [--up OUTPUT|--up=OUTPUT|-u OUTPUT]" << std::endl <<
- " [--down OUTPUT|--down=OUPUT|-d OUTPUT]" << std::endl <<
- " [--sleep MS|--sleep=MS|-s MS]" << std::endl <<
- " [--help|-h]" << std::endl;
- std::cerr << std::endl << "Controls the output pins of a PiFace digital IO."
- << std::endl << std::endl;
- std::cerr << "--device \tSwitch to the provided device."
- << std::endl << "--up \t\tEnable the provided ouput pin."
- << std::endl << "--down \t\tDisable the provided output pin."
- << std::endl << "--sleep \tSleep for the provided amount of milliseconds."
- << std::endl << "--help \t\tDisplay this message."
- << std::endl << std::endl;
- std::cerr << "OUTPUT \t: The output pin to enable/disable. 0 <= OUTPUT <= 7."
- << std::endl << "MS \t: The number of milliseconds to sleep. 0 <= MS <= "
- << UINT_MAX << "."
- << std::endl << "DEVICE \t: The device number. Default is 0. "
- "0 <= DEVICE <= 4." << std::endl;
- return EX_USAGE;
- }
-
- bool MainClass::bad_value_()
- {
- extern int optind;
- extern char* optarg;
- std::cerr << "Bad value " << optarg <<
- " for option " << argv_[optind - 2] << std::endl << std::endl;
- return false;
- }
-
- bool MainClass::build_actions_()
- {
- option opts[] = {
- {"device", 1, 0, 'e'},
- {"up", 1, 0, 'u'},
- {"down", 1, 0, 'd'},
- {"sleep", 1, 0, 's'},
- {"help", 0, 0, 'h'},
- {0, 0, 0, 0}
- };
- int opt;
- extern int optind;
- extern char* optarg;
- char* endptr;
- while ((opt = getopt_long(argc_, argv_, "e:u:d:s:h", opts, 0)) != -1)
- {
- if (!optarg)
- return false;
- long int arg = strtol(optarg, &endptr, 10);
- if (arg < 0)
- return bad_value_();
- if (opt == 'e')
- {
- if (arg > 4)
- return bad_value_();
- actions_.push_back([arg]() -> bool
- {
- return true;
- });
- }
- else if (opt == 'u')
- {
- if (arg > 7)
- return bad_value_();
- }
- else if (opt == 'd')
- {
- if (arg > 7)
- return bad_value_();
- }
- else if (opt == 's')
- {
- if (arg > UINT_MAX)
- return bad_value_();
- }
- else
- return false;
- }
- return optind == argc_;
- }
-
- int MainClass::execute()
- {
- if (argc_ <= 2 || !build_actions_())
- return usage();
- for (auto f : actions_)
- if (!f())
- return 1;
- return 0;
- }
|