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

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