Merge pull request #59 from jtanx/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 /** 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                 while (!a->control_changed && a->control.steps > 0 && a->activated)
175                 {
176                         usleep(1e6*(a->control.stepwait));
177                         a->control.start += a->control.stepsize;
178                         Actuator_SetValue(a, a->control.start, true);
179                         
180                         a->control.steps--;
181                 }
182                 if (a->control_changed)
183                         continue;
184                 usleep(1e6*(a->control.stepwait));
185
186                 //TODO:
187                 // Note that although this loop has a sleep in it which would seem to make it hard to enforce urgent shutdowns,
188                 //      You can call the Actuator's cleanup function immediately (and this loop should later just exit)
189                 //      tl;dr This function isn't/shouldn't be responsible for the emergency Actuator stuff
190                 // (That should be handled by the Fatal function... at some point)
191         }
192
193         //TODO: Cleanup?
194         
195         // Keep pthreads happy
196         return NULL;
197 }
198
199 /**
200  * Set an Actuators control variable
201  * @param a - Actuator to control 
202  * @param c - Control to set to
203  */
204 void Actuator_SetControl(Actuator * a, ActuatorControl * c)
205 {
206         pthread_mutex_lock(&(a->mutex));
207         if (c != NULL)
208                 a->control = *c;
209         a->control_changed = true;
210         pthread_cond_broadcast(&(a->cond));
211         pthread_mutex_unlock(&(a->mutex));
212         
213 }
214
215 /**
216  * Set an Actuator value
217  * @param a - The Actuator
218  * @param value - The value to set
219  */
220 void Actuator_SetValue(Actuator * a, double value, bool record)
221 {
222         if (a->sanity != NULL && !a->sanity(a->user_id, value))
223         {
224                 //ARE YOU INSANE?
225                 Log(LOGERR,"Insane value %lf for actuator %s", value, a->name);
226                 return;
227         }
228         if (!(a->set(a->user_id, value)))
229         {
230                 Fatal("Failed to set actuator %s to %lf", a->name, value);
231         }
232
233         // Set time stamp
234         struct timeval t;
235         gettimeofday(&t, NULL);
236         DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), a->last_setting.value};
237         // Record value change
238         if (record)
239         {       
240                 d.time_stamp -= 1e-6;
241                 Data_Save(&(a->data_file), &d, 1);
242                 d.value = value;
243                 d.time_stamp += 1e-6;
244                 Data_Save(&(a->data_file), &d, 1);
245         }
246         a->last_setting = d;
247 }
248
249 /**
250  * Helper: Begin Actuator response in a given format
251  * @param context - the FCGIContext
252  * @param format - Format
253  * @param id - ID of Actuator
254  */
255 void Actuator_BeginResponse(FCGIContext * context, Actuator * a, DataFormat format)
256 {
257         // Begin response
258         switch (format)
259         {
260                 case JSON:
261                         FCGI_BeginJSON(context, STATUS_OK);
262                         FCGI_JSONLong("id", a->id);
263                         FCGI_JSONLong("user_id", a->user_id); //TODO: Don't need to show this?
264                         FCGI_JSONPair("name", a->name);
265                         break;
266                 default:
267                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
268                         break;
269         }
270 }
271
272 /**
273  * Helper: End Actuator response in a given format
274  * @param context - the FCGIContext
275  * @param id - ID of the Actuator
276  * @param format - Format
277  */
278 void Actuator_EndResponse(FCGIContext * context, Actuator * a, DataFormat format)
279 {
280         // End response
281         switch (format)
282         {
283                 case JSON:
284                         FCGI_EndJSON();
285                         break;
286                 default:
287                         break;
288         }
289 }
290
291
292 /**
293  * Handle a request for an Actuator
294  * @param context - FCGI context
295  * @param params - Parameters passed
296  */
297 void Actuator_Handler(FCGIContext * context, char * params)
298 {
299         struct timeval now;
300         gettimeofday(&now, NULL);
301         double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
302         int id = 0;
303         char * name = "";
304         char * set = "";
305         double start_time = 0;
306         double end_time = current_time;
307         char * fmt_str;
308
309         // key/value pairs
310         FCGIValue values[] = {
311                 {"id", &id, FCGI_INT_T},
312                 {"name", &name, FCGI_STRING_T}, 
313                 {"set", &set, FCGI_STRING_T},
314                 {"start_time", &start_time, FCGI_DOUBLE_T},
315                 {"end_time", &end_time, FCGI_DOUBLE_T},
316                 {"format", &fmt_str, FCGI_STRING_T}
317         };
318
319         // enum to avoid the use of magic numbers
320         typedef enum {
321                 ID,
322                 NAME,
323                 SET,
324                 START_TIME,
325                 END_TIME,
326                 FORMAT
327         } ActuatorParams;
328         
329         // Fill values appropriately
330         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
331         {
332                 // Error occured; FCGI_RejectJSON already called
333                 return;
334         }       
335
336         // Get the Actuator identified
337         Actuator * a = NULL;
338
339         if (FCGI_RECEIVED(values[NAME].flags))
340         {
341                 if (FCGI_RECEIVED(values[ID].flags))
342                 {
343                         FCGI_RejectJSON(context, "Can't supply both id and name");
344                         return;
345                 }
346                 a = Actuator_Identify(name);
347                 if (a == NULL)
348                 {
349                         FCGI_RejectJSON(context, "Unknown actuator name");
350                         return;
351                 }
352                 
353         }
354         else if (!FCGI_RECEIVED(values[ID].flags))
355         {
356                 FCGI_RejectJSON(context, "No id or name supplied");
357                 return;
358         }
359         else if (id < 0 || id >= g_num_actuators)
360         {
361                 FCGI_RejectJSON(context, "Invalid Actuator id");
362                 return;
363         }
364         else
365         {
366                 a = &(g_actuators[id]);
367         }
368         
369
370         DataFormat format = Data_GetFormat(&(values[FORMAT]));
371
372
373
374
375         if (FCGI_RECEIVED(values[SET].flags))
376         {
377                 
378         
379                 ActuatorControl c = {0.0, 0.0, 0.0, 0}; // Need to set default values (since we don't require them all)
380                 // sscanf returns the number of fields successfully read...
381                 int n = sscanf(set, "%lf,%lf,%lf,%d", &(c.start), &(c.stepwait), &(c.stepsize), &(c.steps)); // Set provided values in order
382                 if (n != 4)
383                 {
384                         //      If the user doesn't provide all 4 values, the Actuator will get set *once* using the first of the provided values
385                         //      (see Actuator_Loop)
386                         //  Not really a problem if n = 1, but maybe generate a warning for 2 <= n < 4 ?
387                         Log(LOGDEBUG, "Only provided %d values (expect %d) for Actuator setting", n, 4);
388                 }
389                 // SANITY CHECKS
390                 if (c.stepwait < 0 || c.steps < 0 || (a->sanity != NULL && !a->sanity(a->user_id, c.start)))
391                 {
392                         FCGI_RejectJSON(context, "Bad Actuator setting");
393                         return;
394                 }
395                 Actuator_SetControl(a, &c);
396         }
397         
398         // Begin response
399         Actuator_BeginResponse(context, a, format);
400         if (format == JSON)
401                 FCGI_JSONPair("set", set);
402
403         // Print Data
404         Data_Handler(&(a->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
405         
406         // Finish response
407         Actuator_EndResponse(context, a, format);
408 }
409
410 /**
411  * Get the name of an Actuator given its id
412  * @param id - ID of the actuator
413  * @returns The Actuator's name
414  */
415 const char * Actuator_GetName(int id)
416 {
417         return g_actuators[id].name;
418 }
419
420 /**
421  * Identify an Actuator from its name string
422  * @param name - The name of the Actuator
423  * @returns Actuator
424  */
425 Actuator * Actuator_Identify(const char * name)
426 {
427         for (int i = 0; i < g_num_actuators; ++i)
428         {
429                 if (strcmp(g_actuators[i].name, name) == 0)
430                         return &(g_actuators[i]);
431         }
432         return NULL;
433 }

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