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

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