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

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