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

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