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
50 DOUBLE_TO_TIMEVAL(1e-3, &(s->sample_time));
54 // Set sanity function
59 if (!init(name, user_id))
60 Fatal("Couldn't init sensor %s", name);
63 s->current_data.time_stamp = 0;
64 s->current_data.value = 0;
65 s->averaged_data.time_stamp = 0;
66 s->averaged_data.value = 0;
71 * Initialise all sensors used by the program
72 * TODO: Edit this to add any extra sensors you need
73 * TODO: Edit the includes as well
75 #include "sensors/resource.h"
76 #include "sensors/strain.h"
77 #include "sensors/pressure.h"
80 //Sensor_Add("cpu_stime", RESOURCE_CPU_SYS, Resource_Read, NULL, NULL, NULL);
81 //Sensor_Add("cpu_utime", RESOURCE_CPU_USER, Resource_Read, NULL, NULL, NULL);
82 Sensor_Add("pressure_high0", PRES_HIGH0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
83 Sensor_Add("pressure_high1", PRES_HIGH1, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
84 Sensor_Add("pressure_low0", PRES_LOW0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
85 //Sensor_Add("../testing/count.py", 0, Piped_Read, Piped_Init, Piped_Cleanup, 1e50,-1e50,1e50,-1e50);
86 Sensor_Add("strain0", STRAIN0, Strain_Read, Strain_Init, Strain_Cleanup, Strain_Sanity);
87 Sensor_Add("strain1", STRAIN1, Strain_Read, Strain_Init, Strain_Cleanup, Strain_Sanity);
88 Sensor_Add("strain2", STRAIN2, Strain_Read, Strain_Init, Strain_Cleanup, Strain_Sanity);
89 Sensor_Add("strain3", STRAIN3, Strain_Read, Strain_Init, Strain_Cleanup, Strain_Sanity);
90 //Sensor_Add("pressure0", PRESSURE0, Pressure_Read, Pressure_Init, 5000,0,5000,0);
91 //Sensor_Add("pressure1", PRESSURE1, Pressure_Read, Pressure_Init, 5000,0,5000,0);
92 //Sensor_Add("pressure_feedback", PRESSURE_FEEDBACK, Pressure_Read, Pressure_Init, 5000,0,5000,0);
93 //Sensor_Add("enclosure", ENCLOSURE, Enclosure_Read, Enclosure_Init, 1,1,1,1);
94 //Sensor_Add("dilatometer", DILATOMETER, Dilatometer_Read, Dilatometer_Init, -1,-1,-1,-1);
100 void Sensor_Cleanup()
102 for (int i = 0; i < g_num_sensors; ++i)
104 Sensor * s = g_sensors+i;
105 if (s->cleanup != NULL)
106 s->cleanup(s->user_id);
112 * Sets the sensor to the desired control mode. No checks are
113 * done to see if setting to the desired mode will conflict with
114 * the current mode - the caller must guarantee this itself.
115 * @param s The sensor whose mode is to be changed
116 * @param mode The mode to be changed to
117 * @param arg An argument specific to the mode to be set.
118 * e.g for CONTROL_START it represents the experiment name.
120 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
127 char filename[BUFSIZ];
128 const char *experiment_path = (const char*) arg;
131 ret = snprintf(filename, BUFSIZ, "%s/sensor_%d", experiment_path, s->id);
135 Fatal("Experiment path \"%s\" too long (%d, limit %d)",
136 experiment_path, ret, BUFSIZ);
139 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
141 Data_Open(&(s->data_file), filename);
143 case CONTROL_RESUME: //Case fallthrough, no break before
146 s->activated = true; // Don't forget this!
149 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
152 Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
155 Log(LOGDEBUG, "Resuming sensor %d", s->id);
159 case CONTROL_EMERGENCY:
161 s->activated = false;
162 pthread_join(s->thread, NULL);
163 Log(LOGDEBUG, "Paused sensor %d", s->id);
167 if (s->activated) //May have been paused before
169 s->activated = false;
170 pthread_join(s->thread, NULL);
173 Data_Close(&(s->data_file)); // Close DataFile
174 Log(LOGDEBUG, "Stopped sensor %d", s->id);
177 Fatal("Unknown control mode: %d", mode);
182 * Sets all sensors to the desired mode.
183 * @see Sensor_SetMode for more information.
184 * @param mode The mode to be changed to
185 * @param arg An argument specific to the mode to be set.
187 void Sensor_SetModeAll(ControlModes mode, void * arg)
189 if (mode == CONTROL_START)
191 for (int i = 0; i < g_num_sensors; i++)
192 Sensor_SetMode(&g_sensors[i], mode, arg);
193 if (mode == CONTROL_STOP)
199 * Record data from a single Sensor; to be run in a seperate thread
200 * @param arg - Cast to Sensor* - Sensor that the thread will handle
201 * @returns NULL (void* required to use the function with pthreads)
203 void * Sensor_Loop(void * arg)
205 Sensor * s = (Sensor*)(arg);
206 Log(LOGDEBUG, "Sensor %d starts", s->id);
208 // Until the sensor is stopped, record data points
212 bool success = s->read(s->user_id, &(s->current_data.value));
215 clock_gettime(CLOCK_MONOTONIC, &t);
216 s->current_data.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());
220 if (s->sanity != NULL)
222 if (!s->sanity(s->user_id, s->current_data.value))
224 Fatal("Sensor %s (%d,%d) reads unsafe value", s->name, s->id, s->user_id);
227 s->averaged_data.time_stamp += s->current_data.time_stamp;
228 s->averaged_data.value = s->current_data.value;
230 if (++(s->num_read) >= s->averages)
232 s->averaged_data.time_stamp /= s->averages;
233 s->averaged_data.value /= s->averages;
234 Data_Save(&(s->data_file), &(s->averaged_data), 1); // Record it
236 s->averaged_data.time_stamp = 0;
237 s->averaged_data.value = 0;
242 // Silence because strain sensors fail ~50% of the time :S
243 //Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id);
247 clock_nanosleep(CLOCK_MONOTONIC, 0, &(s->sample_time), NULL);
251 // Needed to keep pthreads happy
252 Log(LOGDEBUG, "Sensor %s (%d,%d) finished", s->name,s->id,s->user_id);
257 * Get a Sensor given its name
258 * @returns Sensor with the given name, NULL if there isn't one
260 Sensor * Sensor_Identify(const char * name)
262 for (int i = 0; i < g_num_sensors; ++i)
264 if (strcmp(g_sensors[i].name, name) == 0)
265 return &(g_sensors[i]);
271 * Helper: Begin sensor response in a given format
272 * @param context - the FCGIContext
273 * @param id - ID of sensor
274 * @param format - Format
276 void Sensor_BeginResponse(FCGIContext * context, Sensor * s, DataFormat format)
282 FCGI_BeginJSON(context, STATUS_OK);
283 FCGI_JSONLong("id", s->id);
284 FCGI_JSONLong("user_id", s->user_id); //NOTE: Might not want to expose this?
285 FCGI_JSONPair("name", s->name);
288 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
294 * Helper: End sensor response in a given format
295 * @param context - the FCGIContext
296 * @param id - ID of the sensor
297 * @param format - Format
299 void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format)
313 * Handle a request to the sensor module
314 * @param context - The context to work in
315 * @param params - Parameters passed
317 void Sensor_Handler(FCGIContext *context, char * params)
320 clock_gettime(CLOCK_MONOTONIC, &now);
321 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
323 const char * name = "";
324 double start_time = 0;
325 double end_time = current_time;
326 const char * fmt_str;
330 FCGIValue values[] = {
331 {"id", &id, FCGI_INT_T},
332 {"name", &name, FCGI_STRING_T},
333 {"format", &fmt_str, FCGI_STRING_T},
334 {"start_time", &start_time, FCGI_DOUBLE_T},
335 {"end_time", &end_time, FCGI_DOUBLE_T},
336 {"sample_s", &sample_s, FCGI_DOUBLE_T}
339 // enum to avoid the use of magic numbers
349 // Fill values appropriately
350 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
352 // Error occured; FCGI_RejectJSON already called
357 if (FCGI_RECEIVED(values[NAME].flags))
359 if (FCGI_RECEIVED(values[ID].flags))
361 FCGI_RejectJSON(context, "Can't supply both sensor id and name");
364 s = Sensor_Identify(name);
367 FCGI_RejectJSON(context, "Unknown sensor name");
371 else if (!FCGI_RECEIVED(values[ID].flags))
373 FCGI_RejectJSON(context, "No sensor id or name supplied");
376 else if (id < 0 || id >= g_num_sensors)
378 FCGI_RejectJSON(context, "Invalid sensor id");
383 s = &(g_sensors[id]);
386 // Adjust sample rate if necessary
387 if (FCGI_RECEIVED(values[SAMPLE_S].flags))
391 FCGI_RejectJSON(context, "Negative sampling speed!");
394 DOUBLE_TO_TIMEVAL(sample_s, &(s->sample_time));
398 DataFormat format = Data_GetFormat(&(values[FORMAT]));
401 Sensor_BeginResponse(context, s, format);
404 Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
407 Sensor_EndResponse(context, s, format);
412 * Get the Name of a Sensor
413 * @param id - ID number
415 const char * Sensor_GetName(int id)
417 return g_sensors[id].name;
420 DataPoint Sensor_LastData(int id)
422 Sensor * s = &(g_sensors[id]);
423 return s->current_data;