266029f51ee17b87f3d36dc58d66c17bbcfacbbd
[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 tasklength
33 t->tasklength = read16();
34 debug("task interval: %d, length: %d\n", t->interval, t->tasklength);
35
36 if(mem_task+t->tasklength > mem_sds){
37 die("Out of memory... Not enough to allocate bytes");
38 }
39
40 mem_task += sizeof(struct task);
41 t->bc = mem_task;
42 mem_task += t->tasklength;
43
44 //Read task bytecode
45 for(i = 0; i<t->tasklength; i++){
46 t->bc[i] = read_byte();
47 }
48
49 //Return the task number for later removal
50 debug("Received a task of length %d", t->tasklength);
51 t->lastrun = 0L;
52 t->taskid = taskid++;
53 t->value = 0;
54
55 write_byte('t');
56 write16(t->taskid);
57 write16(mem_free());
58 write_byte('\n');
59 debug("free memory: %lu\n", mem_free());
60 }
61
62 bool is_interrupt_task(struct task *t)
63 {
64 return t->interval & (2 <<14);
65 }
66
67 bool had_interrupt(struct task* t)
68 {
69 //Not implemented yet...
70 return false;
71 (void)t;
72 }
73
74 struct task *task_head(void)
75 {
76 return mem_task == mem_bottom ? NULL : (struct task *)mem_bottom;
77 }
78
79 struct task *task_next(struct task *t)
80 {
81 uint8_t *next = (uint8_t *)t + sizeof(struct task) + t->tasklength;
82 return next >= mem_task ? NULL : (struct task *)next;
83 }
84
85 void task_delete(uint8_t c)
86 {
87 debug("Going to delete task: %i", c);
88 struct task *t = task_head();
89 while(t != NULL){
90 if(t->taskid == c){
91 break;
92 }
93 t = task_next(t);
94 }
95 //Write acknowledgement
96 write_byte('d');
97 write16(c);
98 write_byte('\n');
99
100 if(t != NULL){
101 //We found the task, now we move everything from the end of the task up
102 //to the spacepointer right
103 uint8_t *start = (uint8_t *)t;
104 uint8_t *end = start + sizeof(struct task) + t->tasklength;
105 debug("Moving %lu bytes\n", mem_task-end);
106 for(int i = 0; i<mem_task-end; i++){
107 start[i] = end[i];
108 }
109
110 //Decrement the spacepointer
111 mem_task -= end-start;
112 }
113 }