dynamic task allocation
[mTask.git] / client / client.c
1 #include <stdbool.h>
2 #include <stdint.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #ifdef LINUX
7 #include <stdio.h>
8 #endif
9
10 #include "interpret.h"
11 #include "mTaskSymbols.h"
12 #include "sds.h"
13 #include "spec.h"
14 #include "task.h"
15 #include "interface.h"
16
17 #define MSG_GET_TASK 't'
18 #define MSG_DEL_TASK 'd'
19 #define MSG_SDS_SPEC 's'
20 #define MSG_SDS_DEL 'a'
21 #define MSG_SDS_UPD 'u'
22 #define MSG_SPEC 'c'
23
24 #define LOOPDELAY 100
25
26 void read_message(void)
27 {
28 //Find next task
29 if(input_available()){
30 uint8_t c = read_byte();
31 debug("Receiving input: %c %02x\n", c, c);
32 switch(c){
33 case MSG_SDS_SPEC:
34 debug("Receiving an sds");
35 sds_register();
36 break;
37 case MSG_SDS_UPD:
38 debug("Receiving an sds update");
39 //TODO do something with the return value
40 sds_update();
41 break;
42 case MSG_SDS_DEL:
43 debug("Receiving a delete SDS request");
44 sds_delete();
45 break;
46 case MSG_DEL_TASK:
47 debug("Receiving a delete task request");
48 c = read16();
49 task_delete(c);
50 //Write acknowledgement
51 write_byte('d');
52 write16(c);
53 write_byte('\n');
54 break;
55 case MSG_GET_TASK:
56 debug("Receiving a task");
57 task_register();
58 break;
59 case MSG_SPEC:
60 debug("Receiving a spec request");
61 spec_send();
62 break;
63 case '\0':
64 debug("Server closed connection");
65 break;
66 case '\n':
67 break;
68 default:
69 debug("Unknown message: %X", c);
70 }
71 } else {
72 // debug("No input");
73 }
74 }
75
76 unsigned long loopmillis = 0;
77 void loop(void)
78 {
79 #ifdef ARDUINO_ESP8266_NODEMCU
80 if(getmillis()-loopmillis < LOOPDELAY){
81 return;
82 }
83 loopmillis = getmillis();
84 #endif
85 debug("Loop");
86
87 read_message();
88
89 //Run tasks
90 unsigned long cyclestart = getmillis();
91 for(struct task *t = task_head(); t != NULL; t = task_next(t)){
92 //interrupt task
93 if(is_interrupt_task(t) && had_interrupt(t)){
94 debug("Interrupt task %d not implemented", t->taskid);
95 run_task(t);
96 //Interval task, and interval passed
97 } else if(cyclestart-t->lastrun > t->interval){
98 debug("Running interval task: %d", t->taskid);
99 run_task(t);
100
101 //Oneshot task, thus disable
102 if(t->interval == 0){
103 task_delete(t->taskid);
104 }
105 t->lastrun = cyclestart;
106 }
107 }
108 }
109
110 #ifdef STM
111 int main(void){
112 #elif defined ARDUINO_ESP8266_NODEMCU
113 void setup(){
114 #elif defined LINUX
115 int main(int argc, char *argv[]){
116 gargc = argc;
117 gargv = argv;
118 #endif
119
120 //Initialize systems
121 real_setup();
122 sds_init();
123 task_init();
124 debug("sending device spec");
125
126 #ifndef ARDUINO_ESP8266_NODEMCU
127 while(true){
128 //Check for newtasks
129 loop();
130 msdelay(LOOPDELAY);
131 }
132
133 return 0;
134 #endif
135 }