further work on return values
[mTask.git] / client / task.c
1 #include <stdlib.h>
2 #include <string.h>
3
4 #include "task.h"
5 #include "spec.h"
6 #include "interface.h"
7 #include "mem.h"
8
9 extern uint8_t *mem_top, *mem_bottom, *mem_task, *mem_sds;
10
11 uint8_t taskid = 0;
12
13 void task_register(void)
14 {
15 debug("free memory: %lu\n", mem_free());
16 int i;
17 if(mem_task+sizeof(struct task) > mem_sds){
18 die("Out of memory... Not enough to allocate taskstruct");
19 }
20
21 struct task *t = (struct task *)mem_task;
22
23 //Read interval
24 t->interval = read16();
25 debug("interval: %d\n", t->interval);
26
27 //Interrupt task
28 if(is_interrupt_task(t)) {
29
30 }
31
32 //Read return type
33 t->type = read_byte();
34
35 //Read tasklength
36 t->tasklength = read16();
37 debug("task interval: %d, length: %d\n", t->interval, t->tasklength);
38
39 if(mem_task+t->tasklength > mem_sds){
40 die("Out of memory... Not enough to allocate bytes");
41 }
42
43 mem_task += sizeof(struct task);
44 t->bc = mem_task;
45 mem_task += t->tasklength;
46
47 //Read task bytecode
48 for(i = 0; i<t->tasklength; i++){
49 t->bc[i] = read_byte();
50 }
51
52 //Return the task number for later removal
53 debug("Received a task of length %d", t->tasklength);
54 t->lastrun = 0L;
55 t->taskid = taskid++;
56 t->value = 0;
57
58 write_byte('t');
59 write16(t->taskid);
60 write16(mem_free());
61 write_byte('\n');
62 debug("free memory: %lu\n", mem_free());
63 }
64
65 bool is_interrupt_task(struct task *t)
66 {
67 return t->interval & (2 <<14);
68 }
69
70 bool had_interrupt(struct task* t)
71 {
72 //Not implemented yet...
73 return false;
74 (void)t;
75 }
76
77 struct task *task_head(void)
78 {
79 return mem_task == mem_bottom ? NULL : (struct task *)mem_bottom;
80 }
81
82 struct task *task_next(struct task *t)
83 {
84 uint8_t *next = (uint8_t *)t + sizeof(struct task) + t->tasklength;
85 return next >= mem_task ? NULL : (struct task *)next;
86 }
87
88 void task_delete(uint8_t c)
89 {
90 debug("Going to delete task: %i", c);
91 struct task *t = task_head();
92 while(t != NULL){
93 if(t->taskid == c){
94 break;
95 }
96 t = task_next(t);
97 }
98 //Write acknowledgement
99 write_byte('d');
100 write16(c);
101 write16(t->value);
102 write_byte('\n');
103
104 if(t != NULL){
105 //We found the task, now we move everything from the end of the task up
106 //to the spacepointer right
107 uint8_t *start = (uint8_t *)t;
108 uint8_t *end = start + sizeof(struct task) + t->tasklength;
109 debug("Moving %lu bytes\n", mem_task-end);
110 for(int i = 0; i<mem_task-end; i++){
111 start[i] = end[i];
112 }
113
114 //Decrement the spacepointer
115 mem_task -= end-start;
116 }
117 }