Merge remote-tracking branch 'upstream/master'
[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 // Files containing GPIO and PWM definitions
9 #include "bbb_pin.h"
10
11
12
13
14 /** Number of actuators **/
15 int g_num_actuators = 0;
16
17 /** Array of Actuators (global to this file) initialised by Actuator_Init **/
18 static Actuator g_actuators[ACTUATORS_MAX];
19 /** 
20  * Add and initialise an Actuator
21  * @param name - Human readable name of the actuator
22  * @param read - Function to call whenever the actuator should be read
23  * @param init - Function to call to initialise the actuator (may be NULL)
24  * @returns Number of actuators added so far
25  */
26 int Actuator_Add(const char * name, int user_id, SetFn set, InitFn init, CleanFn cleanup, SanityFn sanity)
27 {
28         if (++g_num_actuators > ACTUATORS_MAX)
29         {
30                 Fatal("Too many sensors; Increase ACTUATORS_MAX from %d in actuator.h and recompile", ACTUATORS_MAX);
31         }
32         Actuator * a = &(g_actuators[g_num_actuators-1]);
33         a->id = g_num_actuators-1;
34         a->user_id = user_id;
35         Data_Init(&(a->data_file));
36         a->name = name;
37         a->set = set; // Set read function
38         a->init = init; // Set init function
39         if (init != NULL)
40                 init(name, user_id); // Call it
41         a->sanity = sanity;
42
43         pthread_mutex_init(&(a->mutex), NULL);
44
45         return g_num_actuators;
46 }
47
48
49 /**
50  * One off initialisation of *all* Actuators
51  */
52 #include "actuators/ledtest.h"
53 #include "actuators/filetest.h"
54 void Actuator_Init()
55 {
56         //Actuator_Add("ledtest",0,  Ledtest_Set, NULL,NULL,NULL);
57         Actuator_Add("filetest", 0, Filetest_Set, Filetest_Init, Filetest_Cleanup, Filetest_Sanity);
58 }
59
60 /**
61  * Sets the actuator to the desired mode. No checks are
62  * done to see if setting to the desired mode will conflict with
63  * the current mode - the caller must guarantee this itself.
64  * @param a The actuator whose mode is to be changed
65  * @param mode The mode to be changed to
66  * @param arg An argument specific to the mode to be set. 
67  *            e.g for CONTROL_START it represents the experiment name.
68  */
69 void Actuator_SetMode(Actuator * a, ControlModes mode, void *arg)
70 {
71         switch (mode)
72         {
73                 case CONTROL_START:
74                         {
75                                 char filename[BUFSIZ];
76                                 const char *experiment_name = (const char*) arg;
77
78                                 if (snprintf(filename, BUFSIZ, "%s_a%d", experiment_name, a->id) >= BUFSIZ)
79                                 {
80                                         Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
81                                 }
82
83                                 Log(LOGDEBUG, "Actuator %d with DataFile \"%s\"", a->id, filename);
84                                 // Open DataFile
85                                 Data_Open(&(a->data_file), filename);
86                         } 
87                 case CONTROL_RESUME:  //Case fallthrough; no break before
88                         {
89                                 int ret;
90                                 a->activated = true; // Don't forget this
91                                 a->control_changed = false;
92
93                                 ret = pthread_create(&(a->thread), NULL, Actuator_Loop, (void*)(a));
94                                 if (ret != 0)
95                                 {
96                                         Fatal("Failed to create Actuator_Loop for Actuator %d", a->id);
97                                 }
98
99                                 Log(LOGDEBUG, "Resuming actuator %d", a->id);
100                         }
101                 break;
102
103                 case CONTROL_EMERGENCY: //TODO add proper case for emergency
104                 case CONTROL_PAUSE:
105                         a->activated = false;
106                         Actuator_SetControl(a, NULL);
107                         pthread_join(a->thread, NULL); // Wait for thread to exit
108
109                         Log(LOGDEBUG, "Paused actuator %d", a->id);
110                 break;
111
112                 break;
113                 case CONTROL_STOP:
114                         if (a->activated) //May have been paused before
115                         {
116                                 a->activated = false;
117                                 Actuator_SetControl(a, NULL);
118                                 pthread_join(a->thread, NULL); // Wait for thread to exit       
119                         }
120                         Data_Close(&(a->data_file)); // Close DataFile
121                         
122                         Log(LOGDEBUG, "Stopped actuator %d", a->id);
123                 break;
124                 default:
125                         Fatal("Unknown control mode: %d", mode);
126         }
127 }
128
129 /**
130  * Sets all actuators to the desired mode. 
131  * @see Actuator_SetMode for more information.
132  * @param mode The mode to be changed to
133  * @param arg An argument specific to the mode to be set.
134  */
135 void Actuator_SetModeAll(ControlModes mode, void * arg)
136 {
137         for (int i = 0; i < ACTUATORS_MAX; i++)
138                 Actuator_SetMode(&g_actuators[i], mode, arg);
139 }
140
141 /**
142  * Actuator control thread
143  * @param arg - Cast to an Actuator*
144  * @returns NULL to keep pthreads happy
145  */
146 void * Actuator_Loop(void * arg)
147 {
148         Actuator * a = (Actuator*)(arg);
149         
150         // Loop until stopped
151         while (a->activated)
152         {
153                 pthread_mutex_lock(&(a->mutex));
154                 while (!a->control_changed)
155                 {
156                         pthread_cond_wait(&(a->cond), &(a->mutex));
157                 }
158                 a->control_changed = false;
159                 pthread_mutex_unlock(&(a->mutex));
160                 if (!a->activated)
161                         break;
162
163                 Actuator_SetValue(a, a->control.start);
164                 // Currently does discrete steps after specified time intervals
165                 while (a->control.steps > 0 && a->activated)
166                 {
167                         usleep(1e6*(a->control.stepwait));
168                         a->control.start += a->control.stepsize;
169                         Actuator_SetValue(a, a->control.start);
170                         
171                         a->control.steps--;
172                 }
173                 usleep(1e6*(a->control.stepwait));
174
175                 //TODO:
176                 // Note that although this loop has a sleep in it which would seem to make it hard to enforce urgent shutdowns,
177                 //      You can call the Actuator's cleanup function immediately (and this loop should later just exit)
178                 //      tl;dr This function isn't/shouldn't be responsible for the emergency Actuator stuff
179                 // (That should be handled by the Fatal function... at some point)
180         }
181
182         //TODO: Cleanup?
183         
184         // Keep pthreads happy
185         return NULL;
186 }
187
188 /**
189  * Set an Actuators control variable
190  * @param a - Actuator to control 
191  * @param c - Control to set to
192  */
193 void Actuator_SetControl(Actuator * a, ActuatorControl * c)
194 {
195         pthread_mutex_lock(&(a->mutex));
196         if (c != NULL)
197                 a->control = *c;
198         a->control_changed = true;
199         pthread_cond_broadcast(&(a->cond));
200         pthread_mutex_unlock(&(a->mutex));
201         
202 }
203
204 /**
205  * Set an Actuator value
206  * @param a - The Actuator
207  * @param value - The value to set
208  */
209 void Actuator_SetValue(Actuator * a, double value)
210 {
211         if (a->sanity != NULL && !a->sanity(a->user_id, value))
212         {
213                 //ARE YOU INSANE?
214                 Fatal("Insane value %lf for actuator %s", value, a->name);
215         }
216         if (!(a->set(a->user_id, value)))
217         {
218                 Fatal("Failed to set actuator %s to %lf", a->name, value);
219         }
220
221         // Set time stamp
222         struct timeval t;
223         gettimeofday(&t, NULL);
224         // Record and save DataPoint
225         DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), value};
226         Data_Save(&(a->data_file), &d, 1);
227 }
228
229 /**
230  * Helper: Begin Actuator response in a given format
231  * @param context - the FCGIContext
232  * @param format - Format
233  * @param id - ID of Actuator
234  */
235 void Actuator_BeginResponse(FCGIContext * context, Actuator * a, DataFormat format)
236 {
237         // Begin response
238         switch (format)
239         {
240                 case JSON:
241                         FCGI_BeginJSON(context, STATUS_OK);
242                         FCGI_JSONLong("id", a->id);
243                         FCGI_JSONLong("user_id", a->user_id); //TODO: Don't need to show this?
244                         FCGI_JSONPair("name", a->name);
245                         break;
246                 default:
247                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
248                         break;
249         }
250 }
251
252 /**
253  * Helper: End Actuator response in a given format
254  * @param context - the FCGIContext
255  * @param id - ID of the Actuator
256  * @param format - Format
257  */
258 void Actuator_EndResponse(FCGIContext * context, Actuator * a, DataFormat format)
259 {
260         // End response
261         switch (format)
262         {
263                 case JSON:
264                         FCGI_EndJSON();
265                         break;
266                 default:
267                         break;
268         }
269 }
270
271
272 /**
273  * Handle a request for an Actuator
274  * @param context - FCGI context
275  * @param params - Parameters passed
276  */
277 void Actuator_Handler(FCGIContext * context, char * params)
278 {
279         struct timeval now;
280         gettimeofday(&now, NULL);
281         double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
282         int id = 0;
283         char * name = "";
284         char * set = "";
285         double start_time = 0;
286         double end_time = current_time;
287         char * fmt_str;
288
289         // key/value pairs
290         FCGIValue values[] = {
291                 {"id", &id, FCGI_INT_T},
292                 {"name", &name, FCGI_STRING_T}, 
293                 {"set", &set, FCGI_STRING_T},
294                 {"start_time", &start_time, FCGI_DOUBLE_T},
295                 {"end_time", &end_time, FCGI_DOUBLE_T},
296                 {"format", &fmt_str, FCGI_STRING_T}
297         };
298
299         // enum to avoid the use of magic numbers
300         typedef enum {
301                 ID,
302                 NAME,
303                 SET,
304                 START_TIME,
305                 END_TIME,
306                 FORMAT
307         } ActuatorParams;
308         
309         // Fill values appropriately
310         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
311         {
312                 // Error occured; FCGI_RejectJSON already called
313                 return;
314         }       
315
316         // Get the Actuator identified
317         Actuator * a = NULL;
318
319         if (FCGI_RECEIVED(values[NAME].flags))
320         {
321                 if (FCGI_RECEIVED(values[ID].flags))
322                 {
323                         FCGI_RejectJSON(context, "Can't supply both id and name");
324                         return;
325                 }
326                 a = Actuator_Identify(name);
327                 if (a == NULL)
328                 {
329                         FCGI_RejectJSON(context, "Unknown actuator name");
330                         return;
331                 }
332                 
333         }
334         else if (!FCGI_RECEIVED(values[ID].flags))
335         {
336                 FCGI_RejectJSON(context, "No id or name supplied");
337                 return;
338         }
339         else if (id < 0 || id >= ACTUATORS_MAX)
340         {
341                 FCGI_RejectJSON(context, "Invalid Actuator id");
342                 return;
343         }
344         else
345         {
346                 a = &(g_actuators[id]);
347         }
348         
349
350         DataFormat format = Data_GetFormat(&(values[FORMAT]));
351
352
353
354
355         if (FCGI_RECEIVED(values[SET].flags))
356         {
357                 
358         
359                 ActuatorControl c = {0.0, 0.0, 0.0, 0}; // Need to set default values (since we don't require them all)
360                 // sscanf returns the number of fields successfully read...
361                 int n = sscanf(set, "%lf,%lf,%lf,%d", &(c.start), &(c.stepwait), &(c.stepsize), &(c.steps)); // Set provided values in order
362                 if (n != 4)
363                 {
364                         //      If the user doesn't provide all 4 values, the Actuator will get set *once* using the first of the provided values
365                         //      (see Actuator_Loop)
366                         //  Not really a problem if n = 1, but maybe generate a warning for 2 <= n < 4 ?
367                         Log(LOGDEBUG, "Only provided %d values (expect %d) for Actuator setting", n);
368                 }
369                 // SANITY CHECKS
370                 if (c.stepwait < 0 || c.steps < 0 || (a->sanity != NULL && !a->sanity(a->user_id, c.start)))
371                 {
372                         FCGI_RejectJSON(context, "Bad Actuator setting");
373                         return;
374                 }
375                 Actuator_SetControl(a, &c);
376
377         }
378         
379         // Begin response
380         Actuator_BeginResponse(context, a, format);
381         if (format == JSON)
382                 FCGI_JSONPair("set", set);
383
384         // Print Data
385         Data_Handler(&(a->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
386         
387         // Finish response
388         Actuator_EndResponse(context, a, format);
389 }
390
391 /**
392  * Get the name of an Actuator given its id
393  * @param id - ID of the actuator
394  * @returns The Actuator's name
395  */
396 const char * Actuator_GetName(int id)
397 {
398         return g_actuators[id].name;
399 }
400
401 /**
402  * Identify an Actuator from its name string
403  * @param name - The name of the Actuator
404  * @returns Actuator
405  */
406 Actuator * Actuator_Identify(const char * name)
407 {
408         for (int i = 0; i < g_num_actuators; ++i)
409         {
410                 if (strcmp(g_actuators[i].name, name) == 0)
411                         return &(g_actuators[i]);
412         }
413         return NULL;
414 }

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