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

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