dynamic task allocation
[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
8 #define TASKSPACE 128
9
10 uint8_t taskspace[TASKSPACE] = {0};
11 uint8_t *spacepointer = (uint8_t *)&taskspace;
12 uint8_t taskid = 0;
13
14 void task_init(void)
15 {
16 memset(&taskspace, 0, TASKSPACE);
17 }
18
19 void task_register(void)
20 {
21 int i;
22 if(spacepointer+sizeof(struct task) > taskspace+TASKSPACE){
23 die("Out of memory... Not enough to allocate taskstruct");
24 }
25
26 //We haven't had a task before, therefore we initialize head
27 struct task *t = (struct task *)spacepointer;
28
29 //Read interval
30 t->interval = read16();
31 debug("interval: %d\n", t->interval);
32
33 //Interrupt task
34 if(is_interrupt_task(t)) {
35
36 }
37
38 //Read tasklength
39 t->tasklength = read16();
40 debug("task interval: %d, length: %d\n", t->interval, t->tasklength);
41
42 if(spacepointer+t->tasklength > taskspace+TASKSPACE){
43 die("Out of memory... Not enough to allocate bytes");
44 }
45
46 spacepointer += sizeof(struct task);
47 t->bc = spacepointer;
48 spacepointer += t->tasklength;
49
50 //Read task bytecode
51 for(i = 0; i<t->tasklength; i++){
52 t->bc[i] = read_byte();
53 }
54
55 //Return the task number for later removal
56 debug("Received a task of length %d", t->tasklength);
57 t->lastrun = 0L;
58 t->taskid = taskid++;
59
60 write_byte('t');
61 write16(t->taskid);
62 write_byte('\n');
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 spacepointer == (uint8_t *)&taskspace ? NULL
80 : (struct task *)&taskspace;
81 }
82
83 struct task *task_next(struct task *t)
84 {
85 uint8_t *next = (uint8_t *)t;
86 next += sizeof(struct task);
87 next += t->tasklength;
88
89 return next >= spacepointer ? NULL : (struct task *)next;
90 }
91
92 void task_delete(uint8_t c)
93 {
94 debug("Going to delete task: %i", c);
95 debug("spacepointer: %p", spacepointer);
96 struct task *t = task_head();
97 while(t != NULL){
98 if(t->taskid == c){
99 break;
100 }
101 t = task_next(t);
102 }
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", spacepointer-end);
110 for(int i = 0; i<spacepointer-end; i++){
111 start[i] = end[i];
112 }
113
114 //Decrement the spacepointer
115 spacepointer -= end-start;
116 }
117 debug("spacepointer: %p", spacepointer);
118 }