/*
 * master.c
 *
 *  Created on: 06.12.2018
 *      Author: julian
 */

#include "master.h"
#include "../communication.h"

void on_receive(iface_t * me, byte_t b, void*ptr)
{
	master_t * this = (master_t*)(ptr);

	if (this->msg_byte_counter >= 0) {
		if (this->msg_byte_counter <=8) {
			static uint16_t temp = 0;
			if (this->msg_byte_counter%2) {
				temp |= (b<<7);

				switch(this->msg_byte_counter) {
				case 1:
				case 3:
				case 5:
					this->buffer[this->chain_len].poti[this->msg_byte_counter/2] = temp;
					break;
				case 7:
					this->buffer[this->chain_len].slider = temp;
					break;
				}
			}else {
				temp = b&0x7F;
			}
		} else {
			this->buffer[this->chain_len].button = b&0x01;
		}
	}

	this->msg_byte_counter++;
	if (!(this->msg_byte_counter = (this->msg_byte_counter+1)%SLAVE_MESSAGE_LEN)) {
		this->chain_len++;
	}

	// decode package
	if (IS_EOM(b)) {
		return;
	}

	// keep communication running
	me->write(me, 0x00);
}

void master_init(master_t *master, iface_t * dev)
{
	dev->on_read = on_receive;
	dev->callback_data = master;

	// initialize master values
	*master = struct {
		.iface = dev,
	};
}
