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

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