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