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

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