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

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