X-Git-Url: https://git.ucc.asn.au/?a=blobdiff_plain;f=server%2Fsensor.c;h=4e8ac7fd6a719024d1b427082bfca7ed7c38415f;hb=7547dad3aee722136894566bb6802fe6491cbfbe;hp=0bbfc94ec0e7b0217f1ad7dbeb28990ddc08c582;hpb=54d8526bce34af6b0d3a08c84e9d0bdfa6963224;p=matches%2FMCTX3420.git diff --git a/server/sensor.c b/server/sensor.c index 0bbfc94..4e8ac7f 100644 --- a/server/sensor.c +++ b/server/sensor.c @@ -7,169 +7,200 @@ #include "common.h" #include "sensor.h" #include "options.h" +#include "bbb_pin.h" #include /** Array of sensors, initialised by Sensor_Init **/ -static Sensor g_sensors[NUMSENSORS]; //global to this file - -/** Human readable names for the sensors **/ -const char * g_sensor_names[NUMSENSORS] = { - "analog_test0", "analog_test1", - "digital_test0", "digital_test1" -}; - -/** - * One off initialisation of *all* sensors +static Sensor g_sensors[SENSORS_MAX]; +/** The number of sensors **/ +int g_num_sensors = 0; + + + +/** + * Add and initialise a Sensor + * @param name - Human readable name of the sensor + * @param user_id - User identifier + * @param read - Function to call whenever the sensor should be read + * @param init - Function to call to initialise the sensor (may be NULL) + * @param max_error - Maximum error threshold; program will exit if this is exceeded for the sensor reading + * @param min_error - Minimum error threshold; program will exit if the sensor reading falls below this value + * @param max_warn - Maximum warning threshold; program will log warnings if the value exceeds this threshold + * @param min_warn - Minimum warning threshold; program will log warnings if the value falls below this threshold + * @returns Number of actuators added so far */ -void Sensor_Init() +int Sensor_Add(const char * name, int user_id, ReadFn read, InitFn init, CleanFn cleanup, SanityFn sanity) { - for (int i = 0; i < NUMSENSORS; ++i) + if (++g_num_sensors > SENSORS_MAX) { - g_sensors[i].id = i; - Data_Init(&(g_sensors[i].data_file)); - g_sensors[i].record_data = false; + Fatal("Too many sensors; Increase SENSORS_MAX from %d in sensor.h and recompile", SENSORS_MAX); + // We could design the program to use realloc(3) + // But since someone who adds a new sensor has to recompile the program anyway... } -} + Sensor * s = &(g_sensors[g_num_sensors-1]); -/** - * Start a Sensor recording DataPoints - * @param s - The Sensor to start - * @param experiment_name - Prepended to DataFile filename - */ -void Sensor_Start(Sensor * s, const char * experiment_name) -{ - // Set filename - char filename[BUFSIZ]; - if (sprintf(filename, "%s_%d", experiment_name, s->id) >= BUFSIZ) - { - Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ); - } + s->id = g_num_sensors-1; + s->user_id = user_id; + Data_Init(&(s->data_file)); + s->name = name; + s->read = read; // Set read function + s->init = init; // Set init function - Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename); - // Open DataFile - Data_Open(&(s->data_file), filename); + // Start by averaging values taken over a second + DOUBLE_TO_TIMEVAL(1, &(s->sample_time)); + s->averages = 1; + s->num_read = 0; - s->record_data = true; // Don't forget this! + // Set sanity function + s->sanity = sanity; - // Create the thread - pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s)); -} - -/** - * Stop a Sensor from recording DataPoints. Blocks until it has stopped. - * @param s - The Sensor to stop - */ -void Sensor_Stop(Sensor * s) -{ - // Stop - if (s->record_data) + if (init != NULL) { - s->record_data = false; - pthread_join(s->thread, NULL); // Wait for thread to exit - Data_Close(&(s->data_file)); // Close DataFile - s->newest_data.time_stamp = 0; - s->newest_data.value = 0; + if (!init(name, user_id)) + Fatal("Couldn't init sensor %s", name); } + + s->current_data.time_stamp = 0; + s->current_data.value = 0; + s->averaged_data.time_stamp = 0; + s->averaged_data.value = 0; + return g_num_sensors; } /** - * Stop all Sensors + * Initialise all sensors used by the program + * TODO: Edit this to add any extra sensors you need + * TODO: Edit the includes as well */ -void Sensor_StopAll() +#include "sensors/resource.h" +#include "sensors/strain.h" +#include "sensors/pressure.h" +#include "sensors/dilatometer.h" +#include "sensors/microphone.h" +void Sensor_Init() { - for (int i = 0; i < NUMSENSORS; ++i) - Sensor_Stop(g_sensors+i); + //Sensor_Add("cpu_stime", RESOURCE_CPU_SYS, Resource_Read, NULL, NULL, NULL); + //Sensor_Add("cpu_utime", RESOURCE_CPU_USER, Resource_Read, NULL, NULL, NULL); + Sensor_Add("pressure_high0", PRES_HIGH0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL); + Sensor_Add("pressure_high1", PRES_HIGH1, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL); + Sensor_Add("pressure_low0", PRES_LOW0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL); + //Sensor_Add("../testing/count.py", 0, Piped_Read, Piped_Init, Piped_Cleanup, 1e50,-1e50,1e50,-1e50); + //Sensor_Add("strain0_endhoop", STRAIN0, Strain_Read, Strain_Init, Strain_Cleanup, Strain_Sanity); + //Sensor_Add("strain1_endlong", STRAIN1, Strain_Read, Strain_Init, Strain_Cleanup, Strain_Sanity); + //Sensor_Add("strain2_midhoop", STRAIN2, Strain_Read, Strain_Init, Strain_Cleanup, Strain_Sanity); + //Sensor_Add("strain3_midlong", STRAIN3, Strain_Read, Strain_Init, Strain_Cleanup, Strain_Sanity); + + //Sensor_Add("microphone", 0, Microphone_Read, Microphone_Init, Microphone_Cleanup, Microphone_Sanity); + //Sensor_Add("pressure0", PRESSURE0, Pressure_Read, Pressure_Init, 5000,0,5000,0); + //Sensor_Add("pressure1", PRESSURE1, Pressure_Read, Pressure_Init, 5000,0,5000,0); + //Sensor_Add("pressure_feedback", PRESSURE_FEEDBACK, Pressure_Read, Pressure_Init, 5000,0,5000,0); + //Sensor_Add("enclosure", ENCLOSURE, Enclosure_Read, Enclosure_Init, 1,1,1,1); // Does not exist... + + //NOTE: DO NOT ENABLE DILATOMETER WITHOUT FURTHER TESTING; CAUSES SEGFAULTS + //Sensor_Add("dilatometer0", 0, Dilatometer_Read, Dilatometer_Init, Dilatometer_Cleanup, NULL); + //Sensor_Add("dilatometer1",1, Dilatometer_Read, Dilatometer_Init, Dilatometer_Cleanup, NULL); } /** - * Start all Sensors + * Cleanup all sensors */ -void Sensor_StartAll(const char * experiment_name) +void Sensor_Cleanup() { - for (int i = 0; i < NUMSENSORS; ++i) - Sensor_Start(g_sensors+i, experiment_name); + for (int i = 0; i < g_num_sensors; ++i) + { + Sensor * s = g_sensors+i; + if (s->cleanup != NULL) + s->cleanup(s->user_id); + } + g_num_sensors = 0; } /** - * Read a DataPoint from a Sensor; block until value is read - * @param id - The ID of the sensor - * @param d - DataPoint to set - * @returns True if the DataPoint was different from the most recently recorded. + * Sets the sensor to the desired control mode. No checks are + * done to see if setting to the desired mode will conflict with + * the current mode - the caller must guarantee this itself. + * @param s The sensor whose mode is to be changed + * @param mode The mode to be changed to + * @param arg An argument specific to the mode to be set. + * e.g for CONTROL_START it represents the experiment name. */ -bool Sensor_Read(Sensor * s, DataPoint * d) +void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg) { - - // Set time stamp - struct timeval t; - gettimeofday(&t, NULL); - d->time_stamp = TIMEVAL_DIFF(t, g_options.start_time); - - // Read value based on Sensor Id - switch (s->id) + switch(mode) { - case ANALOG_TEST0: - d->value = (double)(rand() % 100) / 100; - break; + case CONTROL_START: + { + // Set filename + char filename[BUFSIZ]; + const char *experiment_path = (const char*) arg; + int ret; + + ret = snprintf(filename, BUFSIZ, "%s/sensor_%d", experiment_path, s->id); + + if (ret >= BUFSIZ) + { + Fatal("Experiment path \"%s\" too long (%d, limit %d)", + experiment_path, ret, BUFSIZ); + } + + Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename); + // Open DataFile + Data_Open(&(s->data_file), filename); + } + case CONTROL_RESUME: //Case fallthrough, no break before + { + int ret; + s->activated = true; // Don't forget this! - case ANALOG_TEST1: - { - static int count = 0; - d->value = count++; - break; - } - case DIGITAL_TEST0: - d->value = t.tv_sec % 2; - break; - case DIGITAL_TEST1: - d->value = (t.tv_sec+1)%2; - break; - default: - Fatal("Unknown sensor id: %d", s->id); - break; - } - usleep(100000); // simulate delay in sensor polling + // Create the thread + ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s)); + if (ret != 0) + { + Fatal("Failed to create Sensor_Loop for Sensor %d", s->id); + } - // Perform sanity check based on Sensor's ID and the DataPoint - Sensor_CheckData(s->id, d); + Log(LOGDEBUG, "Resuming sensor %d", s->id); + } + break; + + case CONTROL_EMERGENCY: + case CONTROL_PAUSE: + s->activated = false; + pthread_join(s->thread, NULL); + Log(LOGDEBUG, "Paused sensor %d", s->id); + break; + + case CONTROL_STOP: + if (s->activated) //May have been paused before + { + s->activated = false; + pthread_join(s->thread, NULL); + } - // Update latest DataPoint if necessary - bool result = (d->value != s->newest_data.value); - if (result) - { - s->newest_data.time_stamp = d->time_stamp; - s->newest_data.value = d->value; + Data_Close(&(s->data_file)); // Close DataFile + Log(LOGDEBUG, "Stopped sensor %d", s->id); + break; + default: + Fatal("Unknown control mode: %d", mode); } - return result; } /** - * Checks the sensor data for unsafe or unexpected results - * @param sensor_id - The ID of the sensor - * @param d - DataPoint to check + * Sets all sensors to the desired mode. + * @see Sensor_SetMode for more information. + * @param mode The mode to be changed to + * @param arg An argument specific to the mode to be set. */ -void Sensor_CheckData(SensorId id, DataPoint * d) +void Sensor_SetModeAll(ControlModes mode, void * arg) { - //TODO: Implement - /* - switch (sensor_id) - { - case ANALOG_TEST0: - { - if( *sensor value* > ANALOG_TEST0_SAFETY) - { - LogEx(LOGERR, GetData, Sensor analog_test0 is above the safe value); - //new log function that stops actuators? - } - //Also include a warning level? - else if( *sensor value* > ANALOG_TEST0_WARN) - { - LogEx(LOGWARN, GetData, Sensor analog_test0); - } - } - } - */ + if (mode == CONTROL_START) + Sensor_Init(); + for (int i = 0; i < g_num_sensors; i++) + Sensor_SetMode(&g_sensors[i], mode, arg); + if (mode == CONTROL_STOP) + Sensor_Cleanup(); } - + /** * Record data from a single Sensor; to be run in a seperate thread @@ -182,44 +213,65 @@ void * Sensor_Loop(void * arg) Log(LOGDEBUG, "Sensor %d starts", s->id); // Until the sensor is stopped, record data points - while (s->record_data) + while (s->activated) { - DataPoint d; - //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value); - if (Sensor_Read(s, &d)) // If new DataPoint is read: + + bool success = s->read(s->user_id, &(s->current_data.value)); + + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + s->current_data.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime()); + + if (success) + { + if (s->sanity != NULL) + { + if (!s->sanity(s->user_id, s->current_data.value)) + { + Fatal("Sensor %s (%d,%d) reads unsafe value", s->name, s->id, s->user_id); + } + } + s->averaged_data.time_stamp += s->current_data.time_stamp; + s->averaged_data.value = s->current_data.value; + + if (++(s->num_read) >= s->averages) + { + s->averaged_data.time_stamp /= s->averages; + s->averaged_data.value /= s->averages; + Data_Save(&(s->data_file), &(s->averaged_data), 1); // Record it + s->num_read = 0; + s->averaged_data.time_stamp = 0; + s->averaged_data.value = 0; + } + } + else { - //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value); - Data_Save(&(s->data_file), &d, 1); // Record it + // Silence because strain sensors fail ~50% of the time :S + //Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id); } + + + clock_nanosleep(CLOCK_MONOTONIC, 0, &(s->sample_time), NULL); + } // Needed to keep pthreads happy - - Log(LOGDEBUG, "Sensor %d finished", s->id); + Log(LOGDEBUG, "Sensor %s (%d,%d) finished", s->name,s->id,s->user_id); return NULL; } /** - * Get a Sensor given an ID string - * @param id_str ID string - * @returns Sensor* identified by the string; NULL on error + * Get a Sensor given its name + * @returns Sensor with the given name, NULL if there isn't one */ -Sensor * Sensor_Identify(const char * id_str) -{ - char * end; - // Parse string as integer - int id = strtol(id_str, &end, 10); - if (*end != '\0') +Sensor * Sensor_Identify(const char * name) +{ + for (int i = 0; i < g_num_sensors; ++i) { - return NULL; + if (strcmp(g_sensors[i].name, name) == 0) + return &(g_sensors[i]); } - // Bounds check - if (id < 0 || id >= NUMSENSORS) - return NULL; - - - Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]); - return g_sensors+id; + return NULL; } /** @@ -228,15 +280,16 @@ Sensor * Sensor_Identify(const char * id_str) * @param id - ID of sensor * @param format - Format */ -void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format) +void Sensor_BeginResponse(FCGIContext * context, Sensor * s, DataFormat format) { // Begin response switch (format) { case JSON: FCGI_BeginJSON(context, STATUS_OK); - FCGI_JSONLong("id", id); - FCGI_JSONKey("data"); + FCGI_JSONLong("id", s->id); + FCGI_JSONLong("user_id", s->user_id); //NOTE: Might not want to expose this? + FCGI_JSONPair("name", s->name); break; default: FCGI_PrintRaw("Content-type: text/plain\r\n\r\n"); @@ -250,7 +303,7 @@ void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format) * @param id - ID of the sensor * @param format - Format */ -void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format) +void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format) { // End response switch (format) @@ -270,29 +323,34 @@ void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format) */ void Sensor_Handler(FCGIContext *context, char * params) { - struct timeval now; - gettimeofday(&now, NULL); - double current_time = TIMEVAL_DIFF(now, g_options.start_time); - + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime()); int id = 0; + const char * name = ""; double start_time = 0; double end_time = current_time; const char * fmt_str; + double sample_s = 0; // key/value pairs FCGIValue values[] = { - {"id", &id, FCGI_REQUIRED(FCGI_INT_T)}, + {"id", &id, FCGI_INT_T}, + {"name", &name, FCGI_STRING_T}, {"format", &fmt_str, FCGI_STRING_T}, {"start_time", &start_time, FCGI_DOUBLE_T}, {"end_time", &end_time, FCGI_DOUBLE_T}, + {"sample_s", &sample_s, FCGI_DOUBLE_T} }; // enum to avoid the use of magic numbers typedef enum { ID, + NAME, FORMAT, START_TIME, END_TIME, + SAMPLE_S } SensorParams; // Fill values appropriately @@ -301,66 +359,75 @@ void Sensor_Handler(FCGIContext *context, char * params) // Error occured; FCGI_RejectJSON already called return; } - else if (id < 0 || id >= NUMSENSORS) - { - FCGI_RejectJSON(context, "Invalid sensor id specified"); - return; - } - // Get Sensor and format - Sensor * s = g_sensors+id; - DataFormat format = JSON; - - // Check if format type was specified - if (FCGI_RECEIVED(values[FORMAT].flags)) + Sensor * s = NULL; + if (FCGI_RECEIVED(values[NAME].flags)) { - if (strcmp(fmt_str, "json") == 0) - format = JSON; - else if (strcmp(fmt_str, "tsv") == 0) - format = TSV; - else + if (FCGI_RECEIVED(values[ID].flags)) + { + FCGI_RejectJSON(context, "Can't supply both sensor id and name"); + return; + } + s = Sensor_Identify(name); + if (s == NULL) { - FCGI_RejectJSON(context, "Unknown format type specified."); + FCGI_RejectJSON(context, "Unknown sensor name"); return; } } - - // Begin response - Sensor_BeginResponse(context, id, format); - - // If a time was specified - if (FCGI_RECEIVED(values[START_TIME].flags) || FCGI_RECEIVED(values[END_TIME].flags)) + else if (!FCGI_RECEIVED(values[ID].flags)) { - // Wrap times relative to the current time - if (start_time < 0) - start_time += current_time; - if (end_time < 0) - end_time += current_time; - - // Print points by time range - Data_PrintByTimes(&(s->data_file), start_time, end_time, format); + FCGI_RejectJSON(context, "No sensor id or name supplied"); + return; } - else // No time was specified; just return a recent set of points + else if (id < 0 || id >= g_num_sensors) { - pthread_mutex_lock(&(s->data_file.mutex)); - int start_index = s->data_file.num_points-DATA_BUFSIZ; - int end_index = s->data_file.num_points; - pthread_mutex_unlock(&(s->data_file.mutex)); - - // Bounds check - if (start_index < 0) - start_index = 0; - if (end_index < 0) - end_index = 0; - - // Print points by indexes - Log(LOGDEBUG, "Sensor %d file \"%s\" indexes %d->%d", s->id, s->data_file.filename, start_index, end_index); - Data_PrintByIndexes(&(s->data_file), start_index, end_index, format); + FCGI_RejectJSON(context, "Invalid sensor id"); + return; + } + else + { + s = &(g_sensors[id]); + } + + // Adjust sample rate if necessary + if (FCGI_RECEIVED(values[SAMPLE_S].flags)) + { + if (sample_s < 0) + { + FCGI_RejectJSON(context, "Negative sampling speed!"); + return; + } + DOUBLE_TO_TIMEVAL(sample_s, &(s->sample_time)); } - // Finish response - Sensor_EndResponse(context, id, format); + DataFormat format = Data_GetFormat(&(values[FORMAT])); + + // Begin response + Sensor_BeginResponse(context, s, format); + + // Print Data + Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time); + + // Finish response + Sensor_EndResponse(context, s, format); + +} + +/** + * Get the Name of a Sensor + * @param id - ID number + */ +const char * Sensor_GetName(int id) +{ + return g_sensors[id].name; +} + +DataPoint Sensor_LastData(int id) +{ + Sensor * s = &(g_sensors[id]); + return s->current_data; }