b501e0fc1b15f6fc528b6a7a02130aad3e644c61
[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 c = read16();
41 sds_update(c);
42 break;
43 case MSG_SDS_DEL:
44 debug("Receiving a delete SDS request");
45 c = read16();
46 sds_delete(c);
47 write_byte('a');
48 write16(c);
49 write_byte('\n');
50 break;
51 case MSG_DEL_TASK:
52 debug("Receiving a delete task request");
53 c = read16();
54 task_delete(c);
55 //Write acknowledgement
56 write_byte('d');
57 write16(c);
58 write_byte('\n');
59 break;
60 case MSG_GET_TASK:
61 debug("Receiving a task");
62 task_register();
63 break;
64 case MSG_SPEC:
65 debug("Receiving a spec request");
66 spec_send();
67 break;
68 case '\0':
69 debug("Server closed connection");
70 break;
71 case '\n':
72 break;
73 default:
74 debug("Unknown message: %X", c);
75 }
76 } else {
77 // debug("No input");
78 }
79 }
80
81 unsigned long loopmillis = 0;
82 void loop(void)
83 {
84 #ifdef ARDUINO_ESP8266_NODEMCU
85 if(getmillis()-loopmillis < LOOPDELAY){
86 return;
87 }
88 loopmillis = getmillis();
89 #endif
90 read_message();
91
92 //Run tasks
93 unsigned long cyclestart = getmillis();
94 for(struct task *t = task_head(); t != NULL; t = task_next(t)){
95 //interrupt task
96 if(is_interrupt_task(t) && had_interrupt(t)){
97 debug("Interrupt task %d not implemented", t->taskid);
98 run_task(t);
99 //Interval task, and interval passed
100 } else if(cyclestart-t->lastrun > t->interval){
101 debug("Running interval task: %d", t->taskid);
102 run_task(t);
103
104 //Oneshot task, thus disable
105 if(t->interval == 0){
106 task_delete(t->taskid);
107 }
108 t->lastrun = cyclestart;
109 }
110 }
111 }
112
113 #ifdef STM
114 int main(void){
115 #elif defined ARDUINO_ESP8266_NODEMCU
116 void setup(){
117 #elif defined LINUX
118 int main(int argc, char *argv[]){
119 gargc = argc;
120 gargv = argv;
121 #endif
122
123 //Initialize device independant functionality
124 real_setup();
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 }