X-Git-Url: https://git.ucc.asn.au/?a=blobdiff_plain;f=server%2Fsensor.c;h=8406870596ca1fa97735e9f6b9aa64662ffc84b2;hb=289794ba2dcbe6234e25e5d00531b26baee342b7;hp=34c931097b567e6fd108f3f45fb317fc99afc574;hpb=2e3ab88d1282fc893c9bd615911aaedc9e552178;p=matches%2FMCTX3420.git diff --git a/server/sensor.c b/server/sensor.c index 34c9310..8406870 100644 --- a/server/sensor.c +++ b/server/sensor.c @@ -1,299 +1,375 @@ /** * @file sensor.c - * @purpose Implementation of sensor thread + * @brief Implementation of sensor thread * TODO: Finalise implementation */ - #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 - -/** - * Read a data value from a sensor; block until value is read - * @param sensor_id - The ID of the sensor - * @param d - DataPoint to set - * @returns NULL on error, otherwise d +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 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 the sensor added */ -DataPoint * GetData(int sensor_id, DataPoint * d) +int Sensor_Add(const char * name, int user_id, ReadFn read, InitFn init, CleanFn cleanup, double max_error, double min_error, double max_warn, double min_warn) { - // switch based on the sensor_id at the moment for testing; - // might be able to just directly access ADC from sensor_id? - //TODO: Implement for real sensors - - - //TODO: We should ensure the time is *never* allowed to change on the server if we use gettimeofday - // Another way people might think of getting the time is to count CPU cycles with clock() - // 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 - gettimeofday(&(d->time_stamp), NULL); - - switch (sensor_id) + if (++g_num_sensors > SENSORS_MAX) { - case SENSOR_TEST0: - { - static int count = 0; - d->value = count++; - break; - } - case SENSOR_TEST1: - d->value = (float)(rand() % 100) / 100; - break; - default: - Fatal("Unknown sensor id: %d", sensor_id); - break; - } - usleep(100000); // simulate delay in sensor polling - - return d; + 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]); + + 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 + if (init != NULL) + init(name, user_id); // Call it + + // Set warning/error thresholds + s->thresholds.max_error = max_error; + s->thresholds.min_error = min_error; + s->thresholds.max_warn = max_warn; + s->thresholds.min_warn = min_warn; + + return g_num_sensors; } - /** - * Destroy a sensor - * @param s - Sensor to destroy + * Initialise all sensors used by the program + * TODO: Edit this to add any extra sensors you need + * TODO: Edit the includes as well */ -void Destroy(Sensor * s) +#include "sensors/resource.h" +#include "sensors/strain.h" +#include "sensors/piped.h" +void Sensor_Init() { - // Maybe move the binary file into long term file storage? - fclose(s->file); + Sensor_Add("cpu_stime", RESOURCE_CPU_SYS, Resource_Read, NULL, NULL, 1e50,-1e50,1e50,-1e50); + Sensor_Add("cpu_utime", RESOURCE_CPU_USER, Resource_Read, NULL, NULL, 1e50,-1e50,1e50,-1e50); + //Sensor_Add("../testing/count.py", 0, Piped_Read, Piped_Init, Piped_Cleanup, 1e50,-1e50,1e50,-1e50); + //Sensor_Add("strain0", STRAIN0, Strain_Read, Strain_Init, 5000,0,5000,0); + //Sensor_Add("strain1", STRAIN1, Strain_Read, Strain_Init, 5000,0,5000,0); + //Sensor_Add("strain2", STRAIN2, Strain_Read, Strain_Init, 5000,0,5000,0); + //Sensor_Add("strain3", STRAIN3, Strain_Read, Strain_Init, 5000,0,5000,0); + //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); + //Sensor_Add("dilatometer", DILATOMETER, Dilatometer_Read, Dilatometer_Init, -1,-1,-1,-1); } - - /** - * Initialise a sensor - * @param s - Sensor to initialise + * Cleanup all sensors */ -void Init(Sensor * s, int id) +void Sensor_Cleanup() { - s->write_index = 0; - s->read_offset = 0; - s->id = id; - - #define FILENAMESIZE 3 - char filename[FILENAMESIZE]; - if (s->id >= pow(10, FILENAMESIZE)) + for (int i = 0; i < g_num_sensors; ++i) { - Fatal("Too many sensors! FILENAMESIZE is %d; increase it and recompile.", FILENAMESIZE); + Sensor * s = g_sensors+i; + if (s->cleanup != NULL) + s->cleanup(s->user_id); } - - pthread_mutex_init(&(s->mutex), NULL); - - sprintf(filename, "%d", s->id); - unlink(filename); //TODO: Move old files somewhere - - s->file = fopen(filename, "a+b"); // open binary file - Log(LOGDEBUG, "Initialised sensor %d; binary file is \"%s\"", id, filename); } - - - - /** - * Run the main sensor polling loop - * @param arg - Cast to Sensor* - Sensor that the thread will handle - * @returns NULL (void* required to use the function with pthreads) + * 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. */ -void * Sensor_Main(void * arg) +void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg) { - Sensor * s = (Sensor*)(arg); - - while (Thread_Runstate() == RUNNING) //TODO: Exit condition + switch(mode) { - // The sensor will write data to a buffer until it is full - // Then it will open a file and dump the buffer to the end of it. - // Rinse and repeat - - // The reason I've added the buffer is because locks are expensive - // But maybe it's better to just write data straight to the file - // I'd like to do some tests by changing SENSOR_DATABUFSIZ - - while (s->write_index < SENSOR_DATABUFSIZ) - { - DataPoint * d = &(s->buffer[s->write_index]); - if (GetData(s->id, d) == NULL) + case CONTROL_START: { - Fatal("Error collecting data"); + // Set filename + char filename[BUFSIZ]; + const char *experiment_name = (const char*) arg; + + if (snprintf(filename, BUFSIZ, "%s_%d", experiment_name, s->id) >= BUFSIZ) + { + Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ); + } + + Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename); + // Open DataFile + Data_Open(&(s->data_file), filename); } - s->write_index += 1; - } + case CONTROL_RESUME: //Case fallthrough, no break before + { + int ret; + s->activated = true; // Don't forget this! - //Log(LOGDEBUG, "Filled buffer"); + // 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); + } - // CRITICAL SECTION (no threads should be able to read/write the file at the same time) - pthread_mutex_lock(&(s->mutex)); - //TODO: Valgrind complains about this fseek: "Syscall param write(buf) points to uninitialised byte(s)" - // Not sure why, but we should find out and fix it. - fseek(s->file, 0, SEEK_END); - int amount_written = fwrite(s->buffer, sizeof(DataPoint), SENSOR_DATABUFSIZ, s->file); - if (amount_written != SENSOR_DATABUFSIZ) + 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 { - Fatal("Wrote %d data points and expected to write %d to \"%s\" - %s", amount_written, SENSOR_DATABUFSIZ, strerror(errno)); + s->activated = false; + pthread_join(s->thread, NULL); } - //Log(LOGDEBUG, "Wrote %d data points for sensor %d", amount_written, s->id); - pthread_mutex_unlock(&(s->mutex)); - // End of critical section - s->write_index = 0; // reset position in buffer - + Data_Close(&(s->data_file)); // Close DataFile + Log(LOGDEBUG, "Stopped sensor %d", s->id); + break; + default: + Fatal("Unknown control mode: %d", mode); } - Log(LOGDEBUG, "Thread for sensor %d exits", s->id); - return NULL; } /** - * Fill buffer with most recent sensor data - * @param s - Sensor to use - * @param buffer - Buffer to fill - * @param bufsiz - Size of buffer to fill - * @returns The number of DataPoints actually read + * 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. */ -int Sensor_Query(Sensor * s, DataPoint * buffer, int bufsiz) +void Sensor_SetModeAll(ControlModes mode, void * arg) { - int amount_read = 0; - //CRITICAL SECTION (Don't access file while sensor thread is writing to it!) - pthread_mutex_lock(&(s->mutex)); - - fseek(s->file, -bufsiz*sizeof(DataPoint), SEEK_END); - amount_read = fread(buffer, sizeof(DataPoint), bufsiz, s->file); - //Log(LOGDEBUG, "Read %d data points", amount_read); - pthread_mutex_unlock(&(s->mutex)); - return amount_read; + for (int i = 0; i < g_num_sensors; i++) + Sensor_SetMode(&g_sensors[i], mode, arg); } + /** - * Get a Sensor given an ID string - * @param id_str ID string - * @returns Sensor* identified by the string; NULL on error + * Checks the sensor data for unsafe or unexpected results + * @param sensor_id - The ID of the sensor + * @param value - The value from the sensor to test */ -Sensor * Sensor_Identify(const char * id_str) +void Sensor_CheckData(Sensor * s, double value) { - char * end; - // Parse string as integer - int id = strtol(id_str, &end, 10); - if (*end != '\0') + if( value > s->thresholds.max_error || value < s->thresholds.min_error) { - return NULL; + Log(LOGERR, "Sensor %s at %f is above or below its safety value of %f or %f\n",s->name,value, s->thresholds.max_error, s->thresholds.min_error); + //new function that stops actuators? + //Control_SetMode(CONTROL_EMERGENCY, NULL) + } + else if( value > s->thresholds.max_warn || value < s->thresholds.min_warn) + { + Log(LOGWARN, "Sensor %s at %f is above or below its warning value of %f or %f\n", s->name,value,s->thresholds.max_warn, s->thresholds.min_warn); } - // Bounds check - if (id < 0 || id > NUMSENSORS) - return NULL; - - return g_sensors+id; } + /** - * Handle a request to the sensor module - * @param context - The context to work in - * @param params - Parameters passed + * Record data from a single Sensor; to be run in a seperate thread + * @param arg - Cast to Sensor* - Sensor that the thread will handle + * @returns NULL (void* required to use the function with pthreads) */ -void Sensor_Handler(FCGIContext *context, char * params) +void * Sensor_Loop(void * arg) { - DataPoint buffer[SENSOR_QUERYBUFSIZ]; - StatusCodes status = STATUS_OK; - const char * key; const char * value; - - Sensor * sensor = NULL; + Sensor * s = (Sensor*)(arg); + Log(LOGDEBUG, "Sensor %d starts", s->id); - while ((params = FCGI_KeyPair(params, &key, &value)) != NULL) + // Until the sensor is stopped, record data points + while (s->activated) { - Log(LOGDEBUG, "Got key=%s and value=%s", key, value); - if (strcmp(key, "id") == 0) + DataPoint d; + d.value = 0; + bool success = s->read(s->user_id, &(d.value)); + + struct timeval t; + gettimeofday(&t, NULL); + d.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime()); + + if (success) { - if (sensor != NULL) - { - Log(LOGERR, "Only one sensor id should be specified"); - status = STATUS_ERROR; - break; - } - if (*value == '\0') - { - Log(LOGERR, "No id specified."); - status = STATUS_ERROR; - break; - } - sensor = Sensor_Identify(value); - if (sensor == NULL) - { - Log(LOGERR, "Invalid sensor id: %s", value); - status = STATUS_ERROR; - break; - } + + Sensor_CheckData(s, d.value); + Data_Save(&(s->data_file), &d, 1); // Record it } else - { - Log(LOGERR, "Unknown key \"%s\" (value = %s)", key, value); - status = STATUS_ERROR; - break; - } - } + Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id); - if (status != STATUS_ERROR && sensor == NULL) - { - Log(LOGERR, "No valid sensor id given"); - status = STATUS_ERROR; + usleep(1e5); //TODO: Adjust appropriately } + + // Needed to keep pthreads happy + Log(LOGDEBUG, "Sensor %s (%d,%d) finished", s->name,s->id,s->user_id); + return NULL; +} - if (status == STATUS_ERROR) +/** + * Get a Sensor given its name + * @returns Sensor with the given name, NULL if there isn't one + */ +Sensor * Sensor_Identify(const char * name) +{ + for (int i = 0; i < g_num_sensors; ++i) { - FCGI_RejectJSON(context); + if (strcmp(g_sensors[i].name, name) == 0) + return &(g_sensors[i]); } - else - { + return NULL; +} - FCGI_BeginJSON(context, status); - FCGI_JSONPair(key, value); // should spit back sensor ID - //Log(LOGDEBUG, "Call Sensor_Query..."); - int amount_read = Sensor_Query(sensor, buffer, SENSOR_QUERYBUFSIZ); - //Log(LOGDEBUG, "Read %d DataPoints", amount_read); - //Log(LOGDEBUG, "Produce JSON response"); - FCGI_JSONKey("data"); - FCGI_JSONValue("["); - for (int i = 0; i < amount_read; ++i) - { - //TODO: Consider; is it better to give both tv_sec and tv_usec to the client seperately, instead of combining here? - //NOTE: Must always use doubles; floats get rounded! - double time = buffer[i].time_stamp.tv_sec + 1e-6*(buffer[i].time_stamp.tv_usec); - FCGI_JSONValue("[%f, %f]", time, buffer[i].value); - if (i+1 < amount_read) - FCGI_JSONValue(","); - } - FCGI_JSONValue("]"); - //Log(LOGDEBUG, "Done producing JSON response"); - FCGI_EndJSON(); +/** + * Helper: Begin sensor response in a given format + * @param context - the FCGIContext + * @param id - ID of sensor + * @param format - Format + */ +void Sensor_BeginResponse(FCGIContext * context, Sensor * s, DataFormat format) +{ + // Begin response + switch (format) + { + case JSON: + FCGI_BeginJSON(context, STATUS_OK); + 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"); + break; } } /** - * Setup Sensors, start Sensor polling thread(s) + * Helper: End sensor response in a given format + * @param context - the FCGIContext + * @param id - ID of the sensor + * @param format - Format */ -void Sensor_Spawn() +void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format) { - // start sensor threads - for (int i = 0; i < NUMSENSORS; ++i) + // End response + switch (format) { - Init(g_sensors+i, i); - pthread_create(&(g_sensors[i].thread), NULL, Sensor_Main, (void*)(g_sensors+i)); + case JSON: + FCGI_EndJSON(); + break; + default: + break; } } /** - * Quit Sensor loops + * Handle a request to the sensor module + * @param context - The context to work in + * @param params - Parameters passed */ -void Sensor_Join() +void Sensor_Handler(FCGIContext *context, char * params) { - if (!Thread_Runstate()) + struct timeval now; + gettimeofday(&now, NULL); + 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; + + // key/value pairs + FCGIValue values[] = { + {"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}, + }; + + // enum to avoid the use of magic numbers + typedef enum { + ID, + NAME, + FORMAT, + START_TIME, + END_TIME, + } SensorParams; + + // Fill values appropriately + if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue))) { - Fatal("This function should not be called before Thread_QuitProgram"); + // Error occured; FCGI_RejectJSON already called + return; } - for (int i = 0; i < NUMSENSORS; ++i) + + Sensor * s = &(g_sensors[id]); // If id was not supplied, this defaults to &(g_sensors[0]) + if (FCGI_RECEIVED(values[NAME].flags)) { - pthread_join(g_sensors[i].thread, NULL); - Destroy(g_sensors+i); + 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 sensor name"); + return; + } } + else if (!FCGI_RECEIVED(values[ID].flags)) + { + FCGI_RejectJSON(context, "No sensor id or name supplied"); + return; + } + + 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; +} + + +