################################################################################################### 
# Scan averaging sensor value, storing all values, mean and variance
###################################################################################################


class AnalogInput(ReadonlyRegisterBase):
    def doRead(self):
        time.sleep(0.001)
        self.val = to_array(self.calc(), 'd')
        return self.val
        
class SinusoidSample(AnalogInput):
    def calc(self):
        self.x = self.x + 0.1 if hasattr(self, 'x') else 0.0
        noise = (random.random() - 0.5) / 10.0
        return math.sin(self.x)  + noise

class SinusoidTime(AnalogInput):
    def calc(self):
        noise = (random.random() - 0.5) / 10.0
        return math.sin(time.time())  + noise

class Const(AnalogInput):
    def calc(self):
        return 5.0
        

add_device(SinusoidSample("ai1"), True)
add_device(SinusoidTime("ai2"), True)
add_device(Const("ai3"), True)

av1 = create_averager(ai3, 5, -0.1)
av2 = create_averager(ai2, 5, 0)

#ai1.setPolling(10)
#ai2.setPolling(10)
ai3.setPolling(10)


#av1.setMonitored(True)
#av2.setMonitored(True)

sleep(0.5) #Give some time for the averager to fill its buffer, before first use
#res= lscan(out, (ai1, av1, av1.samples,  ai2, av2, av2.samples), 0, 40, 20, 0.1)
res= lscan(out, ( av1, av1.samples,  av2, av2.samples), 0, 40, 20, 0.1)


