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