~gpanders/iboot

dc8e8b56cad9266864f5c674b8f1080172536000 — Greg Anders 3 months ago 82ec4a6
Refactor code into smaller functions
2 files changed, 46 insertions(+), 20 deletions(-)

M Makefile
M netpower.c
M Makefile => Makefile +1 -1
@@ 1,4 1,4 @@
CFLAGS := -Wall -Wpedantic
CFLAGS := -Wall -Wpedantic -Os

netpower: netpower.c config.h
	$(CC) $(CFLAGS) -o $@ $<

M netpower.c => netpower.c +45 -19
@@ 1,4 1,5 @@
#include <netdb.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


@@ 8,20 9,12 @@

#include "config.h"

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

	char action = argv[1][0];

	if (action != 'n' && action != 'f' && action != 'c' && action != 'q') {
		fprintf(stderr, "Invalid action: %c\n", action);
		exit(EXIT_FAILURE);
	}
/* 4 extra bytes for the two escape characters (), the action character, and
 * the carriage return (\r) */
static const size_t BUF_SIZE = sizeof(PASSWORD) + 4;

int create_socket()
{
	int sockfd;
	struct addrinfo *result, *rp;
	struct addrinfo hints = {


@@ 57,23 50,56 @@ int main(int argc, char *argv[])

	freeaddrinfo(result);

	char buf[16];
	sprintf(buf, "%s%c\r", PASSWORD, action);
	return sockfd;
}

	int buflen = strnlen(buf, 16);
	if (write(sockfd, buf, buflen) != buflen) {
void send_command(int sockfd, char action)
{
	char buf[BUF_SIZE];
	sprintf(buf, "%s%c\r", PASSWORD, action);
	if (write(sockfd, buf, BUF_SIZE) != BUF_SIZE) {
		fprintf(stderr, "partial/failed write\n");
		exit(EXIT_FAILURE);
	}

	memset(buf, 0, 16);
	ssize_t nread = read(sockfd, buf, 16);
	memset(buf, 0, BUF_SIZE);
	ssize_t nread = read(sockfd, buf, BUF_SIZE);
	if (nread == -1) {
		perror("read");
		exit(EXIT_FAILURE);
	}

	printf("%s\n", buf);
}

int is_valid_action(char action)
{
	switch (action) {
	case 'n': /* ON */
	case 'f': /* OFF */
	case 'c': /* CYCLE */
	case 'q': /* QUERY */
		return 1;
	default:
		return 0;
	}
}

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

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

	int sockfd = create_socket();
	send_command(sockfd, action);

	exit(EXIT_SUCCESS);
}