from pyjoulescope_driver import Driver, time64
from pyjoulescope_driver.record import Record, Writer
import logging
import time

import numpy as np

SAMPLING_FREQUENCY_HZ = 1000000

class XDetector():
    def __init__(self, threshold):
        self.threshold = threshold
        self.duration_in_range_sec = 0
        self.current_batch_mean_samples_in_range = False
        self.last_time = time.time()

    def data_callback(self, topic, value):
        #print(f'Data recieved on topic: {topic}, value length: {len(value)}')
        samples = value['data']
        print(f'Length of Data Received: {len(samples)} ')

    def start(self):
        print("Starting X Detector")
        with Driver() as d:
            devices = d.device_paths()
            device = devices[0]

            d.open(device)
            callback  = self.data_callback

            try:
                # configure the device
                d.publish(f'{device}/s/i/range/mode', 'manual')
                d.publish(f'{device}/s/i/range/select', '180 µA')
                d.publish(f'{device}/s/v/range/mode', 'auto')
                d.publish(f'{device}/h/fs', SAMPLING_FREQUENCY_HZ)

                # Subscribe to current data & stream
                d.subscribe(f'{device}/s/i/!data', ['pub'], callback, timeout = 0)
                self.start_time = time.time()
                d.publish(f'{device}/s/i/ctrl', 1, timeout = 0) # switch on the stream

                while True:
                    pass
                    try:
                        time.sleep(1)
                    except KeyboardInterrupt:
                        break

            finally:
                d.unsubscribe(f'{device}/s/i/!data', callback)
                d.publish(f'{device}/s/i/ctrl', 0, timeout = 0) # switch off the stream
                d.close(device)

if __name__ == '__main__':
    detector = XDetector(1e-6)
    detector.start()