"""
This software is released under a modified beer-ware license:
 * <dan@appliedcarbon.org> was the origonal author of this file. As long as you
 * retain this notice you can do whatever you want with this code. If we meet
 * some day, and you think this stuff is worth it, you can buy me a rootbeer in
 * return.
"""

#This script uses USB HID Reports to toggle the TX/RX lights on the SineStick.
#The SineStick is built around the SiLabs CP2112 USB-to-I2C bridge chip.

#Version 1.0, 2020-01-01


#Fedora install:
#	sudo dnf install hidapi hidapi-devel
#	pip3 install hid
#Remember to use sudo when runing this test script
import hid

import time

print("Running....\n")

#Default codes for CP2112 device
usb_vid = 0x10c4
usb_pid = 0xea90

print("Using first CP2112 device found:")
usb_hid_device = hid.Device(usb_vid, usb_pid)
print(f'\tDevice manufacturer: {usb_hid_device.manufacturer}')
print(f'\tProduct: {usb_hid_device.product}')
print(f'\tSerial Number: {usb_hid_device.serial}')


#First thing first: configure the GPIO pins

#HID Report IDs:
#0x02 Get/Set GPIO Configuration
#0x03 Get GPIO
#0x04 Set GPIO

#With ID 0x02, send four bytes: Direction, Push-Pull, Special, Clock Divider
#GPIO0 is LSB, GPIO7 is MSB

#Build the command:
#0x02 = HID Report ID
#0x03 = Set GPIO0/1 to output
#0x00 = b0000_0000, set everything to open drain
#0x01 = bxxxx_x001, set GPIO0 and GPIO1 to GPIO (note: weird layout)
#0x00 = Set clock to 48 MHz

usb_hid_device.write(bytes("\x02\x03\x00\x01\x00", 'utf-8'))



#Turn on LEDs (powered via resistors to GPIO pins, pull low to power on)

while (True):

	#Set GPIO0/1 to HIGH Z
	#0x04 = HID Report ID, Set GPIO 
	#0x03 = Latch value, GPIO0/1 set to 1
	#0x03 = Latch mask, only change GPIO0/1
	usb_hid_device.write(bytes("\x04\x03\x03", 'utf-8'))
	print("Off...")

	time.sleep(0.3)

	#Set GPIO0/1 to LOW
	#0x04 = HID Report ID, Set GPIO 
	#0x00 = Latch value, GPIO0/1 set to 0
	#0x03 = Latch mask, only change GPIO0/1
	usb_hid_device.write(bytes("\x04\x00\x03", 'utf-8'))
	print("On...")

	time.sleep(0.3)

print("Done!")
