# standard imports import logging import datetime logg = logging.getLogger().getChild(__name__) class GasAggregator: def __init__(self, capacity): self.avg = 0 self.count = 0 self.timestamp = datetime.datetime.utcnow() self.buffer_cursor = 0 self.buffer_capacity = capacity self.buffer = [None] * self.buffer_capacity self.initial = False self.aggr = 0 self.local_aggr = 0 self.local_count = 0 self.local_high = 0 self.local_low = 0 def put(self, v): self.local_aggr += v self.local_count += 1 if self.local_low == 0: self.local_low = v if v > self.local_high: self.local_high = v elif v < self.local_low: self.local_low = v self.count += 1 def process(self): if self.local_count == 0: logg.info('skipping 0 tx block') return False v = int(self.local_aggr / self.local_count) logg.info('calculated new block average {} from {} tx samples, low {} high {}'.format(v, self.local_count, self.local_low, self.local_high)) self.local_aggr = 0 self.local_count = 0 if not self.initial: for i in range(self.buffer_capacity): self.buffer[i] = v self.initial = True else: self.buffer[self.buffer_cursor] = v self.buffer_cursor += 1 self.buffer_cursor %= self.buffer_capacity self.aggr = self.avg * self.count self.aggr += v self.avg = int(self.aggr / self.count) logg.info('added {} to aggregate {} new average {} from {} samples'.format(v, self.aggr, self.avg, self.count)) return True def get(self, n=0): if n == 0: n = self.capacity cursor = self.buffer_cursor aggr = 0 i = 0 while i < n: v = self.buffer[cursor] aggr += v cursor -= 1 if cursor < 0: cursor = self.buffer_capacity - 1 i += 1 return int(aggr / n) def block_callback(self, block, tx): logg.info('synced {}'.format(block)) if self.process(): v = self.get(10) logg.info('last 6 average now {}'.format(v)) v = self.get(360) logg.info('last 360 average now {}'.format(v))