-
Notifications
You must be signed in to change notification settings - Fork 38
/
manchester.c
61 lines (53 loc) · 1.48 KB
/
manchester.c
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
#include "manchester.h"
void manchester_init_encoder(EncoderState *state) {
state->manchester.offset = 2;
}
void manchester_add_raw_byte(EncoderState *state, uint8_t raw) __reentrant {
uint16_t acc = 0;
int i;
for (i=0; i<8; i++) {
acc = (acc << 2) + 2 - (raw >> 7);
raw = raw << 1;
}
state->manchester.output[0] = acc >> 8;
state->manchester.output[1] = acc & 0xff;
state->manchester.offset = 0;
}
uint8_t manchester_next_encoded_byte(EncoderState *state, uint8_t *encoded, bool flush) __reentrant {
if (state->manchester.offset > 1) {
return 0;
}
*encoded = state->manchester.output[state->manchester.offset];
state->manchester.offset++;
return 1;
}
// Manchester decoder funcs
void manchester_init_decoder(DecoderState *state) {
state->manchester.output = 0;
state->manchester.bits_avail = 0;
}
uint8_t manchester_add_encoded_byte(DecoderState *state, uint8_t encoded) __reentrant {
uint8_t acc = 0;
int i;
for (i=6; i>=0; i-=2) {
acc = (acc << 1);
switch((encoded >> i) & 0b11) {
case 0b00:
case 0b11:
return 1; // Encoding error
case 0b01:
acc++;
}
}
state->manchester.output = (state->manchester.output << 4) + acc;
state->manchester.bits_avail += 4;
return 0;
}
uint8_t manchester_next_decoded_byte(DecoderState *state, uint8_t *decoded) __reentrant {
if (state->manchester.bits_avail < 8) {
return 0;
}
*decoded = state->manchester.output;
state->manchester.bits_avail = 0;
return 1;
}