3 * @brief Implementation of sensor thread
4 * TODO: Finalise implementation
13 /** Array of sensors, initialised by Sensor_Init **/
14 static Sensor g_sensors[NUMSENSORS]; //global to this file
16 /** Array of sensor threshold structures defining the safety values of each sensor**/
17 const SensorThreshold thresholds[NUMSENSORS]= {
18 //Max Safety, Min safety, Max warning, Min warning
19 {1,-1,1,-1}, // ANALOG_TEST0
20 {500,0,499,0}, // ANALOG_TEST1
21 {5000,0,5000,0}, // ANALOG_REALTEST
22 {5,-5,4,-4}, // ANALOG_FAIL0
23 {1,0,1,0}, // DIGITAL_TEST0
24 {1,0,1,0}, // DIGITAL_TEST1
25 {1,0,1,0}, // DIGITAL_REALTEST
26 {1,0,1,0} // DIGITAL_FAIL0
29 /** Human readable names for the sensors **/
30 const char * g_sensor_names[NUMSENSORS] = {
31 "analog_test0", "analog_test1",
32 "analog_realtest", "analog_fail0",
33 "digital_test0", "digital_test1",
34 "digital_realtest", "digital_fail0"
38 * One off initialisation of *all* sensors
42 for (int i = 0; i < NUMSENSORS; ++i)
45 Data_Init(&(g_sensors[i].data_file));
46 g_sensors[i].record_data = false;
52 // GPIO1_28 used as a pulse for sampling
53 GPIO_Export(GPIO1_28);
54 // GPIO0_30 toggled during sampling
55 GPIO_Export(GPIO0_30);
59 * Sets the sensor to the desired control mode. No checks are
60 * done to see if setting to the desired mode will conflict with
61 * the current mode - the caller must guarantee this itself.
62 * @param s The sensor whose mode is to be changed
63 * @param mode The mode to be changed to
64 * @param arg An argument specific to the mode to be set.
65 * e.g for CONTROL_START it represents the experiment name.
67 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
74 char filename[BUFSIZ];
75 const char *experiment_name = (const char*) arg;
78 if (snprintf(filename, BUFSIZ, "%s_s%d", experiment_name, s->id) >= BUFSIZ)
80 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
83 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
85 Data_Open(&(s->data_file), filename);
88 s->record_data = true; // Don't forget this!
91 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
94 Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
98 case CONTROL_EMERGENCY:
100 s->record_data = false;
103 s->record_data = true;
106 s->activated = false;
107 s->record_data = false;
108 pthread_join(s->thread, NULL);
110 Data_Close(&(s->data_file)); // Close DataFile
111 s->newest_data.time_stamp = 0;
112 s->newest_data.value = 0;
115 Fatal("Unknown control mode: %d", mode);
120 * Sets all sensors to the desired mode.
121 * @see Sensor_SetMode for more information.
122 * @param mode The mode to be changed to
123 * @param arg An argument specific to the mode to be set.
125 void Sensor_SetModeAll(ControlModes mode, void * arg)
127 for (int i = 0; i < NUMSENSORS; i++)
128 Sensor_SetMode(&g_sensors[i], mode, arg);
133 * Checks the sensor data for unsafe or unexpected results
134 * @param sensor_id - The ID of the sensor
135 * @param value - The value from the sensor to test
137 void Sensor_CheckData(SensorId id, double value)
139 if( value > thresholds[id].max_error || value < thresholds[id].min_error)
141 Log(LOGERR, "Sensor %s is above or below its safety value of %f or %f\n", g_sensor_names[id],thresholds[id].max_error, thresholds[id].min_error);
142 //new function that stops actuators?
144 else if( value > thresholds[id].max_warn || value < thresholds[id].min_warn)
146 Log(LOGWARN, "Sensor %s is above or below its warning value of %f or %f\n", g_sensor_names[id],thresholds[id].max_warn, thresholds[id].min_warn);
152 * Read a DataPoint from a Sensor; block until value is read
153 * @param id - The ID of the sensor
154 * @param d - DataPoint to set
155 * @returns True if the DataPoint was different from the most recently recorded.
157 bool Sensor_Read(Sensor * s, DataPoint * d)
162 gettimeofday(&t, NULL);
163 d->time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());
165 static bool result = true;
168 // Read value based on Sensor Id
171 case ANALOG_REALTEST:
173 static bool set = false;
175 GPIO_Set(GPIO0_30, true);
176 d->value = (double)ADC_Read(ADC0); //ADC #0 on the Beaglebone
177 //Log(LOGDEBUG, "Got value %f from ADC0", d->value);
178 GPIO_Set(GPIO0_30, false);
180 GPIO_Set(GPIO1_28, set);
186 d->value = rand() % 2;
193 d->value = (double)(rand() % 100) / 100;
198 static int count = 0;
206 //d->value = (double)(rand() % 6) * -( rand() % 2) / ( rand() % 100 + 1);
207 //Gives a value between -5 and 5
210 d->value = t.tv_sec % 2;
214 d->value = (t.tv_sec+1)%2;
216 case DIGITAL_REALTEST:
218 // Can pass pin as argument, just using 20 as an example here
219 // Although since pins will be fixed, can just define it here if we need to
220 //d->value = pinRead(20); //Pin 20 on the Beaglebone
224 if( rand() % 100 > 98)
226 d->value = rand() % 2;
227 //Gives 0 or 1 or a 2 every 1/100 times
230 // Fatal("Unknown sensor id: %d", s->id);
235 // Perform sanity check based on Sensor's ID and the DataPoint
236 Sensor_CheckData(s->id, d->value);
238 // Update latest DataPoint if necessary
242 s->newest_data.time_stamp = d->time_stamp;
243 s->newest_data.value = d->value;
249 * Record data from a single Sensor; to be run in a seperate thread
250 * @param arg - Cast to Sensor* - Sensor that the thread will handle
251 * @returns NULL (void* required to use the function with pthreads)
253 void * Sensor_Loop(void * arg)
255 Sensor * s = (Sensor*)(arg);
256 Log(LOGDEBUG, "Sensor %d starts", s->id);
258 // Until the sensor is stopped, record data points
264 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
265 if (Sensor_Read(s, &d)) // If new DataPoint is read:
267 //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
268 Data_Save(&(s->data_file), &d, 1); // Record it
273 //Do something? wait?
278 // Needed to keep pthreads happy
280 Log(LOGDEBUG, "Sensor %d finished", s->id);
285 * Get a Sensor given an ID string
286 * @param id_str ID string
287 * @returns Sensor* identified by the string; NULL on error
289 Sensor * Sensor_Identify(const char * id_str)
292 // Parse string as integer
293 int id = strtol(id_str, &end, 10);
299 if (id < 0 || id >= NUMSENSORS)
303 Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
308 * Helper: Begin sensor response in a given format
309 * @param context - the FCGIContext
310 * @param id - ID of sensor
311 * @param format - Format
313 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
319 FCGI_BeginJSON(context, STATUS_OK);
320 FCGI_JSONLong("id", id);
321 FCGI_JSONPair("name", g_sensor_names[id]);
324 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
330 * Helper: End sensor response in a given format
331 * @param context - the FCGIContext
332 * @param id - ID of the sensor
333 * @param format - Format
335 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
349 * Handle a request to the sensor module
350 * @param context - The context to work in
351 * @param params - Parameters passed
353 void Sensor_Handler(FCGIContext *context, char * params)
356 gettimeofday(&now, NULL);
357 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
360 double start_time = 0;
361 double end_time = current_time;
362 const char * fmt_str;
365 FCGIValue values[] = {
366 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)},
367 {"format", &fmt_str, FCGI_STRING_T},
368 {"start_time", &start_time, FCGI_DOUBLE_T},
369 {"end_time", &end_time, FCGI_DOUBLE_T},
372 // enum to avoid the use of magic numbers
380 // Fill values appropriately
381 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
383 // Error occured; FCGI_RejectJSON already called
387 // Error checking on sensor id
388 if (id < 0 || id >= NUMSENSORS)
390 FCGI_RejectJSON(context, "Invalid sensor id");
393 Sensor * s = g_sensors+id;
395 DataFormat format = Data_GetFormat(&(values[FORMAT]));
398 Sensor_BeginResponse(context, id, format);
401 Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
404 Sensor_EndResponse(context, id, format);