2570017c8738ef35cd6552a0d9a7f50736b3dd94
[mTask.git] / client / sds.c
1 #include <stdlib.h>
2 #include <string.h>
3
4 #include "interface.h"
5 #include "sds.h"
6 #include "mem.h"
7
8 extern uint8_t *mem_top, *mem_bottom, *mem_task, *mem_sds;
9
10 struct sds *sds_head(void)
11 {
12 return mem_sds == mem_top ? NULL
13 : (struct sds *)(mem_top-sizeof(struct sds));
14 }
15
16 struct sds *sds_next(struct sds *s)
17 {
18 uint8_t *next = (uint8_t *)s - sizeof(struct sds);
19 return next < mem_sds ? NULL : (struct sds *)next;
20 }
21
22 struct sds *sds_get(uint8_t id)
23 {
24 struct sds *s = sds_head();
25 while(s != NULL){
26 if(s->id == id){
27 break;
28 }
29 s = sds_next(s);
30 }
31 return s;
32 }
33
34 void sds_register(void)
35 {
36 debug("free memory: %lu", mem_free());
37
38 if(mem_sds-sizeof(struct sds) < mem_task){
39 die("Out of memory... Not enough to allocate sds struct");
40 }
41
42 struct sds *s = (struct sds *)(mem_sds-sizeof(struct sds));
43
44 //Read identifier
45 s->id = read16();
46
47 //Read value
48 s->type = read_byte();
49 s->value = read16();
50
51 write_byte('s');
52 write16(s->id);
53 write_byte('\n');
54
55 mem_sds -= sizeof(struct sds);
56 }
57
58 void sds_delete(uint8_t c)
59 {
60 struct sds *s = sds_get(c);
61
62 if(s != NULL){
63 //We found the sds, now we move verything from the end of the sds up to
64 //the pointer to the right
65 uint8_t *end = (uint8_t *)s;
66 uint8_t *start = end + sizeof(struct sds) - 1;
67 for(int i = 0; i<end-mem_sds; i++){
68 *(start - i) = *(end - i-1);
69 }
70 mem_sds += start-end+1;
71 }
72 }
73
74 bool sds_update(uint8_t id)
75 {
76 //Read identifier
77 struct sds *s = sds_get(id);
78 if(s != NULL){
79 s->value = read16();
80 debug("Received sds update %d: %d", s->id, s->value);
81 write_byte('u');
82 write16(s->id);
83 write_byte('\n');
84 return true;
85 }
86 return false;
87 }
88
89 void sds_publish(int id)
90 {
91 struct sds *s = sds_get(id);
92 if(s != NULL){
93 debug("Publish %d=%d", s->id, s->value);
94 write_byte('p');
95 write16(s->id);
96 write_byte(s->type);
97
98 switch(s->type){
99 //Long
100 case 'l':
101 //Int
102 case 'i':
103 write16(s->value);
104 break;
105 case 'b': //Bool
106 case 'c': //Character
107 case 'B': //Button
108 case 'L': //UserLED
109 write_byte(s->value);
110 break;
111 }
112 write_byte('\n');
113 return;
114
115 } else {
116 debug("SDS identifier unknown: %d", id);
117 die("");
118 }
119 }
120
121 int sds_fetch(int id)
122 {
123 struct sds *s = sds_get(id);
124 if(s != NULL){
125 return s->value;
126 }
127 debug("SDS identifier unknown: %d", id);
128 die("");
129 return 0;
130 }
131
132 void sds_store(int id, int val)
133 {
134 struct sds *s = sds_get(id);
135 if(s != NULL){
136 s->value = val;
137 } else {
138 debug("SDS identifier unknown: %d", id);
139 die("");
140 }
141 }