Merge branch 'master' of https://github.com/szmoore/MCTX3420.git
[matches/MCTX3420.git] / server / actuator.c
1 /**
2  * @file actuator.c
3  * @brief Implementation of Actuator related functionality
4  */
5
6 #include "actuator.h"
7 #include "options.h"
8
9 /** Array of Actuators (global to this file) initialised by Actuator_Init **/
10 static Actuator g_actuators[NUMACTUATORS];
11
12 /** Human readable names for the Actuators **/
13 const char * g_actuator_names[NUMACTUATORS] = { 
14         "actuator_test0", "actuator_test1"
15 };
16
17 /**
18  * One off initialisation of *all* Actuators
19  */
20 void Actuator_Init()
21 {
22         for (int i = 0; i < NUMACTUATORS; ++i)
23         {
24                 g_actuators[i].id = i;
25                 Data_Init(&(g_actuators[i].data_file));
26                 pthread_mutex_init(&(g_actuators[i].mutex), NULL);
27         }
28 }
29
30 /**
31  * Sets the actuator to the desired mode. No checks are
32  * done to see if setting to the desired mode will conflict with
33  * the current mode - the caller must guarantee this itself.
34  * @param a The actuator whose mode is to be changed
35  * @param mode The mode to be changed to
36  * @param arg An argument specific to the mode to be set. 
37  *            e.g for CONTROL_START it represents the experiment name.
38  */
39 void Actuator_SetMode(Actuator * a, ControlModes mode, void *arg)
40 {
41         switch (mode)
42         {
43                 case CONTROL_START:
44                         {
45                                 char filename[BUFSIZ];
46                                 const char *experiment_name = (const char*) arg;
47                                 int ret;
48
49                                 if (snprintf(filename, BUFSIZ, "%s_a%d", experiment_name, a->id) >= BUFSIZ)
50                                 {
51                                         Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
52                                 }
53
54                                 Log(LOGDEBUG, "Actuator %d with DataFile \"%s\"", a->id, filename);
55                                 // Open DataFile
56                                 Data_Open(&(a->data_file), filename);
57
58                                 a->activated = true; // Don't forget this
59                                 a->allow_actuation = true;
60
61                                 a->control_changed = false;
62
63                                 // Create the thread
64                                 ret = pthread_create(&(a->thread), NULL, Actuator_Loop, (void*)(a));
65                                 if (ret != 0)
66                                 {
67                                         Fatal("Failed to create Actuator_Loop for Actuator %d", a->id);
68                                 }
69                         }
70                 break;
71
72                 case CONTROL_EMERGENCY: //TODO add proper case for emergency
73                 case CONTROL_PAUSE:
74                         a->allow_actuation = false;
75                 break;
76                 case CONTROL_RESUME:
77                         a->allow_actuation = true;
78                 break;
79                 case CONTROL_STOP:
80                         a->allow_actuation = false;
81                         a->activated = false;
82                         Actuator_SetControl(a, NULL);
83                         pthread_join(a->thread, NULL); // Wait for thread to exit       
84                         Data_Close(&(a->data_file)); // Close DataFile
85                 break;
86                 default:
87                         Fatal("Unknown control mode: %d", mode);
88         }
89 }
90
91 /**
92  * Sets all actuators to the desired mode. 
93  * @see Actuator_SetMode for more information.
94  * @param mode The mode to be changed to
95  * @param arg An argument specific to the mode to be set.
96  */
97 void Actuator_SetModeAll(ControlModes mode, void * arg)
98 {
99         for (int i = 0; i < NUMACTUATORS; i++)
100                 Actuator_SetMode(&g_actuators[i], mode, arg);
101 }
102
103 /**
104  * Actuator control thread
105  * @param arg - Cast to an Actuator*
106  * @returns NULL to keep pthreads happy
107  */
108 void * Actuator_Loop(void * arg)
109 {
110         Actuator * a = (Actuator*)(arg);
111         
112         // Loop until stopped
113         while (a->activated)
114         {
115                 pthread_mutex_lock(&(a->mutex));
116                 while (!a->control_changed)
117                 {
118                         pthread_cond_wait(&(a->cond), &(a->mutex));
119                 }
120                 a->control_changed = false;
121                 pthread_mutex_unlock(&(a->mutex));
122                 if (!a->activated)
123                         break;
124                 else if (!a->allow_actuation)
125                         continue;
126
127                 Actuator_SetValue(a, a->control.value);
128         }
129
130         //TODO: Cleanup?
131         
132         // Keep pthreads happy
133         return NULL;
134 }
135
136 /**
137  * Set an Actuators control variable
138  * @param a - Actuator to control 
139  * @param c - Control to set to
140  */
141 void Actuator_SetControl(Actuator * a, ActuatorControl * c)
142 {
143         pthread_mutex_lock(&(a->mutex));
144         if (c != NULL)
145                 a->control = *c;
146         a->control_changed = true;
147         pthread_cond_broadcast(&(a->cond));
148         pthread_mutex_unlock(&(a->mutex));
149         
150 }
151
152 /**
153  * Set an Actuator value
154  * @param a - The Actuator
155  * @param value - The value to set
156  */
157 void Actuator_SetValue(Actuator * a, double value)
158 {
159         // Set time stamp
160         struct timeval t;
161         gettimeofday(&t, NULL);
162
163         DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), value};
164         //TODO: Set actuator
165         switch (a->id)
166         {
167                 case ACTUATOR_TEST0:
168                         break;
169                 case ACTUATOR_TEST1:
170                         break;
171         }
172
173         Log(LOGDEBUG, "Actuator %s set to %f", g_actuator_names[a->id], value);
174
175         // Record the value
176         Data_Save(&(a->data_file), &d, 1);
177 }
178
179 /**
180  * Helper: Begin Actuator response in a given format
181  * @param context - the FCGIContext
182  * @param format - Format
183  * @param id - ID of Actuator
184  */
185 void Actuator_BeginResponse(FCGIContext * context, ActuatorId id, DataFormat format)
186 {
187         // Begin response
188         switch (format)
189         {
190                 case JSON:
191                         FCGI_BeginJSON(context, STATUS_OK);
192                         FCGI_JSONLong("id", id);
193                         break;
194                 default:
195                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
196                         break;
197         }
198 }
199
200 /**
201  * Helper: End Actuator response in a given format
202  * @param context - the FCGIContext
203  * @param id - ID of the Actuator
204  * @param format - Format
205  */
206 void Actuator_EndResponse(FCGIContext * context, ActuatorId id, DataFormat format)
207 {
208         // End response
209         switch (format)
210         {
211                 case JSON:
212                         FCGI_EndJSON();
213                         break;
214                 default:
215                         break;
216         }
217 }
218
219
220
221
222 /**
223  * Handle a request for an Actuator
224  * @param context - FCGI context
225  * @param params - Parameters passed
226  */
227 void Actuator_Handler(FCGIContext * context, char * params)
228 {
229         struct timeval now;
230         gettimeofday(&now, NULL);
231         double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
232         int id = 0;
233         double set = 0;
234         double start_time = 0;
235         double end_time = current_time;
236         char * fmt_str;
237
238         // key/value pairs
239         FCGIValue values[] = {
240                 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)}, 
241                 {"set", &set, FCGI_DOUBLE_T},
242                 {"start_time", &start_time, FCGI_DOUBLE_T},
243                 {"end_time", &end_time, FCGI_DOUBLE_T},
244                 {"format", &fmt_str, FCGI_STRING_T}
245         };
246
247         // enum to avoid the use of magic numbers
248         typedef enum {
249                 ID,
250                 SET,
251                 START_TIME,
252                 END_TIME,
253                 FORMAT
254         } ActuatorParams;
255         
256         // Fill values appropriately
257         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
258         {
259                 // Error occured; FCGI_RejectJSON already called
260                 return;
261         }       
262
263         // Get the Actuator identified
264         Actuator * a = NULL;
265         if (id < 0 || id >= NUMACTUATORS)
266         {
267                 FCGI_RejectJSON(context, "Invalid Actuator id");
268                 return;
269         }
270         
271         a = g_actuators+id;
272
273         DataFormat format = Data_GetFormat(&(values[FORMAT]));
274
275         // Begin response
276         Actuator_BeginResponse(context, id, format);
277
278         // Set?
279         if (FCGI_RECEIVED(values[SET].flags))
280         {
281                 if (format == JSON)
282                         FCGI_JSONDouble("set", set);
283         
284                 ActuatorControl c;
285                 c.value = set;
286
287                 Actuator_SetControl(a, &c);
288         }
289
290         // Print Data
291         Data_Handler(&(a->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
292         
293         // Finish response
294         Actuator_EndResponse(context, id, format);
295 }

UCC git Repository :: git.ucc.asn.au