koder aka kdanilov | 63ad206 | 2015-04-27 13:11:40 +0300 | [diff] [blame] | 1 | import array |
| 2 | import threading |
| 3 | |
| 4 | |
| 5 | class SensorDatastore(object): |
| 6 | def __init__(self, stime=None): |
| 7 | self.lock = threading.Lock() |
| 8 | self.stime = stime |
| 9 | |
| 10 | self.min_size = 60 * 60 |
| 11 | self.max_size = 60 * 61 |
| 12 | |
| 13 | self.data = { |
| 14 | 'testnodes:io': array.array("B"), |
| 15 | 'testnodes:cpu': array.array("B"), |
| 16 | } |
| 17 | |
| 18 | def get_values(self, name, start, end): |
| 19 | assert end >= start |
| 20 | |
| 21 | if end == start: |
| 22 | return [] |
| 23 | |
| 24 | with self.lock: |
| 25 | curr_arr = self.data[name] |
| 26 | if self.stime is None: |
| 27 | return [] |
| 28 | |
| 29 | sidx = start - self.stime |
| 30 | eidx = end - self.stime |
| 31 | |
| 32 | if sidx < 0 and eidx < 0: |
| 33 | return [0] * (end - start) |
| 34 | elif sidx < 0: |
| 35 | return [0] * (-sidx) + curr_arr[:eidx] |
| 36 | return curr_arr[sidx:eidx] |
| 37 | |
| 38 | def update_values(self, data_time, vals, add=False): |
| 39 | with self.lock: |
| 40 | if self.stime is None: |
| 41 | self.stime = data_time |
| 42 | |
| 43 | for name, value in vals.items(): |
| 44 | curr_arr = self.data.setdefault(name, array.array("H")) |
| 45 | curr_end_time = len(curr_arr) + self.stime |
| 46 | |
| 47 | dtime = data_time - curr_end_time |
| 48 | |
| 49 | if dtime > 0: |
| 50 | curr_arr.extend([0] * dtime) |
| 51 | curr_arr.append(value) |
| 52 | elif dtime == 0: |
| 53 | curr_arr.append(value) |
| 54 | else: |
| 55 | # dtime < 0 |
| 56 | sindex = len(curr_arr) + dtime |
| 57 | if sindex > 0: |
| 58 | if add: |
| 59 | curr_arr[sindex] += value |
| 60 | else: |
| 61 | curr_arr[sindex].append(value) |