/*
 * slave.c
 *
 * this is a default implementation for a slave
 * it will continously encode its state on request
 */

#include "slave.h"
#include "../communication.h"


// implementation for slave_encode
void slave_encode(iface_t *iface, int16_t s) {
	iface->write(iface, (s>>0)&0x7F);
	iface->write(iface, (s>>7)&0x7F);
}

void slave_on_receive(iface_t * me, byte_t buffer, void *ptr)
{
	slave_t * slave = (slave_t*)ptr;

	if (!IS_EOM(buffer)) {
		me->write(me, buffer);
		return;
	}

	me->write(me, buffer & 0x7F);

	// write state
	// write potis
	for (int i = 0; i < 4; i++)
		slave_encode(me, slave->state.poti[i]);

	// write slider
	slave_encode(me, slave->state.slider);

	me->write(me, 0x80 | (slave->state.button & 0x01));
}

void slave_init(slave_t *slave, iface_t *iface)
{
	iface->on_read = slave_on_receive;
	iface->callback_data = slave;

	slave->iface = iface;
	slave->state = (message_t){};
}

