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, double initial_value)
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
42 pthread_mutex_init(&(a->mutex), NULL);
46 if (!init(name, user_id))
47 Fatal("Couldn't initialise actuator %s", name);
50 Actuator_SetValue(a, initial_value, false);
52 return g_num_actuators;
57 * One off initialisation of *all* Actuators
59 #include "actuators/ledtest.h"
60 #include "actuators/filetest.h"
63 //Actuator_Add("ledtest",0, Ledtest_Set, NULL,NULL,NULL);
64 Actuator_Add("filetest", 0, Filetest_Set, Filetest_Init, Filetest_Cleanup, Filetest_Sanity, 0);
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.
76 void Actuator_SetMode(Actuator * a, ControlModes mode, void *arg)
82 char filename[BUFSIZ];
83 const char *experiment_name = (const char*) arg;
85 if (snprintf(filename, BUFSIZ, "%s_a%d", experiment_name, a->id) >= BUFSIZ)
87 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
90 Log(LOGDEBUG, "Actuator %d with DataFile \"%s\"", a->id, filename);
92 Data_Open(&(a->data_file), filename);
94 case CONTROL_RESUME: //Case fallthrough; no break before
97 a->activated = true; // Don't forget this
98 a->control_changed = false;
100 ret = pthread_create(&(a->thread), NULL, Actuator_Loop, (void*)(a));
103 Fatal("Failed to create Actuator_Loop for Actuator %d", a->id);
106 Log(LOGDEBUG, "Resuming actuator %d", a->id);
110 case CONTROL_EMERGENCY: //TODO add proper case for emergency
112 a->activated = false;
113 Actuator_SetControl(a, NULL);
114 pthread_join(a->thread, NULL); // Wait for thread to exit
116 Log(LOGDEBUG, "Paused actuator %d", a->id);
121 if (a->activated) //May have been paused before
123 a->activated = false;
124 Actuator_SetControl(a, NULL);
125 pthread_join(a->thread, NULL); // Wait for thread to exit
127 Data_Close(&(a->data_file)); // Close DataFile
129 Log(LOGDEBUG, "Stopped actuator %d", a->id);
132 Fatal("Unknown control mode: %d", mode);
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.
142 void Actuator_SetModeAll(ControlModes mode, void * arg)
144 for (int i = 0; i < ACTUATORS_MAX; i++)
145 Actuator_SetMode(&g_actuators[i], mode, arg);
149 * Actuator control thread
150 * @param arg - Cast to an Actuator*
151 * @returns NULL to keep pthreads happy
153 void * Actuator_Loop(void * arg)
155 Actuator * a = (Actuator*)(arg);
157 // Loop until stopped
160 pthread_mutex_lock(&(a->mutex));
161 while (!a->control_changed)
163 pthread_cond_wait(&(a->cond), &(a->mutex));
165 a->control_changed = false;
166 pthread_mutex_unlock(&(a->mutex));
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)
174 usleep(1e6*(a->control.stepwait));
175 a->control.start += a->control.stepsize;
176 Actuator_SetValue(a, a->control.start, true);
180 if (a->control_changed)
182 usleep(1e6*(a->control.stepwait));
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)
193 // Keep pthreads happy
198 * Set an Actuators control variable
199 * @param a - Actuator to control
200 * @param c - Control to set to
202 void Actuator_SetControl(Actuator * a, ActuatorControl * c)
204 pthread_mutex_lock(&(a->mutex));
207 a->control_changed = true;
208 pthread_cond_broadcast(&(a->cond));
209 pthread_mutex_unlock(&(a->mutex));
214 * Set an Actuator value
215 * @param a - The Actuator
216 * @param value - The value to set
218 void Actuator_SetValue(Actuator * a, double value, bool record)
220 if (a->sanity != NULL && !a->sanity(a->user_id, value))
223 Log(LOGERR,"Insane value %lf for actuator %s", value, a->name);
226 if (!(a->set(a->user_id, value)))
228 Fatal("Failed to set actuator %s to %lf", a->name, value);
233 gettimeofday(&t, NULL);
234 DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), a->last_setting.value};
235 // Record value change
238 d.time_stamp -= 1e-6;
239 Data_Save(&(a->data_file), &d, 1);
241 d.time_stamp += 1e-6;
242 Data_Save(&(a->data_file), &d, 1);
248 * Helper: Begin Actuator response in a given format
249 * @param context - the FCGIContext
250 * @param format - Format
251 * @param id - ID of Actuator
253 void Actuator_BeginResponse(FCGIContext * context, Actuator * a, DataFormat format)
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);
265 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
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
276 void Actuator_EndResponse(FCGIContext * context, Actuator * a, DataFormat format)
291 * Handle a request for an Actuator
292 * @param context - FCGI context
293 * @param params - Parameters passed
295 void Actuator_Handler(FCGIContext * context, char * params)
298 gettimeofday(&now, NULL);
299 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
303 double start_time = 0;
304 double end_time = current_time;
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}
317 // enum to avoid the use of magic numbers
327 // Fill values appropriately
328 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
330 // Error occured; FCGI_RejectJSON already called
334 // Get the Actuator identified
337 if (FCGI_RECEIVED(values[NAME].flags))
339 if (FCGI_RECEIVED(values[ID].flags))
341 FCGI_RejectJSON(context, "Can't supply both id and name");
344 a = Actuator_Identify(name);
347 FCGI_RejectJSON(context, "Unknown actuator name");
352 else if (!FCGI_RECEIVED(values[ID].flags))
354 FCGI_RejectJSON(context, "No id or name supplied");
357 else if (id < 0 || id >= g_num_actuators)
359 FCGI_RejectJSON(context, "Invalid Actuator id");
364 a = &(g_actuators[id]);
368 DataFormat format = Data_GetFormat(&(values[FORMAT]));
373 if (FCGI_RECEIVED(values[SET].flags))
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
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);
388 if (c.stepwait < 0 || c.steps < 0 || (a->sanity != NULL && !a->sanity(a->user_id, c.start)))
390 FCGI_RejectJSON(context, "Bad Actuator setting");
393 Actuator_SetControl(a, &c);
397 Actuator_BeginResponse(context, a, format);
399 FCGI_JSONPair("set", set);
402 Data_Handler(&(a->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
405 Actuator_EndResponse(context, a, format);
409 * Get the name of an Actuator given its id
410 * @param id - ID of the actuator
411 * @returns The Actuator's name
413 const char * Actuator_GetName(int id)
415 return g_actuators[id].name;
419 * Identify an Actuator from its name string
420 * @param name - The name of the Actuator
423 Actuator * Actuator_Identify(const char * name)
425 for (int i = 0; i < g_num_actuators; ++i)
427 if (strcmp(g_actuators[i].name, name) == 0)
428 return &(g_actuators[i]);