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

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