import time
import board
import pwmio, digitalio
from adafruit_motor import servo
from adafruit_debouncer import Button

from adafruit_ble import BLERadio #use bluetooh radio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement #how they display themselves
from adafruit_ble.services.nordic import UARTService #How bluetooth exchanges info
from adafruit_bluefruit_connect.button_packet import ButtonPacket #data envelopes - packets #mimicks buttons
from adafruit_bluefruit_connect.color_packet import ColorPacket #mimicks the color wheel
from adafruit_bluefruit_connect.raw_text_packet import RawTextPacket #mimicks text

# IMPORTANT: This must be 11 char or less or your code WILL NOT WORK
# name of advertised device that we are seeking:
receiver_name = "chris-k"

ble = BLERadio() #work with bluetooth radio
uart_connection = None

def send_packet(uart_connection_name, packet): #sends the stuff to the receiver
    """Returns False if no longer connected."""
    try:
        uart_connection_name[UARTService].write(packet.to_bytes())
    except:  # pylint: disable=bare-except
        try:
            uart_connection[UARTService].write(packet)
        except:  # pylint: disable=bare-except
            try:
                uart_connection_name.disconnect()
            except:  # pylint: disable=bare-except
                pass
            print("No longer connected")
            return False
    return True #If it does send the packet

# create a PWMOut object on Pin A2.
pwm = pwmio.PWMOut(board.A1, frequency=50)

# Create a servo object, my_servo.
my_servo = servo.ContinuousServo(pwm)


# Use Pull.UP for external buttons wired to ground
button_A_input = digitalio.DigitalInOut(board.A3)
button_A_input.switch_to_input(digitalio.Pull.UP) # Note: Pull.UP for external buttons
button_A = Button(button_A_input, value_when_pressed = False)


while True:
    if not uart_connection or not uart_connection.connected:  # If not connected...
        print("Scanning...")
        for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=5):  # Scan...
            if UARTService in adv.services:  # If UARTService found...
                if adv.complete_name == receiver_name:
                    uart_connection = ble.connect(adv)  # Create a UART connection...
                    print(f"I've found and connected to {receiver_name}!")
                    break # MUST include this here or code will never continue after connection.
        # Stop scanning whether or not we are connected.
        ble.stop_scan()
    while uart_connection and uart_connection.connected:
        button_A.update()
        if button_A.pressed : # Button is pressed when False
            print("BUTTON IS PRESSED!")
            my_servo.throttle = 1.0
            time.sleep(6.5)
            my_servo.throttle = -0.1
            print("Test")
            user_input = "play\r\n"
            print("Test")
            if not send_packet(uart_connection, user_input):
                print("test")
                uart_connection = None
            print("Reached here!")
            time.sleep(1)
            my_servo.throttle = -1.0
            time.sleep(7.1)
            my_servo.throttle = -0.05
            time.sleep(1)




