3 * @brief Implementation of Actuator related functionality
8 // Files containing GPIO and PWM definitions
11 /** Number of actuators **/
12 int g_num_actuators = 0;
14 /** Array of Actuators (global to this file) initialised by Actuator_Init **/
15 static Actuator g_actuators[ACTUATORS_MAX];
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
23 int Actuator_Add(const char * name, int user_id, SetFn set, InitFn init, CleanFn cleanup, SanityFn sanity, double initial_value)
25 if (++g_num_actuators > ACTUATORS_MAX)
27 Fatal("Too many sensors; Increase ACTUATORS_MAX from %d in actuator.h and recompile", ACTUATORS_MAX);
29 Actuator * a = &(g_actuators[g_num_actuators-1]);
30 a->id = g_num_actuators-1;
32 Data_Init(&(a->data_file));
34 a->set = set; // Set read function
35 a->init = init; // Set init function
39 pthread_mutex_init(&(a->mutex), NULL);
43 if (!init(name, user_id))
44 Fatal("Couldn't initialise actuator %s", name);
47 Actuator_SetValue(a, initial_value, false);
49 return g_num_actuators;
54 * Initialisation of *all* Actuators
56 #include "actuators/pregulator.h"
57 #include "actuators/relays.h"
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 Actuator_Add("pregulator", 0, Pregulator_Set, Pregulator_Init, Pregulator_Cleanup, Pregulator_Sanity, 0);
63 Actuator_Add("can_select", RELAY_CANSELECT, Relay_Set, Relay_Init, Relay_Cleanup, Relay_Sanity, 0);
64 Actuator_Add("can_enable", RELAY_CANENABLE, Relay_Set, Relay_Init, Relay_Cleanup, Relay_Sanity, 0);
65 Actuator_Add("main_pressure", RELAY_MAIN, Relay_Set, Relay_Init, Relay_Cleanup, Relay_Sanity, 1);
69 * Deinitialise actuators
71 void Actuator_Cleanup()
73 for (int i = 0; i < g_num_actuators; ++i)
75 Actuator * a = g_actuators+i;
76 if (a->cleanup != NULL)
77 a->cleanup(a->user_id);
84 * Sets the actuator to the desired mode. No checks are
85 * done to see if setting to the desired mode will conflict with
86 * the current mode - the caller must guarantee this itself.
87 * @param a The actuator whose mode is to be changed
88 * @param mode The mode to be changed to
89 * @param arg An argument specific to the mode to be set.
90 * e.g for CONTROL_START it represents the experiment name.
92 void Actuator_SetMode(Actuator * a, ControlModes mode, void *arg)
99 char filename[BUFSIZ];
100 const char *experiment_path = (const char*) arg;
103 ret = snprintf(filename, BUFSIZ, "%s/actuator_%d", experiment_path, a->id);
107 Fatal("Experiment path \"%s\" too long (%d, limit %d)",
108 experiment_path, ret, BUFSIZ);
111 Log(LOGDEBUG, "Actuator %d with DataFile \"%s\"", a->id, filename);
113 Data_Open(&(a->data_file), filename);
115 case CONTROL_RESUME: //Case fallthrough; no break before
118 a->activated = true; // Don't forget this
119 a->control_changed = false;
121 ret = pthread_create(&(a->thread), NULL, Actuator_Loop, (void*)(a));
124 Fatal("Failed to create Actuator_Loop for Actuator %d", a->id);
127 Log(LOGDEBUG, "Resuming actuator %d", a->id);
131 case CONTROL_EMERGENCY: //TODO add proper case for emergency
133 a->activated = false;
134 Actuator_SetControl(a, NULL);
135 pthread_join(a->thread, NULL); // Wait for thread to exit
137 Log(LOGDEBUG, "Paused actuator %d", a->id);
142 if (a->activated) //May have been paused before
144 a->activated = false;
145 Actuator_SetControl(a, NULL);
146 pthread_join(a->thread, NULL); // Wait for thread to exit
148 Data_Close(&(a->data_file)); // Close DataFile
150 Log(LOGDEBUG, "Stopped actuator %d", a->id);
153 Fatal("Unknown control mode: %d", mode);
158 * Sets all actuators to the desired mode.
159 * @see Actuator_SetMode for more information.
160 * @param mode The mode to be changed to
161 * @param arg An argument specific to the mode to be set.
163 void Actuator_SetModeAll(ControlModes mode, void * arg)
165 if (mode == CONTROL_START)
167 for (int i = 0; i < g_num_actuators; i++)
168 Actuator_SetMode(&g_actuators[i], mode, arg);
169 if (mode == CONTROL_STOP)
174 * Actuator control thread
175 * @param arg - Cast to an Actuator*
176 * @returns NULL to keep pthreads happy
178 void * Actuator_Loop(void * arg)
180 Actuator * a = (Actuator*)(arg);
182 // Loop until stopped
185 pthread_mutex_lock(&(a->mutex));
186 while (!a->control_changed)
188 pthread_cond_wait(&(a->cond), &(a->mutex));
190 a->control_changed = false;
191 pthread_mutex_unlock(&(a->mutex));
195 Actuator_SetValue(a, a->control.start, true);
196 // Currently does discrete steps after specified time intervals
198 struct timespec wait;
199 DOUBLE_TO_TIMEVAL(a->control.stepwait, &wait);
200 while (!a->control_changed && a->control.steps > 0 && a->activated)
202 clock_nanosleep(CLOCK_MONOTONIC, 0, &wait, NULL);
203 a->control.start += a->control.stepsize;
204 Actuator_SetValue(a, a->control.start, true);
208 if (a->control_changed)
210 clock_nanosleep(CLOCK_MONOTONIC, 0, &wait, NULL);
213 // Note that although this loop has a sleep in it which would seem to make it hard to enforce urgent shutdowns,
214 // You can call the Actuator's cleanup function immediately (and this loop should later just exit)
215 // tl;dr This function isn't/shouldn't be responsible for the emergency Actuator stuff
216 // (That should be handled by the Fatal function... at some point)
221 // Keep pthreads happy
226 * Set an Actuators control variable
227 * @param a - Actuator to control
228 * @param c - Control to set to
230 void Actuator_SetControl(Actuator * a, ActuatorControl * c)
232 pthread_mutex_lock(&(a->mutex));
235 a->control_changed = true;
236 pthread_cond_broadcast(&(a->cond));
237 pthread_mutex_unlock(&(a->mutex));
242 * Set an Actuator value
243 * @param a - The Actuator
244 * @param value - The value to set
246 void Actuator_SetValue(Actuator * a, double value, bool record)
248 if (a->sanity != NULL && !a->sanity(a->user_id, value))
251 Log(LOGERR,"Insane value %lf for actuator %s", value, a->name);
254 if (!(a->set(a->user_id, value)))
256 Fatal("Failed to set actuator %s to %lf", a->name, value);
261 clock_gettime(CLOCK_MONOTONIC, &t);
262 DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), a->last_setting.value};
263 // Record value change
266 d.time_stamp -= 1e-6;
267 Data_Save(&(a->data_file), &d, 1);
269 d.time_stamp += 1e-6;
270 Data_Save(&(a->data_file), &d, 1);
276 * Helper: Begin Actuator response in a given format
277 * @param context - the FCGIContext
278 * @param format - Format
279 * @param id - ID of Actuator
281 void Actuator_BeginResponse(FCGIContext * context, Actuator * a, DataFormat format)
287 FCGI_BeginJSON(context, STATUS_OK);
288 FCGI_JSONLong("id", a->id);
289 FCGI_JSONLong("user_id", a->user_id); //TODO: Don't need to show this?
290 FCGI_JSONPair("name", a->name);
293 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
299 * Helper: End Actuator response in a given format
300 * @param context - the FCGIContext
301 * @param id - ID of the Actuator
302 * @param format - Format
304 void Actuator_EndResponse(FCGIContext * context, Actuator * a, DataFormat format)
319 * Handle a request for an Actuator
320 * @param context - FCGI context
321 * @param params - Parameters passed
323 void Actuator_Handler(FCGIContext * context, char * params)
326 clock_gettime(CLOCK_MONOTONIC, &now);
327 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
331 double start_time = 0;
332 double end_time = current_time;
336 FCGIValue values[] = {
337 {"id", &id, FCGI_INT_T},
338 {"name", &name, FCGI_STRING_T},
339 {"set", &set, FCGI_STRING_T},
340 {"start_time", &start_time, FCGI_DOUBLE_T},
341 {"end_time", &end_time, FCGI_DOUBLE_T},
342 {"format", &fmt_str, FCGI_STRING_T}
345 // enum to avoid the use of magic numbers
355 // Fill values appropriately
356 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
358 // Error occured; FCGI_RejectJSON already called
362 // Get the Actuator identified
365 if (FCGI_RECEIVED(values[NAME].flags))
367 if (FCGI_RECEIVED(values[ID].flags))
369 FCGI_RejectJSON(context, "Can't supply both id and name");
372 a = Actuator_Identify(name);
375 FCGI_RejectJSON(context, "Unknown actuator name");
380 else if (!FCGI_RECEIVED(values[ID].flags))
382 FCGI_RejectJSON(context, "No id or name supplied");
385 else if (id < 0 || id >= g_num_actuators)
387 FCGI_RejectJSON(context, "Invalid Actuator id");
392 a = &(g_actuators[id]);
396 DataFormat format = Data_GetFormat(&(values[FORMAT]));
401 if (FCGI_RECEIVED(values[SET].flags))
405 ActuatorControl c = {0.0, 0.0, 0.0, 0}; // Need to set default values (since we don't require them all)
406 // sscanf returns the number of fields successfully read...
407 int n = sscanf(set, "%lf_%lf_%lf_%d", &(c.start), &(c.stepwait), &(c.stepsize), &(c.steps)); // Set provided values in order
410 // If the user doesn't provide all 4 values, the Actuator will get set *once* using the first of the provided values
411 // (see Actuator_Loop)
412 // Not really a problem if n = 1, but maybe generate a warning for 2 <= n < 4 ?
413 Log(LOGDEBUG, "Only provided %d values (expect %d) for Actuator setting", n, 4);
416 if (c.stepwait < 0 || c.steps < 0 || (a->sanity != NULL && !a->sanity(a->user_id, c.start)))
418 FCGI_RejectJSON(context, "Bad Actuator setting");
421 Actuator_SetControl(a, &c);
425 Actuator_BeginResponse(context, a, format);
427 FCGI_JSONPair("set", set);
430 Data_Handler(&(a->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
433 Actuator_EndResponse(context, a, format);
437 * Get the name of an Actuator given its id
438 * @param id - ID of the actuator
439 * @returns The Actuator's name
441 const char * Actuator_GetName(int id)
443 return g_actuators[id].name;
447 * Identify an Actuator from its name string
448 * @param name - The name of the Actuator
451 Actuator * Actuator_Identify(const char * name)
453 for (int i = 0; i < g_num_actuators; ++i)
455 if (strcmp(g_actuators[i].name, name) == 0)
456 return &(g_actuators[i]);
461 DataPoint Actuator_LastData(int id)
463 Actuator * a = &(g_actuators[id]);
464 return a->last_setting;