e36600dfee838a29e715774cb888e02117a9ad92
[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;
10 extern uint8_t *mem_bottom;
11 extern uint8_t *mem_task;
12 extern uint8_t *mem_sds;
13
14 uint8_t taskid = 0;
15
16 void task_register(void)
17 {
18 debug("free memory: %lu\n", mem_free());
19 int i;
20 if(mem_task+sizeof(struct task) > mem_sds){
21 die("Out of memory... Not enough to allocate taskstruct");
22 }
23
24 struct task *t = (struct task *)mem_task;
25
26 //Read interval
27 t->interval = read16();
28 debug("interval: %d\n", t->interval);
29
30 //Interrupt task
31 if(is_interrupt_task(t)) {
32
33 }
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
57 write_byte('t');
58 write16(t->taskid);
59 write_byte('\n');
60 debug("free memory: %lu\n", mem_free());
61 }
62
63 bool is_interrupt_task(struct task *t)
64 {
65 return t->interval & (2 <<14);
66 }
67
68 bool had_interrupt(struct task* t)
69 {
70 //Not implemented yet...
71 return false;
72 (void)t;
73 }
74
75 struct task *task_head(void)
76 {
77 return mem_task == mem_bottom ? NULL : (struct task *)mem_bottom;
78 }
79
80 struct task *task_next(struct task *t)
81 {
82 uint8_t *next = (uint8_t *)t + sizeof(struct task) + t->tasklength;
83 return next >= mem_task ? NULL : (struct task *)next;
84 }
85
86 void task_delete(uint8_t c)
87 {
88 debug("Going to delete task: %i", c);
89 debug("mem_task: %p", mem_task);
90 struct task *t = task_head();
91 while(t != NULL){
92 if(t->taskid == c){
93 break;
94 }
95 t = task_next(t);
96 }
97
98 if(t != NULL){
99 //We found the task, now we move everything from the end of the task up
100 //to the spacepointer right
101 uint8_t *start = (uint8_t *)t;
102 uint8_t *end = start + sizeof(struct task) + t->tasklength;
103 debug("Moving %lu bytes\n", mem_task-end);
104 for(int i = 0; i<mem_task-end; i++){
105 start[i] = end[i];
106 }
107
108 //Decrement the spacepointer
109 mem_task -= end-start;
110 }
111 debug("mem_task: %p", mem_task);
112 }