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

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

    # Iow28, SMF LCD and LCD2x16
    iow_dev_28 = factory.get_iow28_device()
    lcd_28 = LCD2x16()
    iow_dev_28.add_special_mode_function_impl(lcd_28)
    print(iow_dev_28)
    
    # Iow24, SMF I2C and i2clcd (PCF8547 based LcD)
    iow_dev_24 = factory.get_iow24_device()
    i2c = I2C(I2C.I2C_SPEED_100KHZ)
    iow_dev_24.add_special_mode_function_impl(i2c)
    lcd_24 = I2CLCD(device_address=0x07, rows=2, cols=16)
    i2c.add_i2c_device(lcd_24)
    print(iow_dev_24)

    try:
        print("Clearing LCD...")
        lcd_28.clear_lcd()
        lcd_24.clearLCD()

        print("Writing lines...")
        lcd_28.write_line(1, True, "Hello iowp! (28)")
        lcd_28.write_line(2, True, "LCD 2x16 Ready")
        lcd_24.setCursor(0, 0)
        lcd_24.writeString("Hello iowp! (24)")
        lcd_24.setCursor(1, 0)
        lcd_24.writeString("LCD 2x16 Ready")

        print("Testing special characters (smiley)...")
        smiley = [
            0b00000,
            0b01010,
            0b01010,
            0b00000,
            0b10001,
            0b01110,
            0b00000,
            0b00000
        ]
        lcd_28.set_special_char(0, smiley)
        lcd_28.set_cursor(2, 16)
        lcd_28.write_string(chr(0))
        lcd_24.createChar(0, smiley)
        lcd_24.setCursor(1, 15)
        lcd_24.writeString(chr(0))
      
       
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    main()
