//
// Created by nano on 4/26/25.
//
#include <stdio.h>
#include <stdlib.h>

#include "utils.h"
#include "communication.h"

int main(int argc, char *argv[]) {
	comm_init_communication(); //initialize communication with zigbee board
	int currpower =1;
	while (1) {
		if (comm_await_data_ready(50)) {
			//await in 50ms increments for data to be ready
			byte *buffer = malloc(sizeof(byte)); //allocate enough space to store incoming data

			if (comm_blocking_read(buffer, 1, 50) == ALL_BYTES) {
				// read data from buffer and continue only if the correct nr of bytes is received

				byte *bits = malloc(sizeof(byte) * 8); //
				byte_to_bit_array(bits, *buffer); // convert the incoming data to
				printf("Data received: "); // an array of bits and print said bits
				for (int i = 7; i>=0; i--) {
					//
					printf("%d", bits[i]); //	 THIS IS JUST TESTING CODE
				} //
				printf("\n"); //
				free(buffer);
				if (bits[7] == 1) {
					free(bits); //exit if the MSB is 1, so that we don't loop infinitely
					break; // again, test code
				}
			}
		}

		if (comm_await_ready_for_tx(50) && comm_output_waiting() == 0) {
			if (currpower==16)
				currpower=1;
			currpower*=2;

			byte *buffer = malloc(sizeof(byte));
			*buffer=currpower;
			if (comm_nonblocking_write(buffer, 1) == ALL_BYTES) {
				printf("SENT BYTE %d \n",*buffer);
			}
			*buffer=0;
			if (comm_nonblocking_write(buffer, 1) == ALL_BYTES) {
				printf("SENT IDLE %d \n",*buffer);
			}
			free(buffer);

		}
	}
	comm_end_communication();
	return 0;
}
