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