+ Sensor * s = (Sensor*)(arg);
+
+ while (true) //TODO: Exit condition
+ {
+ // 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)
+ {
+ s->buffer[s->write_index] = GetData(s->id);
+ s->write_index += 1;
+ }
+
+ //Log(LOGDEBUG, "Filled buffer");
+
+ // CRITICAL SECTION (no threads should be able to read/write the file at the same time)
+ pthread_mutex_lock(&(s->mutex));
+
+ // Open binary file in append mode and dump buffer into it
+ FILE * file = fopen(s->filename, "ab");
+ if (file == NULL)
+ {
+ Fatal("Couldn't open file \"%s\" mode ab - %s", s->filename, strerror(errno));
+ }
+ int amount_written = fwrite(s->buffer, sizeof(DataPoint), SENSOR_DATABUFSIZ, file);
+ if (amount_written != SENSOR_DATABUFSIZ)
+ {
+ Fatal("Wrote %d data points and expected to write %d to \"%s\" - %s", amount_written, SENSOR_DATABUFSIZ, strerror(errno));
+ }
+
+ Log(LOGDEBUG, "Wrote %d data points for sensor %d", amount_written, s->id);
+
+ fclose(file);
+
+ pthread_mutex_unlock(&(s->mutex));
+ // End of critical section
+
+ s->write_index = 0; // reset position in buffer
+
+ }
+ return NULL;