# cPy - storage scope with playback implemented on FSK0001
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-06-18  initial release

import	time
from	leds64_oscilloscope	import	Potm8, Oscilloscope64
from	logger_dict			import	Logger

# Connections:
#    IO26=POT
#    IO15=DIN, IO2=CS, IO0=CLK

# ===================== StorageScope =======================

class StorageScope:
    
    def __init__(self):
        self.potm = Potm8()
        self.osc64 = Oscilloscope64()
        self.logger = Logger(100, fn='logger.json')
        
        
    # acquire and save potmeter data for 10 seconds
    def acquire(self):
        print('start acquire ...')
        for _ in range(100):
            y = self.potm.get8()
            self.osc64.add(y)
            self.logger.append(y)
            time.sleep_ms(100)
        self.osc64.off()
        self.logger.save()
        print('finished')
        
        
    # potmeter controlled windowed playback of stored data
    def playBack(self):
        
        # get potmeter as 2-tuple i.e. 0..91 (database idx) and 0..100 (%)
        def getX():
            x = 94-int(self.potm.get()*30.3)
            return min(max(0, x), 91), 100*x//91
        
        
        try:
            self.logger.load()
            last_data = None
            while True:
                x, perc = getX()
                data    = self.logger.query(x)
                if data != last_data:					# refresh when data changed only
                    for y in data: self.osc64.add(y)
                    last_data = data
                print(f'{perc}%')
                time.sleep_ms(500)
        finally: self.osc64.off()
            
        
# ========================== main ==============================

#StorageScope().acquire()
StorageScope().playBack()                                                                                                                                                                                                                                                                                                                                                                                                                                                                     

# ========================= end ============================
