3 * @brief Implementation of Actuator related functionality
8 // Files containing GPIO and PWM definitions
14 /** Number of actuators **/
15 int g_num_actuators = 0;
17 /** Array of Actuators (global to this file) initialised by Actuator_Init **/
18 static Actuator g_actuators[ACTUATORS_MAX];
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
26 int Actuator_Add(const char * name, int user_id, SetFn set, InitFn init, CleanFn cleanup, SanityFn sanity)
28 if (++g_num_actuators > ACTUATORS_MAX)
30 Fatal("Too many sensors; Increase ACTUATORS_MAX from %d in actuator.h and recompile", ACTUATORS_MAX);
32 Actuator * a = &(g_actuators[g_num_actuators-1]);
33 a->id = g_num_actuators-1;
35 Data_Init(&(a->data_file));
37 a->set = set; // Set read function
38 a->init = init; // Set init function
40 init(name, user_id); // Call it
43 pthread_mutex_init(&(a->mutex), NULL);
45 return g_num_actuators;
50 * One off initialisation of *all* Actuators
52 #include "actuators/ledtest.h"
53 #include "actuators/filetest.h"
56 //Actuator_Add("ledtest",0, Ledtest_Set, NULL,NULL,NULL);
57 Actuator_Add("filetest", 0, Filetest_Set, Filetest_Init, Filetest_Cleanup, Filetest_Sanity);
61 * Sets the actuator to the desired mode. No checks are
62 * done to see if setting to the desired mode will conflict with
63 * the current mode - the caller must guarantee this itself.
64 * @param a The actuator whose mode is to be changed
65 * @param mode The mode to be changed to
66 * @param arg An argument specific to the mode to be set.
67 * e.g for CONTROL_START it represents the experiment name.
69 void Actuator_SetMode(Actuator * a, ControlModes mode, void *arg)
75 char filename[BUFSIZ];
76 const char *experiment_name = (const char*) arg;
78 if (snprintf(filename, BUFSIZ, "%s_a%d", experiment_name, a->id) >= BUFSIZ)
80 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
83 Log(LOGDEBUG, "Actuator %d with DataFile \"%s\"", a->id, filename);
85 Data_Open(&(a->data_file), filename);
87 case CONTROL_RESUME: //Case fallthrough; no break before
90 a->activated = true; // Don't forget this
91 a->control_changed = false;
93 ret = pthread_create(&(a->thread), NULL, Actuator_Loop, (void*)(a));
96 Fatal("Failed to create Actuator_Loop for Actuator %d", a->id);
99 Log(LOGDEBUG, "Resuming actuator %d", a->id);
103 case CONTROL_EMERGENCY: //TODO add proper case for emergency
105 a->activated = false;
106 Actuator_SetControl(a, NULL);
107 pthread_join(a->thread, NULL); // Wait for thread to exit
109 Log(LOGDEBUG, "Paused actuator %d", a->id);
114 if (a->activated) //May have been paused before
116 a->activated = false;
117 Actuator_SetControl(a, NULL);
118 pthread_join(a->thread, NULL); // Wait for thread to exit
120 Data_Close(&(a->data_file)); // Close DataFile
122 Log(LOGDEBUG, "Stopped actuator %d", a->id);
125 Fatal("Unknown control mode: %d", mode);
130 * Sets all actuators to the desired mode.
131 * @see Actuator_SetMode for more information.
132 * @param mode The mode to be changed to
133 * @param arg An argument specific to the mode to be set.
135 void Actuator_SetModeAll(ControlModes mode, void * arg)
137 for (int i = 0; i < ACTUATORS_MAX; i++)
138 Actuator_SetMode(&g_actuators[i], mode, arg);
142 * Actuator control thread
143 * @param arg - Cast to an Actuator*
144 * @returns NULL to keep pthreads happy
146 void * Actuator_Loop(void * arg)
148 Actuator * a = (Actuator*)(arg);
150 // Loop until stopped
153 pthread_mutex_lock(&(a->mutex));
154 while (!a->control_changed)
156 pthread_cond_wait(&(a->cond), &(a->mutex));
158 a->control_changed = false;
159 pthread_mutex_unlock(&(a->mutex));
163 Actuator_SetValue(a, a->control.start);
164 // Currently does discrete steps after specified time intervals
165 while (a->control.steps > 0 && a->activated)
167 usleep(1e6*(a->control.stepwait));
168 a->control.start += a->control.stepsize;
169 Actuator_SetValue(a, a->control.start);
173 usleep(1e6*(a->control.stepwait));
176 // Note that although this loop has a sleep in it which would seem to make it hard to enforce urgent shutdowns,
177 // You can call the Actuator's cleanup function immediately (and this loop should later just exit)
178 // tl;dr This function isn't/shouldn't be responsible for the emergency Actuator stuff
179 // (That should be handled by the Fatal function... at some point)
184 // Keep pthreads happy
189 * Set an Actuators control variable
190 * @param a - Actuator to control
191 * @param c - Control to set to
193 void Actuator_SetControl(Actuator * a, ActuatorControl * c)
195 pthread_mutex_lock(&(a->mutex));
198 a->control_changed = true;
199 pthread_cond_broadcast(&(a->cond));
200 pthread_mutex_unlock(&(a->mutex));
205 * Set an Actuator value
206 * @param a - The Actuator
207 * @param value - The value to set
209 void Actuator_SetValue(Actuator * a, double value)
211 if (a->sanity != NULL && !a->sanity(a->user_id, value))
214 Fatal("Insane value %lf for actuator %s", value, a->name);
216 if (!(a->set(a->user_id, value)))
218 Fatal("Failed to set actuator %s to %lf", a->name, value);
223 gettimeofday(&t, NULL);
224 // Record and save DataPoint
225 DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), value};
226 Data_Save(&(a->data_file), &d, 1);
230 * Helper: Begin Actuator response in a given format
231 * @param context - the FCGIContext
232 * @param format - Format
233 * @param id - ID of Actuator
235 void Actuator_BeginResponse(FCGIContext * context, Actuator * a, DataFormat format)
241 FCGI_BeginJSON(context, STATUS_OK);
242 FCGI_JSONLong("id", a->id);
243 FCGI_JSONLong("user_id", a->user_id); //TODO: Don't need to show this?
244 FCGI_JSONPair("name", a->name);
247 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
253 * Helper: End Actuator response in a given format
254 * @param context - the FCGIContext
255 * @param id - ID of the Actuator
256 * @param format - Format
258 void Actuator_EndResponse(FCGIContext * context, Actuator * a, DataFormat format)
273 * Handle a request for an Actuator
274 * @param context - FCGI context
275 * @param params - Parameters passed
277 void Actuator_Handler(FCGIContext * context, char * params)
280 gettimeofday(&now, NULL);
281 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
285 double start_time = 0;
286 double end_time = current_time;
290 FCGIValue values[] = {
291 {"id", &id, FCGI_INT_T},
292 {"name", &name, FCGI_STRING_T},
293 {"set", &set, FCGI_STRING_T},
294 {"start_time", &start_time, FCGI_DOUBLE_T},
295 {"end_time", &end_time, FCGI_DOUBLE_T},
296 {"format", &fmt_str, FCGI_STRING_T}
299 // enum to avoid the use of magic numbers
309 // Fill values appropriately
310 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
312 // Error occured; FCGI_RejectJSON already called
316 // Get the Actuator identified
319 if (FCGI_RECEIVED(values[NAME].flags))
321 if (FCGI_RECEIVED(values[ID].flags))
323 FCGI_RejectJSON(context, "Can't supply both id and name");
326 a = Actuator_Identify(name);
329 FCGI_RejectJSON(context, "Unknown actuator name");
334 else if (!FCGI_RECEIVED(values[ID].flags))
336 FCGI_RejectJSON(context, "No id or name supplied");
339 else if (id < 0 || id >= ACTUATORS_MAX)
341 FCGI_RejectJSON(context, "Invalid Actuator id");
346 a = &(g_actuators[id]);
350 DataFormat format = Data_GetFormat(&(values[FORMAT]));
355 if (FCGI_RECEIVED(values[SET].flags))
359 ActuatorControl c = {0.0, 0.0, 0.0, 0}; // Need to set default values (since we don't require them all)
360 // sscanf returns the number of fields successfully read...
361 int n = sscanf(set, "%lf,%lf,%lf,%d", &(c.start), &(c.stepwait), &(c.stepsize), &(c.steps)); // Set provided values in order
364 // If the user doesn't provide all 4 values, the Actuator will get set *once* using the first of the provided values
365 // (see Actuator_Loop)
366 // Not really a problem if n = 1, but maybe generate a warning for 2 <= n < 4 ?
367 Log(LOGDEBUG, "Only provided %d values (expect %d) for Actuator setting", n);
370 if (c.stepwait < 0 || c.steps < 0 || (a->sanity != NULL && !a->sanity(a->user_id, c.start)))
372 FCGI_RejectJSON(context, "Bad Actuator setting");
375 Actuator_SetControl(a, &c);
380 Actuator_BeginResponse(context, a, format);
382 FCGI_JSONPair("set", set);
385 Data_Handler(&(a->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
388 Actuator_EndResponse(context, a, format);
392 * Get the name of an Actuator given its id
393 * @param id - ID of the actuator
394 * @returns The Actuator's name
396 const char * Actuator_GetName(int id)
398 return g_actuators[id].name;
402 * Identify an Actuator from its name string
403 * @param name - The name of the Actuator
406 Actuator * Actuator_Identify(const char * name)
408 for (int i = 0; i < g_num_actuators; ++i)
410 if (strcmp(g_actuators[i].name, name) == 0)
411 return &(g_actuators[i]);