# demo.py : 

# Raspberry Pi Pico - Decision tree classifier demo.

# No copyright, 2020-2021, Garth Zeglin.  This file is explicitly placed in the public domain.

# The decision tree function is kept in a separate .py file which 
# was generated from data using classifier_gen.py.

# Import CircuitPython modules.
import board
import time
import analogio

# Import filters. These files should be copied to the top-level
# directory of the CIRCUITPY filesystem on the Pico.
import linear

# Import the generated classifier, which should copied into CIRCUITPY.
import classifier

#---------------------------------------------------------------
# Set up the hardware.

# Set up an analogs input on ADC0 (GP26), which is physically pin 31.
# E.g., this may be attached to two axes of an accelerometer.
x_in = analogio.AnalogIn(board.A0)
y_in = analogio.AnalogIn(board.A1)

#---------------------------------------------------------------
# Run the main event loop.

# Use the high-precision clock to regulate a precise *average* sampling rate.
sampling_interval  = 100000000           # 0.1 sec period of 10 Hz in nanoseconds
next_sample_time   = time.monotonic_ns()

while True:
    # read the current nanosecond clock
    now = time.monotonic_ns()
    if now >= next_sample_time:
        # Advance the next event time; by spacing out the timestamps at precise
        # intervals, the individual sample times may have 'jitter', but the
        # average rate will be exact.
        next_sample_time += sampling_interval
        
        # Read the ADC values as synchronously as possible
        raw_x = x_in.value
        raw_y = y_in.value
        
        # apply linear calibration to find the unit gravity vector direction
        calib_x = linear.map(raw_x, 26240, 39120, -1.0, 1.0)
        calib_y = linear.map(raw_y, 26288, 39360, -1.0, 1.0)

        # Use the classifier to label the current state.
        label = classifier.classify([calib_x, calib_y])

        # Print the data and label for plotting.
        print((calib_x, calib_y, label))

        # Print a .CSV record while recording training data.
        # print(f"4,{calib_x},{calib_y}")
