update
[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 struct task *head = NULL;
14
15 void task_init(void)
16 {
17 memset(&taskspace, 0, TASKSPACE);
18 head = NULL;
19 }
20
21 void task_register(void)
22 {
23 int i;
24 if(spacepointer+sizeof(struct task) > taskspace+TASKSPACE){
25 die("Out of memory... Not enough to allocate taskstruct");
26 }
27
28 //We haven't had a task before, therefore we initialize head
29 struct task *t = (struct task *)spacepointer;
30 if(head == NULL) {
31 head = t;
32 }
33
34 //Read interval
35 t->interval = read16();
36 debug("interval: %d\n", t->interval);
37
38 //Interrupt task
39 if(is_interrupt_task(t)) {
40
41 }
42
43 //Read tasklength
44 t->tasklength = read16();
45 debug("task interval: %d, length: %d\n", t->interval, t->tasklength);
46
47 if(spacepointer+t->tasklength > taskspace+TASKSPACE){
48 die("Out of memory... Not enough to allocate bytes");
49 }
50
51 spacepointer += t->tasklength;
52
53 //Read task bytecode
54 for(i = 0; i<t->tasklength; i++){
55 t->bc[i] = read_byte();
56 }
57 //Return the task number for later removal
58 debug("Received a task of length %d", t->tasklength);
59 t->lastrun = 0L;
60 t->taskid = taskid++;
61
62 write_byte('t');
63 write16(t->taskid);
64 write_byte('\n');
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 head;
82 }
83
84 struct task *task_next(struct task *t)
85 {
86 if(t == NULL){
87 return NULL;
88 }
89
90 uint8_t *next = (uint8_t *)t;
91 next += sizeof(struct task);
92 next += t->tasklength;
93
94 return next > spacepointer ? NULL : (struct task *)next;
95 }
96
97 void task_delete(void)
98 {
99 uint8_t c = read16();
100 struct task *t = NULL;
101 while(t != NULL){
102 if(t->taskid == c){
103 break;
104 }
105 t = task_next(t);
106 }
107 if(t != NULL){
108 //We found the task, now we move everything from the end of the task up
109 //to the spacepointer right
110 uint8_t *start = (uint8_t *)t;
111 uint8_t *end = start + sizeof(struct task) + t->tasklength;
112 debug("Moving %lu bytes\n", spacepointer-end);
113 for(int i = 0; i<spacepointer-end; i++){
114 start[i] = end[i];
115 }
116
117 //Decrement the spacepointer
118 spacepointer -= end-start;
119
120 if(t == head){
121 head = task_next(t);
122 }
123
124 //Write acknowledgement
125 write_byte('d');
126 write16(c);
127 write_byte('\n');
128 }
129 }