3 * @brief Implementation of sensor thread
4 * TODO: Finalise implementation
13 /** Array of sensors, initialised by Sensor_Init **/
14 static Sensor g_sensors[SENSORS_MAX];
15 /** The number of sensors **/
16 int g_num_sensors = 0;
21 * Add and initialise a Sensor
22 * @param name - Human readable name of the sensor
23 * @param user_id - User identifier
24 * @param read - Function to call whenever the sensor should be read
25 * @param init - Function to call to initialise the sensor (may be NULL)
26 * @param max_error - Maximum error threshold; program will exit if this is exceeded for the sensor reading
27 * @param min_error - Minimum error threshold; program will exit if the sensor reading falls below this value
28 * @param max_warn - Maximum warning threshold; program will log warnings if the value exceeds this threshold
29 * @param min_warn - Minimum warning threshold; program will log warnings if the value falls below this threshold
30 * @returns Number of actuators added so far
32 int Sensor_Add(const char * name, int user_id, ReadFn read, InitFn init, CleanFn cleanup, SanityFn sanity)
34 if (++g_num_sensors > SENSORS_MAX)
36 Fatal("Too many sensors; Increase SENSORS_MAX from %d in sensor.h and recompile", SENSORS_MAX);
37 // We could design the program to use realloc(3)
38 // But since someone who adds a new sensor has to recompile the program anyway...
40 Sensor * s = &(g_sensors[g_num_sensors-1]);
42 s->id = g_num_sensors-1;
44 Data_Init(&(s->data_file));
46 s->read = read; // Set read function
47 s->init = init; // Set init function
49 // Start by averaging values taken over a second
53 // Set sanity function
58 if (!init(name, user_id))
59 Fatal("Couldn't init sensor %s", name);
67 * Initialise all sensors used by the program
68 * TODO: Edit this to add any extra sensors you need
69 * TODO: Edit the includes as well
71 #include "sensors/resource.h"
72 #include "sensors/strain.h"
73 #include "sensors/pressure.h"
76 Sensor_Add("cpu_stime", RESOURCE_CPU_SYS, Resource_Read, NULL, NULL, NULL);
77 Sensor_Add("cpu_utime", RESOURCE_CPU_USER, Resource_Read, NULL, NULL, NULL);
78 Sensor_Add("pressure_high0", PRES_HIGH0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
79 Sensor_Add("pressure_high1", PRES_HIGH1, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
80 Sensor_Add("pressure_low0", PRES_LOW0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
81 //Sensor_Add("../testing/count.py", 0, Piped_Read, Piped_Init, Piped_Cleanup, 1e50,-1e50,1e50,-1e50);
82 //Sensor_Add("strain0", STRAIN0, Strain_Read, Strain_Init, 5000,0,5000,0);
83 //Sensor_Add("strain1", STRAIN1, Strain_Read, Strain_Init, 5000,0,5000,0);
84 //Sensor_Add("strain2", STRAIN2, Strain_Read, Strain_Init, 5000,0,5000,0);
85 //Sensor_Add("strain3", STRAIN3, Strain_Read, Strain_Init, 5000,0,5000,0);
86 //Sensor_Add("pressure0", PRESSURE0, Pressure_Read, Pressure_Init, 5000,0,5000,0);
87 //Sensor_Add("pressure1", PRESSURE1, Pressure_Read, Pressure_Init, 5000,0,5000,0);
88 //Sensor_Add("pressure_feedback", PRESSURE_FEEDBACK, Pressure_Read, Pressure_Init, 5000,0,5000,0);
89 //Sensor_Add("enclosure", ENCLOSURE, Enclosure_Read, Enclosure_Init, 1,1,1,1);
90 //Sensor_Add("dilatometer", DILATOMETER, Dilatometer_Read, Dilatometer_Init, -1,-1,-1,-1);
98 for (int i = 0; i < g_num_sensors; ++i)
100 Sensor * s = g_sensors+i;
101 if (s->cleanup != NULL)
102 s->cleanup(s->user_id);
107 * Sets the sensor to the desired control mode. No checks are
108 * done to see if setting to the desired mode will conflict with
109 * the current mode - the caller must guarantee this itself.
110 * @param s The sensor whose mode is to be changed
111 * @param mode The mode to be changed to
112 * @param arg An argument specific to the mode to be set.
113 * e.g for CONTROL_START it represents the experiment name.
115 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
122 char filename[BUFSIZ];
123 const char *experiment_path = (const char*) arg;
126 ret = snprintf(filename, BUFSIZ, "%s/sensor_%d", experiment_path, s->id);
130 Fatal("Experiment path \"%s\" too long (%d, limit %d)",
131 experiment_path, ret, BUFSIZ);
134 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
136 Data_Open(&(s->data_file), filename);
138 case CONTROL_RESUME: //Case fallthrough, no break before
141 s->activated = true; // Don't forget this!
144 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
147 Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
150 Log(LOGDEBUG, "Resuming sensor %d", s->id);
154 case CONTROL_EMERGENCY:
156 s->activated = false;
157 pthread_join(s->thread, NULL);
158 Log(LOGDEBUG, "Paused sensor %d", s->id);
162 if (s->activated) //May have been paused before
164 s->activated = false;
165 pthread_join(s->thread, NULL);
168 Data_Close(&(s->data_file)); // Close DataFile
169 Log(LOGDEBUG, "Stopped sensor %d", s->id);
172 Fatal("Unknown control mode: %d", mode);
177 * Sets all sensors to the desired mode.
178 * @see Sensor_SetMode for more information.
179 * @param mode The mode to be changed to
180 * @param arg An argument specific to the mode to be set.
182 void Sensor_SetModeAll(ControlModes mode, void * arg)
184 for (int i = 0; i < g_num_sensors; i++)
185 Sensor_SetMode(&g_sensors[i], mode, arg);
190 * Record data from a single Sensor; to be run in a seperate thread
191 * @param arg - Cast to Sensor* - Sensor that the thread will handle
192 * @returns NULL (void* required to use the function with pthreads)
194 void * Sensor_Loop(void * arg)
196 Sensor * s = (Sensor*)(arg);
197 Log(LOGDEBUG, "Sensor %d starts", s->id);
199 // Until the sensor is stopped, record data points
204 bool success = s->read(s->user_id, &(d.value));
207 gettimeofday(&t, NULL);
208 d.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());
212 if (s->sanity != NULL)
214 if (!s->sanity(s->user_id, d.value))
216 Fatal("Sensor %s (%d,%d) reads unsafe value", s->name, s->id, s->user_id);
219 Data_Save(&(s->data_file), &d, 1); // Record it
222 Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id);
224 usleep(s->sample_us);
227 // Needed to keep pthreads happy
228 Log(LOGDEBUG, "Sensor %s (%d,%d) finished", s->name,s->id,s->user_id);
233 * Get a Sensor given its name
234 * @returns Sensor with the given name, NULL if there isn't one
236 Sensor * Sensor_Identify(const char * name)
238 for (int i = 0; i < g_num_sensors; ++i)
240 if (strcmp(g_sensors[i].name, name) == 0)
241 return &(g_sensors[i]);
247 * Helper: Begin sensor response in a given format
248 * @param context - the FCGIContext
249 * @param id - ID of sensor
250 * @param format - Format
252 void Sensor_BeginResponse(FCGIContext * context, Sensor * s, DataFormat format)
258 FCGI_BeginJSON(context, STATUS_OK);
259 FCGI_JSONLong("id", s->id);
260 FCGI_JSONLong("user_id", s->user_id); //NOTE: Might not want to expose this?
261 FCGI_JSONPair("name", s->name);
264 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
270 * Helper: End sensor response in a given format
271 * @param context - the FCGIContext
272 * @param id - ID of the sensor
273 * @param format - Format
275 void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format)
289 * Handle a request to the sensor module
290 * @param context - The context to work in
291 * @param params - Parameters passed
293 void Sensor_Handler(FCGIContext *context, char * params)
296 gettimeofday(&now, NULL);
297 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
299 const char * name = "";
300 double start_time = 0;
301 double end_time = current_time;
302 const char * fmt_str;
306 FCGIValue values[] = {
307 {"id", &id, FCGI_INT_T},
308 {"name", &name, FCGI_STRING_T},
309 {"format", &fmt_str, FCGI_STRING_T},
310 {"start_time", &start_time, FCGI_DOUBLE_T},
311 {"end_time", &end_time, FCGI_DOUBLE_T},
312 {"sample_s", &sample_s, FCGI_DOUBLE_T}
315 // enum to avoid the use of magic numbers
325 // Fill values appropriately
326 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
328 // Error occured; FCGI_RejectJSON already called
333 if (FCGI_RECEIVED(values[NAME].flags))
335 if (FCGI_RECEIVED(values[ID].flags))
337 FCGI_RejectJSON(context, "Can't supply both sensor id and name");
340 s = Sensor_Identify(name);
343 FCGI_RejectJSON(context, "Unknown sensor name");
347 else if (!FCGI_RECEIVED(values[ID].flags))
349 FCGI_RejectJSON(context, "No sensor id or name supplied");
352 else if (id < 0 || id >= g_num_sensors)
354 FCGI_RejectJSON(context, "Invalid sensor id");
359 s = &(g_sensors[id]);
362 // Adjust sample rate if necessary
363 if (FCGI_RECEIVED(values[SAMPLE_S].flags))
367 FCGI_RejectJSON(context, "Negative sampling speed!");
370 s->sample_us = 1e6*sample_s;
374 DataFormat format = Data_GetFormat(&(values[FORMAT]));
377 Sensor_BeginResponse(context, s, format);
380 Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
383 Sensor_EndResponse(context, s, format);
388 * Get the Name of a Sensor
389 * @param id - ID number
391 const char * Sensor_GetName(int id)
393 return g_sensors[id].name;