Refactor Sensor related code; introduce seperate functions for dealing with DataPoints
[matches/MCTX3420.git] / server / data.c
1 /**
2  * @file data.c
3  * @purpose Implementation of data handling functions; saving, loading, displaying, selecting.
4  */
5
6 #include "data.h"
7 #include <assert.h> //TODO: Remove asserts
8
9 /**
10  * One off initialisation of DataFile
11  * @param df - The DataFile
12  */
13 void Data_Init(DataFile * df)
14 {
15         // Everything is NULL
16         df->filename = NULL;
17         df->read_file = NULL;
18         df->write_file = NULL;
19 }
20
21 /**
22  * Initialise a DataFile from a filename; opens read/write FILE*
23  * @param df - DataFile to initialise
24  * @param filename - Name of file; overwritten if it exists
25  */
26 void Data_Open(DataFile * df, const char * filename)
27 {
28         assert(filename != NULL);
29         assert(df != NULL);
30
31         // Set the filename
32         df->filename = filename;
33
34         // Set number of DataPoints
35         df->num_points = 0; 
36         
37         // Set read FILE*
38         df->read_file = fopen(filename, "r");
39         if (df->read_file == NULL)
40         {
41                 Fatal("Error opening DataFile %s - %s", filename, strerror(errno));
42         }
43
44         // Set write FILE*
45         df->write_file = fopen(filename, "w");
46         if (df->write_file == NULL)
47         {
48                 Fatal("Error opening DataFile %s - %s", filename, strerror(errno));
49         }
50 }
51
52 /**
53  * Close a DataFile
54  * @param df - The DataFile to close
55  */
56 void Data_Close(DataFile * df)
57 {
58         assert(df != NULL);
59
60         //TODO: Write data to TSV?
61
62         // Clear the FILE*s
63         df->read_file = NULL;
64         df->write_file = NULL;
65
66         // Clear the filename
67         df->filename = NULL;
68 }
69
70 /**
71  * Save DataPoints to a DataFile
72  * @param df - The DataFile to save to
73  * @param buffer - Array of DataPoint(s) to save
74  * @param amount - Number of DataPoints in the buffer
75  */
76 void Data_Save(DataFile * df, DataPoint * buffer, int amount)
77 {
78         assert(df != NULL);
79         assert(buffer != NULL);
80         assert(amount >= 0);
81
82         // Go to the end of the file
83         if (fseek(df->write_file, 0, SEEK_END) < 0)
84         {
85                 Fatal("Error seeking to end of DataFile %s - %s", df->filename, strerror(errno));
86         }
87
88         // Attempt to write the DataPoints
89         int amount_written = fwrite(buffer, sizeof(DataPoint), amount, df->write_file);
90         
91         // Check if the correct number of points were written
92         if (amount_written != amount)
93         {
94                 Fatal("Wrote %d points instead of %d to DataFile %s - %s", amount_written, amount, df->filename, strerror(errno));
95         }
96
97         // Update number of DataPoints
98         pthread_mutex_lock(&(df->mutex));
99                 df->num_points += amount_written;
100         pthread_mutex_unlock(&(df->mutex));
101         
102 }
103
104 /**
105  * Read DataPoints from a DataFile
106  * @param df - The DataFile to read from
107  * @param buffer - Array to fill with DataPoints
108  * @param index - Index to start reading at (inclusive)
109  * @param amount - Maximum number of DataPoints to read
110  * @returns - Actual number of points read (If smaller than amount, the end of the file was reached)
111  */
112 int Data_Read(DataFile * df, DataPoint * buffer, int index, int amount)
113 {
114         assert(df != NULL);
115         assert(buffer != NULL);
116         assert(index >= 0);
117         assert(amount > 0);
118         
119         // If we would read past the end of the file, reduce the amount of points to read
120         pthread_mutex_lock(&(df->mutex));
121                 if (index + amount >= df->num_points)
122                 {
123                         Log(LOGDEBUG, "Requested %d points but will only read %d to get to EOF", amount, df->num_points - index);
124                         amount = df->num_points - index;
125                 }
126         pthread_mutex_unlock(&(df->mutex));
127
128         // Go to position in file
129         if (fseek(df->read_file, index*sizeof(DataPoint), SEEK_SET))
130         {
131                 Fatal("Error seeking to position %d in DataFile %s - %s", index, df->filename, strerror(errno));
132         }
133
134         // Attempt to read the DataPoints
135         int amount_read = fread(buffer, sizeof(DataPoint), amount, df->read_file);
136
137         // Check if correct number of points were read
138         if (amount_read != amount)
139         {
140                 Fatal("Read %d points instead of %d from DataFile %s - %s", amount_read, amount, df->filename, strerror(errno));
141         }
142
143         return amount;
144 }
145
146 /**
147  * Print data points between two indexes using a given format
148  * @param df - DataFile to print
149  * @param start_index - Index to start at (inclusive)
150  * @param end_index - Index to end at (inclusive)
151  * @param format - The format to use
152  */
153 void Data_Print(DataFile * df, int start_index, int end_index, DataFormat format)
154 {
155         assert(df != NULL);
156         assert(start_index >= 0);
157         assert(end_index <= df->num_points-1);
158
159         const char * fmt_string; // Format for each data point
160         char seperator; // Character used to seperate successive data points
161         
162         // Determine what format string and seperator character to use
163         switch (format)
164         {
165                 case JSON:
166                         fmt_string = "[%f,%f]";
167                         seperator = ',';
168                         // For JSON we need an opening bracket
169                         FCGI_PrintRaw("["); 
170                         break;
171                 case TSV:
172                         fmt_string = "%f\t%f";
173                         seperator = '\n';
174                         break;
175         }
176
177         DataPoint buffer[DATA_BUFSIZ]; // Buffer
178
179         int index = start_index;
180
181         // Repeat until all DataPoints are printed
182         while (index <= end_index)
183         {
184                 // Fill the buffer from the DataFile
185                 int amount_read = Data_Read(df, buffer, index, DATA_BUFSIZ);
186
187                 // Print all points in the buffer
188                 for (int i = 0; i < amount_read; ++i)
189                 {
190                         // Print individual DataPoint
191                         FCGI_PrintRaw(fmt_string, buffer[i].time_stamp, buffer[i].value);
192                         
193                         // Last seperator is not required
194                         if (index+1 < end_index)
195                                 FCGI_PrintRaw("%c", seperator);
196
197                         // Advance the position in the DataFile
198                         ++index;
199                 }
200         }
201         
202         switch (format)
203         {
204                 case JSON:
205                         // For JSON we need a closing bracket
206                         FCGI_PrintRaw("]"); 
207                         break;
208                 default:
209                         break;
210         }
211 }
212
213 /**
214  * Print data points between two time stamps using a given format.
215  * Prints nothing if the time stamp
216  * @param df - DataFile to print
217  * @param start_time - Time to start from (inclusive)
218  * @param end_time - Time to end at (inclusive)
219  * @param format - The format to use
220  */
221 void Data_PrintTimes(DataFile * df, double start_time, double end_time, DataFormat format)
222 {
223         assert(df != NULL);
224         assert(start_time > 0);
225         assert(end_time > 0);
226         assert(end_time > start_time);
227         
228         DataPoint closest;
229
230         // Get starting index
231         int start_index = Data_FindByTime(df, start_time, &closest);
232
233         // Start time is greater than most recent time stamp
234         if (start_index >= df->num_points-1 && closest.time_stamp < start_time)
235         {
236                 Data_Print(df, 0, 0, format); // Will print "empty" dataset
237                 return;
238         }
239
240         // Get finishing index
241         int end_index = Data_FindByTime(df, end_time, &closest);
242
243         // Print data between the indexes
244         Data_Print(df, start_index, end_index, format);
245 }
246
247 /**
248  * Get the index of the DataPoint closest to a given time stamp
249  * @param df - DataFile to search
250  * @param time_stamp - The time stamp to search for
251  * @param closest - If not NULL, will be filled with the DataPoint chosen
252  * @returns index of DataPoint with the *closest* time stamp to that given
253  */
254 int Data_FindByTime(DataFile * df, double time_stamp, DataPoint * closest)
255 {
256         assert(df != NULL);
257         assert(time_stamp >= 0);
258         assert(closest != NULL);
259
260         DataPoint tmp; // Current DataPoint in binary search
261
262         int lower = 0; // lower index in binary search
263         pthread_mutex_lock(&(df->mutex));
264                 int upper = df->num_points - 1; // upper index in binary search
265         pthread_mutex_unlock(&(df->mutex));
266         int index = 0; // current index in binary search
267
268         // Commence binary search:
269         while (upper - lower > 1)
270         {
271                 // Pick midpoint
272                 index = lower + ((upper - lower)/2);
273
274                 // Look at DataPoint
275                 if (Data_Read(df, &tmp, index, 1) != 1)
276                 {
277                         Fatal("Couldn't read DataFile %s at index %d", df->filename, index);
278                 }
279
280                 // Change search interval to either half appropriately
281                 if (tmp.time_stamp > time_stamp)
282                 {
283                         upper = index;
284                 }
285                 else if (tmp.time_stamp < time_stamp)
286                 {
287                         lower = index;
288                 }
289         }
290
291         // Store closest DataPoint
292         if (closest != NULL)
293                 *closest = tmp;
294         
295         return index;
296         
297 }

UCC git Repository :: git.ucc.asn.au