Merge branch 'master' of https://github.com/szmoore/MCTX3420.git
[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 /** Array of Actuators (global to this file) initialised by Actuator_Init **/
13 static Actuator g_actuators[NUMACTUATORS];
14
15 /** Human readable names for the Actuators **/
16 const char * g_actuator_names[NUMACTUATORS] = { 
17         "actuator_test0", "gpio1_16", "EHRPWM0A_duty@60Hz"
18 };
19
20 /**
21  * One off initialisation of *all* Actuators
22  */
23 void Actuator_Init()
24 {
25         for (int i = 0; i < NUMACTUATORS; ++i)
26         {
27                 g_actuators[i].id = i;
28                 Data_Init(&(g_actuators[i].data_file));
29                 pthread_mutex_init(&(g_actuators[i].mutex), NULL);
30         }
31
32         // Initialise pins used
33         GPIO_Export(GPIO1_16);
34         PWM_Export(EHRPWM0A);
35         
36 }
37
38 /**
39  * Sets the actuator to the desired mode. No checks are
40  * done to see if setting to the desired mode will conflict with
41  * the current mode - the caller must guarantee this itself.
42  * @param a The actuator whose mode is to be changed
43  * @param mode The mode to be changed to
44  * @param arg An argument specific to the mode to be set. 
45  *            e.g for CONTROL_START it represents the experiment name.
46  */
47 void Actuator_SetMode(Actuator * a, ControlModes mode, void *arg)
48 {
49         switch (mode)
50         {
51                 case CONTROL_START:
52                         {
53                                 char filename[BUFSIZ];
54                                 const char *experiment_name = (const char*) arg;
55
56                                 if (snprintf(filename, BUFSIZ, "%s_a%d", experiment_name, a->id) >= BUFSIZ)
57                                 {
58                                         Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
59                                 }
60
61                                 Log(LOGDEBUG, "Actuator %d with DataFile \"%s\"", a->id, filename);
62                                 // Open DataFile
63                                 Data_Open(&(a->data_file), filename);
64                         } 
65                 case CONTROL_RESUME:  //Case fallthrough; no break before
66                         {
67                                 int ret;
68                                 a->activated = true; // Don't forget this
69                                 a->control_changed = false;
70
71                                 ret = pthread_create(&(a->thread), NULL, Actuator_Loop, (void*)(a));
72                                 if (ret != 0)
73                                 {
74                                         Fatal("Failed to create Actuator_Loop for Actuator %d", a->id);
75                                 }
76
77                                 Log(LOGDEBUG, "Resuming actuator %d", a->id);
78                         }
79                 break;
80
81                 case CONTROL_EMERGENCY: //TODO add proper case for emergency
82                 case CONTROL_PAUSE:
83                         a->activated = false;
84                         Actuator_SetControl(a, NULL);
85                         pthread_join(a->thread, NULL); // Wait for thread to exit
86
87                         Log(LOGDEBUG, "Paused actuator %d", a->id);
88                 break;
89
90                 break;
91                 case CONTROL_STOP:
92                         if (a->activated) //May have been paused before
93                         {
94                                 a->activated = false;
95                                 Actuator_SetControl(a, NULL);
96                                 pthread_join(a->thread, NULL); // Wait for thread to exit       
97                         }
98                         Data_Close(&(a->data_file)); // Close DataFile
99                         
100                         Log(LOGDEBUG, "Stopped actuator %d", a->id);
101                 break;
102                 default:
103                         Fatal("Unknown control mode: %d", mode);
104         }
105 }
106
107 /**
108  * Sets all actuators to the desired mode. 
109  * @see Actuator_SetMode for more information.
110  * @param mode The mode to be changed to
111  * @param arg An argument specific to the mode to be set.
112  */
113 void Actuator_SetModeAll(ControlModes mode, void * arg)
114 {
115         for (int i = 0; i < NUMACTUATORS; i++)
116                 Actuator_SetMode(&g_actuators[i], mode, arg);
117 }
118
119 /**
120  * Actuator control thread
121  * @param arg - Cast to an Actuator*
122  * @returns NULL to keep pthreads happy
123  */
124 void * Actuator_Loop(void * arg)
125 {
126         Actuator * a = (Actuator*)(arg);
127         
128         // Loop until stopped
129         while (a->activated)
130         {
131                 pthread_mutex_lock(&(a->mutex));
132                 while (!a->control_changed)
133                 {
134                         pthread_cond_wait(&(a->cond), &(a->mutex));
135                 }
136                 a->control_changed = false;
137                 pthread_mutex_unlock(&(a->mutex));
138                 if (!a->activated)
139                         break;
140
141                 Actuator_SetValue(a, a->control.value);
142         }
143
144         //TODO: Cleanup?
145         
146         // Keep pthreads happy
147         return NULL;
148 }
149
150 /**
151  * Set an Actuators control variable
152  * @param a - Actuator to control 
153  * @param c - Control to set to
154  */
155 void Actuator_SetControl(Actuator * a, ActuatorControl * c)
156 {
157         pthread_mutex_lock(&(a->mutex));
158         if (c != NULL)
159                 a->control = *c;
160         a->control_changed = true;
161         pthread_cond_broadcast(&(a->cond));
162         pthread_mutex_unlock(&(a->mutex));
163         
164 }
165
166 /**
167  * Set an Actuator value
168  * @param a - The Actuator
169  * @param value - The value to set
170  */
171 void Actuator_SetValue(Actuator * a, double value)
172 {
173         // Set time stamp
174         struct timeval t;
175         gettimeofday(&t, NULL);
176
177         DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), value};
178         //TODO: Set actuator
179         switch (a->id)
180         {
181                 case ACTUATOR_TEST0: 
182                         {
183                         // Onboard LEDs test actuator
184                                 FILE *led_handle = NULL;        //code reference: http://learnbuildshare.wordpress.com/2013/05/19/beaglebone-black-controlling-user-leds-using-c/
185                                 const char *led_format = "/sys/class/leds/beaglebone:green:usr%d/brightness";
186                                 char buf[50];
187                                 bool turn_on = value;
188
189                                 for (int i = 0; i < 4; i++) 
190                                 {
191                                         snprintf(buf, 50, led_format, i);
192                                         if ((led_handle = fopen(buf, "w")) != NULL)
193                                         {
194                                                 if (turn_on)
195                                                         fwrite("1", sizeof(char), 1, led_handle);
196                                                 else
197                                                         fwrite("0", sizeof(char), 1, led_handle);
198                                                 fclose(led_handle);
199                                         }
200                                         else
201                                                 Log(LOGDEBUG, "LED fopen failed: %s", strerror(errno)); 
202                                 }
203                         }
204                         break;
205                 case ACTUATOR_TEST1:
206                         GPIO_Set(GPIO1_16, (bool)(value));
207                         break;
208                 case ACTUATOR_TEST2:
209                 {
210                         // PWM analogue actuator (currently generates one PWM signal with first PWM module)
211                         static long freq = 16666666; // This is 60Hz
212                         PWM_Set(EHRPWM0A, true, freq, value * freq); // Set the duty cycle
213                         break;
214                 }
215         }
216
217         Log(LOGDEBUG, "Actuator %s set to %f", g_actuator_names[a->id], value);
218
219         // Record the value
220         Data_Save(&(a->data_file), &d, 1);
221 }
222
223 /**
224  * Helper: Begin Actuator response in a given format
225  * @param context - the FCGIContext
226  * @param format - Format
227  * @param id - ID of Actuator
228  */
229 void Actuator_BeginResponse(FCGIContext * context, ActuatorId id, DataFormat format)
230 {
231         // Begin response
232         switch (format)
233         {
234                 case JSON:
235                         FCGI_BeginJSON(context, STATUS_OK);
236                         FCGI_JSONLong("id", id);
237                         FCGI_JSONPair("name", g_actuator_names[id]);
238                         break;
239                 default:
240                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
241                         break;
242         }
243 }
244
245 /**
246  * Helper: End Actuator response in a given format
247  * @param context - the FCGIContext
248  * @param id - ID of the Actuator
249  * @param format - Format
250  */
251 void Actuator_EndResponse(FCGIContext * context, ActuatorId id, DataFormat format)
252 {
253         // End response
254         switch (format)
255         {
256                 case JSON:
257                         FCGI_EndJSON();
258                         break;
259                 default:
260                         break;
261         }
262 }
263
264
265 /**
266  * Handle a request for an Actuator
267  * @param context - FCGI context
268  * @param params - Parameters passed
269  */
270 void Actuator_Handler(FCGIContext * context, char * params)
271 {
272         struct timeval now;
273         gettimeofday(&now, NULL);
274         double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
275         int id = 0;
276         double set = 0;
277         double start_time = 0;
278         double end_time = current_time;
279         char * fmt_str;
280
281         // key/value pairs
282         FCGIValue values[] = {
283                 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)}, 
284                 {"set", &set, FCGI_DOUBLE_T},
285                 {"start_time", &start_time, FCGI_DOUBLE_T},
286                 {"end_time", &end_time, FCGI_DOUBLE_T},
287                 {"format", &fmt_str, FCGI_STRING_T}
288         };
289
290         // enum to avoid the use of magic numbers
291         typedef enum {
292                 ID,
293                 SET,
294                 START_TIME,
295                 END_TIME,
296                 FORMAT
297         } ActuatorParams;
298         
299         // Fill values appropriately
300         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
301         {
302                 // Error occured; FCGI_RejectJSON already called
303                 return;
304         }       
305
306         // Get the Actuator identified
307         Actuator * a = NULL;
308         if (id < 0 || id >= NUMACTUATORS)
309         {
310                 FCGI_RejectJSON(context, "Invalid Actuator id");
311                 return;
312         }
313         
314         a = g_actuators+id;
315
316         DataFormat format = Data_GetFormat(&(values[FORMAT]));
317
318         // Begin response
319         Actuator_BeginResponse(context, id, format);
320
321         // Set?
322         if (FCGI_RECEIVED(values[SET].flags))
323         {
324                 if (format == JSON)
325                         FCGI_JSONDouble("set", set);
326         
327                 ActuatorControl c;
328                 c.value = set;
329
330                 Actuator_SetControl(a, &c);
331         }
332
333         // Print Data
334         Data_Handler(&(a->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
335         
336         // Finish response
337         Actuator_EndResponse(context, id, format);
338 }

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