3 * @brief Implementation of sensor thread
4 * TODO: Finalise implementation
12 /** Array of sensors, initialised by Sensor_Init **/
13 static Sensor g_sensors[NUMSENSORS]; //global to this file
14 const char * g_sensor_names[NUMSENSORS] = {
15 "analog_test0", "analog_test1",
16 "digital_test0", "digital_test1"
20 * Read a data value from a sensor; block until value is read
21 * @param sensor_id - The ID of the sensor
22 * @param d - DataPoint to set
23 * @returns NULL for digital sensors when data is unchanged, otherwise d
25 DataPoint * GetData(SensorId sensor_id, DataPoint * d)
27 // switch based on the sensor_id at the moment for testing;
28 // might be able to just directly access ADC from sensor_id?
29 //TODO: Implement for real sensors
32 //TODO: We should ensure the time is *never* allowed to change on the server if we use gettimeofday
33 // Another way people might think of getting the time is to count CPU cycles with clock()
34 // But this will not work because a) CPU clock speed may change on some devices (RPi?) and b) It counts cycles used by all threads
37 gettimeofday(&t, NULL);
38 d->time_stamp = (t.tv_sec - g_options.start_time.tv_sec) + 1e-6*(t.tv_usec - g_options.start_time.tv_usec);
41 //d->time_stamp.tv_sec -= g_options.start_time.tv_sec;
42 //d->time_stamp.tv_usec -= g_options.start_time.tv_usec;
48 //CheckSensor( sensor_id, *sensor value*);
55 d->value = (double)(rand() % 100) / 100;
58 //TODO: For digital sensors, consider only updating when sensor is actually changed
60 d->value = t.tv_sec % 2;
63 d->value = (t.tv_sec+1)%2;
66 Fatal("Unknown sensor id: %d", sensor_id);
69 usleep(100000); // simulate delay in sensor polling
75 * Checks the sensor data for unsafe or unexpected results
76 * @param sensor_id - The ID of the sensor
79 void CheckSensor( SensorId sensor_id)
85 if( *sensor value* > ANALOG_TEST0_SAFETY)
87 LogEx(LOGERR, GetData, Sensor analog_test0 is above the safe value);
88 //new log function that stops actuators?
90 //Also include a warning level?
91 else if( *sensor value* > ANALOG_TEST0_WARN)
93 LogEx(LOGWARN, GetData, Sensor analog_test0);
104 * @param s - Sensor to destroy
106 void Destroy(Sensor * s)
108 // Maybe move the binary file into long term file storage?
115 * Initialise a sensor
116 * @param s - Sensor to initialise
118 void Init(Sensor * s, int id)
122 s->points_written = 0;
125 #define FILENAMESIZE 3
126 char filename[FILENAMESIZE];
127 if (s->id >= pow(10, FILENAMESIZE))
129 Fatal("Too many sensors! FILENAMESIZE is %d; increase it and recompile.", FILENAMESIZE);
132 pthread_mutex_init(&(s->mutex), NULL);
134 sprintf(filename, "%d", s->id);
135 unlink(filename); //TODO: Move old files somewhere
137 s->file = fopen(filename, "a+b"); // open binary file
138 Log(LOGDEBUG, "Initialised sensor %d; binary file is \"%s\"", id, filename);
143 * Run the main sensor polling loop
144 * @param arg - Cast to Sensor* - Sensor that the thread will handle
145 * @returns NULL (void* required to use the function with pthreads)
147 void * Sensor_Main(void * arg)
149 Sensor * s = (Sensor*)(arg);
151 while (Thread_Runstate() == RUNNING) //TODO: Exit condition
153 // The sensor will write data to a buffer until it is full
154 // Then it will open a file and dump the buffer to the end of it.
157 // The reason I've added the buffer is because locks are expensive
158 // But maybe it's better to just write data straight to the file
159 // I'd like to do some tests by changing SENSOR_DATABUFSIZ
161 while (s->write_index < SENSOR_DATABUFSIZ)
163 DataPoint * d = &(s->buffer[s->write_index]);
164 if (GetData(s->id, d) == NULL)
166 Fatal("Error collecting data");
171 //Log(LOGDEBUG, "Filled buffer");
173 // CRITICAL SECTION (no threads should be able to read/write the file at the same time)
174 pthread_mutex_lock(&(s->mutex));
175 //TODO: Valgrind complains about this fseek: "Syscall param write(buf) points to uninitialised byte(s)"
176 // Not sure why, but we should find out and fix it.
177 fseek(s->file, 0, SEEK_END);
178 int amount_written = fwrite(s->buffer, sizeof(DataPoint), SENSOR_DATABUFSIZ, s->file);
179 if (amount_written != SENSOR_DATABUFSIZ)
181 Fatal("Wrote %d data points and expected to write %d to \"%s\" - %s", amount_written, SENSOR_DATABUFSIZ, strerror(errno));
183 s->points_written += amount_written;
184 //Log(LOGDEBUG, "Wrote %d data points for sensor %d", amount_written, s->id);
185 pthread_mutex_unlock(&(s->mutex));
186 // End of critical section
188 s->write_index = 0; // reset position in buffer
191 Log(LOGDEBUG, "Thread for sensor %d exits", s->id);
196 * Get position in a binary sensor file with a timestamp using a binary search
197 * @param s - Sensor to use
198 * @param time_stamp - Timestamp
199 * @param count - If not NULL, used to provide number of searches required
200 * @param found - If not NULL, set to the closest DataPoint
201 * @returns Integer giving the *closest* index in the file
202 * TODO: Refactor or replace?
204 int FindTime(Sensor * s, double time_stamp, int * count, DataPoint * found)
209 int upper = s->points_written - 1;
214 while (upper - lower > 1)
216 index = lower + ((upper - lower)/2);
218 // Basically anything with fseek is critical; if we don't make it critical the sensor thread may alter data at a random point in the file!
219 // CRITICAL SECTION (May need to rethink how this is done, but I can't see how to do it without fseek :S)
220 // Regarding the suggestion that we have 2 file pointers; one for reading and one for writing:
221 // That seems like it will work... but we will have to be very careful and test it first
222 pthread_mutex_lock(&s->mutex);
223 fseek(s->file, index*sizeof(DataPoint), SEEK_SET);
224 int amount_read = fread(&d, sizeof(DataPoint), 1, s->file);
225 pthread_mutex_unlock(&s->mutex);
227 if (amount_read != 1)
229 Fatal("Couldn't read single data point from sensor %d", s->id);
232 if (d.time_stamp > time_stamp)
236 else if (d.time_stamp < time_stamp)
252 * Print sensor data between two indexes in the file, using a given format
253 * @param s - Sensor to use
254 * @param start - Start index
255 * @param end - End index
256 * @param output_type - JSON, CSV or TSV output format
258 void PrintData(Sensor * s, int start, int end, OutputType output_type)
260 DataPoint buffer[SENSOR_QUERYBUFSIZ];
263 if (output_type == JSON)
271 int to_read = end - index;
272 if (to_read > SENSOR_QUERYBUFSIZ)
274 to_read = SENSOR_QUERYBUFSIZ;
279 pthread_mutex_lock(&(s->mutex));
281 fseek(s->file, index*sizeof(DataPoint), SEEK_SET);
282 amount_read = fread(buffer, sizeof(DataPoint), to_read, s->file);
284 pthread_mutex_unlock(&(s->mutex));
285 // End critical section
287 if (amount_read != to_read)
289 Fatal("Failed to read %d DataPoints from sensor %d; read %d instead", to_read, s->id, amount_read);
293 for (int i = 0; i < amount_read; ++i)
299 FCGI_JSONValue("[%f, %f]", buffer[i].time_stamp, buffer[i].value);
300 if (i+1 < amount_read)
304 FCGI_PrintRaw("%f,%f\n", buffer[i].time_stamp, buffer[i].value);
308 FCGI_PrintRaw("%f\t%f\n", buffer[i].time_stamp, buffer[i].value);
312 index += amount_read;
315 if (output_type == JSON)
322 * Fill buffer with most recent sensor data
323 * TODO: This may be obselete; remove?
324 * @param s - Sensor to use
325 * @param buffer - Buffer to fill
326 * @param bufsiz - Size of buffer to fill
327 * @returns The number of DataPoints actually read
329 int Sensor_Query(Sensor * s, DataPoint * buffer, int bufsiz)
332 //CRITICAL SECTION (Don't access file while sensor thread is writing to it!)
333 pthread_mutex_lock(&(s->mutex));
335 fseek(s->file, -bufsiz*sizeof(DataPoint), SEEK_END);
336 amount_read = fread(buffer, sizeof(DataPoint), bufsiz, s->file);
337 //Log(LOGDEBUG, "Read %d data points", amount_read);
338 pthread_mutex_unlock(&(s->mutex));
343 * Get a Sensor given an ID string
344 * @param id_str ID string
345 * @returns Sensor* identified by the string; NULL on error
347 Sensor * Sensor_Identify(const char * id_str)
350 // Parse string as integer
351 int id = strtol(id_str, &end, 10);
357 if (id < 0 || id >= NUMSENSORS)
361 Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
366 * Handle a request to the sensor module
367 * @param context - The context to work in
368 * @param params - Parameters passed
369 * TODO: Seriously need to write more helper functions and decrease the size of this function!
371 void Sensor_Handler(FCGIContext *context, char * params)
373 StatusCodes status = STATUS_OK;
375 OutputType output_type = JSON;
379 const char * key; const char * value;
381 Sensor * sensor = NULL;
384 gettimeofday(&now, NULL);
386 double start_time = -1;
387 double end_time = -1;
388 double current_time = (now.tv_sec - g_options.start_time.tv_sec) + 1e-6*(now.tv_usec - g_options.start_time.tv_usec);
389 bool seek_time = false;
390 bool points_specified = false;
391 int query_size = SENSOR_QUERYBUFSIZ;
392 int start_index = -1;
396 while ((params = FCGI_KeyPair(params, &key, &value)) != NULL)
398 Log(LOGDEBUG, "Got key=%s and value=%s", key, value);
399 if (strcmp(key, "id") == 0)
403 Log(LOGERR, "Only one sensor id should be specified");
404 status = STATUS_ERROR;
409 Log(LOGERR, "No id specified.");
410 status = STATUS_ERROR;
414 sensor = Sensor_Identify(value);
417 Log(LOGERR, "Invalid sensor id: %s", value);
418 status = STATUS_ERROR;
422 else if (strcmp(key, "format") == 0)
424 if (strcmp(value, "json") == 0)
426 else if (strcmp(value, "csv") == 0)
428 else if (strcmp(value, "tsv") == 0)
431 else if (strcmp(key, "points") == 0)
433 points_specified = true;
434 if (strcmp(value, "all") == 0)
436 query_size = sensor->points_written;
441 query_size = strtol(value, &end, 10);
444 Log(LOGERR, "Require \"all\" or an integer value: %s = %s", key, value);
445 status = STATUS_ERROR;
451 else if (strcmp(key, "start_time") == 0)
455 start_time = strtod(value, &end);
458 Log(LOGERR, "Require a double: %s = %s", key, value);
459 status = STATUS_ERROR;
463 // Treat negative values as being relative to the current time
466 start_time = current_time + start_time;
468 start_time = floor(start_time);
470 else if (strcmp(key, "end_time") == 0)
474 end_time = strtod(value, &end);
477 Log(LOGERR, "Require a double: %s = %s", key, value);
478 status = STATUS_ERROR;
482 // Treat negative values as being relative to the current time
485 end_time = current_time + end_time;
487 end_time = ceil(end_time);
489 // For backward compatability:
490 else if (strcmp(key, "dump") == 0)
493 query_size = sensor->points_written+1;
497 Log(LOGERR, "Unknown key \"%s\" (value = %s)", key, value);
498 status = STATUS_ERROR;
503 if (status != STATUS_ERROR && sensor == NULL)
505 Log(LOGERR, "No valid sensor id given");
506 status = STATUS_ERROR;
509 if (status == STATUS_ERROR)
511 FCGI_RejectJSON(context, "Invalid input parameters");
518 if (end_time < 0 && !points_specified)
519 end_index = sensor->points_written;
522 int count = 0; DataPoint d;
523 end_index = FindTime(sensor, end_time, &count, &d);
524 Log(LOGDEBUG, "FindTime - Looked for %f; found [%f,%f] after %d iterations; sensor %d, position %d", end_time, d.time_stamp, d.value, count, sensor->id, end_index);
530 int count = 0; DataPoint d;
531 start_index = FindTime(sensor, start_time, &count, &d);
532 Log(LOGDEBUG, "FindTime - Looked for %f; found [%f,%f] after %d iterations; sensor %d, position %d", start_time, d.time_stamp, d.value, count, sensor->id, start_index);
535 if (points_specified)
536 end_index = start_index + query_size;
540 start_index = sensor->points_written - query_size;
542 end_index = sensor->points_written;
547 Log(LOGNOTE, "start_index = %d => Clamped to 0", start_index);
550 if (end_index > sensor->points_written)
552 Log(LOGNOTE, "end_index = %d => Clamped to %d", end_index, sensor->points_written);
553 end_index = sensor->points_written;
559 FCGI_BeginJSON(context, status);
560 FCGI_JSONLong("id", sensor->id);
561 FCGI_JSONKey("data");
562 PrintData(sensor, start_index, end_index, output_type);
566 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
567 PrintData(sensor, start_index, end_index, output_type);
568 //Force download with content-disposition
569 // Sam: This is cool, but I don't think we should do it
570 // - letting the user view it in the browser and then save with their own filename is more flexible
571 //"Content-disposition: attachment;filename=%d.csv\r\n\r\n", sensor->id);
578 * Setup Sensors, start Sensor polling thread(s)
582 // start sensor threads
583 for (int i = 0; i < NUMSENSORS; ++i)
585 Init(g_sensors+i, i);
586 pthread_create(&(g_sensors[i].thread), NULL, Sensor_Main, (void*)(g_sensors+i));
595 if (!Thread_Runstate())
597 Fatal("This function should not be called before Thread_QuitProgram");
599 for (int i = 0; i < NUMSENSORS; ++i)
601 pthread_join(g_sensors[i].thread, NULL);
602 Destroy(g_sensors+i);