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 * One off initialisation of *all* Actuators
56 #include "actuators/ledtest.h"
57 #include "actuators/filetest.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);
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.
73 void Actuator_SetMode(Actuator * a, ControlModes mode, void *arg)
80 char filename[BUFSIZ];
81 const char *experiment_path = (const char*) arg;
84 ret = snprintf(filename, BUFSIZ, "%s/actuator_%d", experiment_path, a->id);
88 Fatal("Experiment path \"%s\" too long (%d, limit %d)",
89 experiment_path, ret, BUFSIZ);
92 Log(LOGDEBUG, "Actuator %d with DataFile \"%s\"", a->id, filename);
94 Data_Open(&(a->data_file), filename);
96 case CONTROL_RESUME: //Case fallthrough; no break before
99 a->activated = true; // Don't forget this
100 a->control_changed = false;
102 ret = pthread_create(&(a->thread), NULL, Actuator_Loop, (void*)(a));
105 Fatal("Failed to create Actuator_Loop for Actuator %d", a->id);
108 Log(LOGDEBUG, "Resuming actuator %d", a->id);
112 case CONTROL_EMERGENCY: //TODO add proper case for emergency
114 a->activated = false;
115 Actuator_SetControl(a, NULL);
116 pthread_join(a->thread, NULL); // Wait for thread to exit
118 Log(LOGDEBUG, "Paused actuator %d", a->id);
123 if (a->activated) //May have been paused before
125 a->activated = false;
126 Actuator_SetControl(a, NULL);
127 pthread_join(a->thread, NULL); // Wait for thread to exit
129 Data_Close(&(a->data_file)); // Close DataFile
131 Log(LOGDEBUG, "Stopped actuator %d", a->id);
134 Fatal("Unknown control mode: %d", mode);
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.
144 void Actuator_SetModeAll(ControlModes mode, void * arg)
146 for (int i = 0; i < g_num_actuators; i++)
147 Actuator_SetMode(&g_actuators[i], mode, arg);
151 * Actuator control thread
152 * @param arg - Cast to an Actuator*
153 * @returns NULL to keep pthreads happy
155 void * Actuator_Loop(void * arg)
157 Actuator * a = (Actuator*)(arg);
159 // Loop until stopped
162 pthread_mutex_lock(&(a->mutex));
163 while (!a->control_changed)
165 pthread_cond_wait(&(a->cond), &(a->mutex));
167 a->control_changed = false;
168 pthread_mutex_unlock(&(a->mutex));
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)
176 usleep(1e6*(a->control.stepwait));
177 a->control.start += a->control.stepsize;
178 Actuator_SetValue(a, a->control.start, true);
182 if (a->control_changed)
184 usleep(1e6*(a->control.stepwait));
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)
195 // Keep pthreads happy
200 * Set an Actuators control variable
201 * @param a - Actuator to control
202 * @param c - Control to set to
204 void Actuator_SetControl(Actuator * a, ActuatorControl * c)
206 pthread_mutex_lock(&(a->mutex));
209 a->control_changed = true;
210 pthread_cond_broadcast(&(a->cond));
211 pthread_mutex_unlock(&(a->mutex));
216 * Set an Actuator value
217 * @param a - The Actuator
218 * @param value - The value to set
220 void Actuator_SetValue(Actuator * a, double value, bool record)
222 if (a->sanity != NULL && !a->sanity(a->user_id, value))
225 Log(LOGERR,"Insane value %lf for actuator %s", value, a->name);
228 if (!(a->set(a->user_id, value)))
230 Fatal("Failed to set actuator %s to %lf", a->name, value);
235 gettimeofday(&t, NULL);
236 DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), a->last_setting.value};
237 // Record value change
240 d.time_stamp -= 1e-6;
241 Data_Save(&(a->data_file), &d, 1);
243 d.time_stamp += 1e-6;
244 Data_Save(&(a->data_file), &d, 1);
250 * Helper: Begin Actuator response in a given format
251 * @param context - the FCGIContext
252 * @param format - Format
253 * @param id - ID of Actuator
255 void Actuator_BeginResponse(FCGIContext * context, Actuator * a, DataFormat format)
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);
267 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
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
278 void Actuator_EndResponse(FCGIContext * context, Actuator * a, DataFormat format)
293 * Handle a request for an Actuator
294 * @param context - FCGI context
295 * @param params - Parameters passed
297 void Actuator_Handler(FCGIContext * context, char * params)
300 gettimeofday(&now, NULL);
301 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
305 double start_time = 0;
306 double end_time = current_time;
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}
319 // enum to avoid the use of magic numbers
329 // Fill values appropriately
330 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
332 // Error occured; FCGI_RejectJSON already called
336 // Get the Actuator identified
339 if (FCGI_RECEIVED(values[NAME].flags))
341 if (FCGI_RECEIVED(values[ID].flags))
343 FCGI_RejectJSON(context, "Can't supply both id and name");
346 a = Actuator_Identify(name);
349 FCGI_RejectJSON(context, "Unknown actuator name");
354 else if (!FCGI_RECEIVED(values[ID].flags))
356 FCGI_RejectJSON(context, "No id or name supplied");
359 else if (id < 0 || id >= g_num_actuators)
361 FCGI_RejectJSON(context, "Invalid Actuator id");
366 a = &(g_actuators[id]);
370 DataFormat format = Data_GetFormat(&(values[FORMAT]));
375 if (FCGI_RECEIVED(values[SET].flags))
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
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);
390 if (c.stepwait < 0 || c.steps < 0 || (a->sanity != NULL && !a->sanity(a->user_id, c.start)))
392 FCGI_RejectJSON(context, "Bad Actuator setting");
395 Actuator_SetControl(a, &c);
399 Actuator_BeginResponse(context, a, format);
401 FCGI_JSONPair("set", set);
404 Data_Handler(&(a->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
407 Actuator_EndResponse(context, a, format);
411 * Get the name of an Actuator given its id
412 * @param id - ID of the actuator
413 * @returns The Actuator's name
415 const char * Actuator_GetName(int id)
417 return g_actuators[id].name;
421 * Identify an Actuator from its name string
422 * @param name - The name of the Actuator
425 Actuator * Actuator_Identify(const char * name)
427 for (int i = 0; i < g_num_actuators; ++i)
429 if (strcmp(g_actuators[i].name, name) == 0)
430 return &(g_actuators[i]);