#!/usr/bin/env python3
# test_i2c_devices.py

import os
from maix import i2c

def list_i2c_devices():
    """List available I2C device nodes"""
    print("Available I2C devices:")
    
    # Check /dev directory
    try:
        dev_files = os.listdir("/dev")
        i2c_devices = [f for f in dev_files if "i2c" in f]
        if i2c_devices:
            for dev in sorted(i2c_devices):
                print(f"  /dev/{dev}")
        else:
            print("  No /dev/i2c-* devices found!")
    except Exception as e:
        print(f"  Error listing /dev: {e}")

def try_i2c_bus(bus_num):
    """Try to initialize an I2C bus"""
    try:
        bus = i2c.I2C(bus_num, i2c.Mode.MASTER)
        print(f"  I2C bus {bus_num}: OK")
        return True
    except RuntimeError as e:
        print(f"  I2C bus {bus_num}: {e}")
        return False
    except Exception as e:
        print(f"  I2C bus {bus_num}: Unexpected error: {e}")
        return False

def main():
    print("=" * 60)
    print("I2C Device Diagnostic")
    print("=" * 60)
    
    # List kernel devices
    list_i2c_devices()
    
    # Try common bus numbers
    print("\nTesting I2C buses:")
    working_buses = []
    for bus_num in range(10):
        if try_i2c_bus(bus_num):
            working_buses.append(bus_num)
    
    print(f"\nWorking buses: {working_buses}")
    
    if not working_buses:
        print("\nERROR: No I2C buses available!")
        print("Possible causes:")
        print("  1. I2C kernel driver not loaded")
        print("  2. Device tree doesn't enable I2C")
        print("  3. Different kernel version with different device naming")

if __name__ == "__main__":
    main()