~gpanders/iboot

5226a15e0116ff00092e979429413db30653c58d — Greg Anders 3 months ago dc8e8b5
Replace magic strings with constants
1 files changed, 34 insertions(+), 14 deletions(-)

M netpower.c
M netpower.c => netpower.c +34 -14
@@ 13,6 13,18 @@
 * the carriage return (\r) */
static const size_t BUF_SIZE = sizeof(PASSWORD) + 4;

static const char ACTION_ON[]    = "on";
static const char ACTION_OFF[]   = "off";
static const char ACTION_CYCLE[] = "cycle";
static const char ACTION_QUERY[] = "query";

enum action {
	ON      = 'n',
	OFF     = 'f',
	CYCLE   = 'c',
	QUERY   = 'q',
};

int create_socket()
{
	int sockfd;


@@ 53,7 65,7 @@ int create_socket()
	return sockfd;
}

void send_command(int sockfd, char action)
void send_command(int sockfd, enum action action)
{
	char buf[BUF_SIZE];
	sprintf(buf, "%s%c\r", PASSWORD, action);


@@ 72,29 84,37 @@ void send_command(int sockfd, char action)
	printf("%s\n", buf);
}

int is_valid_action(char action)
enum action get_action(const char *action)
{
	switch (action) {
	case 'n': /* ON */
	case 'f': /* OFF */
	case 'c': /* CYCLE */
	case 'q': /* QUERY */
		return 1;
	default:
		return 0;
	if (!strcmp(action, ACTION_ON)) {
		return ON;
	}

	if (!strcmp(action, ACTION_OFF)) {
		return OFF;
	}

	if (!strcmp(action, ACTION_CYCLE)) {
		return CYCLE;
	}

	if (!strcmp(action, ACTION_QUERY)) {
		return QUERY;
	}

	return 0;
}

int main(int argc, char *argv[])
{
	if (argc < 2) {
		fprintf(stderr, "Usage: %s <n|f|c|q>\n", argv[0]);
		fprintf(stderr, "Usage: %s <on|off|cycle|query>\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	char action = argv[1][0];
	if (!is_valid_action(action)) {
		fprintf(stderr, "Invalid action: %c\n", action);
	char action = get_action(argv[1]);
	if (!action) {
		fprintf(stderr, "Invalid action: %s\n", argv[1]);
		exit(EXIT_FAILURE);
	}