9206a130d55b7ff665903b5e9468531f215b3898
[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
54 write_byte('t');
55 write16(t->taskid);
56 write_byte('\n');
57 debug("free memory: %lu\n", mem_free());
58 }
59
60 bool is_interrupt_task(struct task *t)
61 {
62 return t->interval & (2 <<14);
63 }
64
65 bool had_interrupt(struct task* t)
66 {
67 //Not implemented yet...
68 return false;
69 (void)t;
70 }
71
72 struct task *task_head(void)
73 {
74 return mem_task == mem_bottom ? NULL : (struct task *)mem_bottom;
75 }
76
77 struct task *task_next(struct task *t)
78 {
79 uint8_t *next = (uint8_t *)t + sizeof(struct task) + t->tasklength;
80 return next >= mem_task ? NULL : (struct task *)next;
81 }
82
83 void task_delete(uint8_t c)
84 {
85 debug("Going to delete task: %i", c);
86 struct task *t = task_head();
87 while(t != NULL){
88 if(t->taskid == c){
89 break;
90 }
91 t = task_next(t);
92 }
93
94 if(t != NULL){
95 //We found the task, now we move everything from the end of the task up
96 //to the spacepointer right
97 uint8_t *start = (uint8_t *)t;
98 uint8_t *end = start + sizeof(struct task) + t->tasklength;
99 debug("Moving %lu bytes\n", mem_task-end);
100 for(int i = 0; i<mem_task-end; i++){
101 start[i] = end[i];
102 }
103
104 //Decrement the spacepointer
105 mem_task -= end-start;
106 }
107 }