aboutsummaryrefslogtreecommitdiffstats
path: root/fw/table.c
blob: 41c1bc45c296d759e3152deab26bb02dc9ba41de (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdbool.h>
#include <stdint.h>

#include "types.h"
#include "can.h"
#include "eeprom.h"

#include "table.h"

Status
tabWrite(const Table *tab, U8 k, U16 key, U16 val) {
	if (k >= TAB_ROWS) {
		return FAIL;
	}

	U16 addr = tab->offset + k*TAB_ROW_SIZE;
	U8 row[4u] = {
		(key>>0u)&0xFF, (key>>8u)&0xFF,
		(val>>0u)&0xFF, (val>>8u)&0xFF};
	return eepromWrite(addr, row, sizeof(row));
}

Status
tabRead(const Table *tab, U8 k, U16 *key, U16 *val) {
	U16 addr;
	U8 row[4u];
	Status status;

	if (k >= TAB_ROWS) {
		return FAIL;
	}

	addr = tab->offset + k*TAB_ROW_SIZE;
	status = eepromRead(addr, row, sizeof(row));
	*key = ((U16)row[0u]<<0u) | ((U16)row[1u]<<8u);
	*val = ((U16)row[2u]<<0u) | ((U16)row[3u]<<8u);
	return status;
}

Status
tabLookup(const Table *tab, U16 key, U16 *val) {
	U8 k;
	U16 tkey, tval1, tval2;
	Status status;

	// Search for key
	for (k = 0u; (k < TAB_ROWS-1u); k++) {
		status = tabRead(tab, k, &tkey, &tval1);
		if (status != OK) {
			return FAIL;
		}
		if (key == tkey) { // found exact key
			*val = tval1; 
			return OK;
		} else if (key > tkey) { // interpolate
			status = tabRead(tab, k+1u, &tkey, &tval2);
			if (status != OK) {
				return FAIL;
			}
			*val = (tval1 + tval2) / 2u; 
			return OK;
		} else { // less
			// continue
		}
	}

	// Reached last row
	*val = tval1; // last value in table

	return OK;
}