from iowp import IowFactory, I2C
from iowp.i2c_devices import I2CLCD

def main():
    factory = IowFactory.get_instance()
    if len(factory.get_devices()) == 0:
        print("No IO-Warrior devices found.")
        return
    print(factory)

    # Iow 1, SMF I2C and i2clcd (PCF8547 based LcD)
    iow_dev_1 = factory.get_iow_device(0)
    i2c_1 = I2C(I2C.I2C_SPEED_100KHZ)
    iow_dev_1.add_special_mode_function_impl(i2c_1)
    lcd_1 = I2CLCD(device_address=0x07, rows=2, cols=16)
    i2c_1.add_i2c_device(lcd_1)
    print(iow_dev_1)
    
    # Iow 2, SMF I2C and i2clcd (PCF8547 based LcD)
    iow_dev_2 = factory.get_iow_device(1)
    i2c_2 = I2C(I2C.I2C_SPEED_100KHZ)
    iow_dev_2.add_special_mode_function_impl(i2c_2)
    lcd_2 = I2CLCD(device_address=0x07, rows=2, cols=16)
    i2c_2.add_i2c_device(lcd_2)
    print(iow_dev_2)

    try:
        print("Clearing LCD...")
        lcd_1.clearLCD()
        lcd_2.clearLCD()

        print("Writing lines...")
        lcd_1.setCursor(0, 0)
        lcd_1.writeString("Hello iowp ")
        lcd_1.writeString(iow_dev_1.name)
        lcd_1.setCursor(1, 0)
        lcd_1.writeString("LCD 2x16 Ready")
        lcd_2.setCursor(0, 0)
        lcd_2.writeString("Hello iowp ")
        lcd_2.writeString(iow_dev_2.name)
        lcd_2.setCursor(1, 0)
        lcd_2.writeString("LCD 2x16 Ready")

        print("Testing special characters (smiley)...")
        smiley = [
            0b00000,
            0b01010,
            0b01010,
            0b00000,
            0b10001,
            0b01110,
            0b00000,
            0b00000
        ]
        lcd_1.createChar(0, smiley)
        lcd_1.setCursor(1, 15)
        lcd_1.writeString(chr(0))
        lcd_2.createChar(0, smiley)
        lcd_2.setCursor(1, 15)
        lcd_2.writeString(chr(0))
      
       
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    main()
