from pyzk.zk import ZK

# Replace with the correct COM port (for RS232) or USB device path
# For USB, you may need to find the correct device path (e.g., /dev/ttyUSB0 on Linux)
device_port = 'COM3'  # Replace with your COM port or USB path
timeout = 5  # Timeout in seconds

try:
    # Initialize the ZK object
    zk = ZK(device_port, timeout=timeout, password=0, force_udp=False, ommit_ping=False)

    # Connect to the device
    conn = zk.connect()
    print("Connected to the device")

    # Disable the device to prevent unwanted operations
    conn.disable_device()
    print("Device disabled")

    # Get device information
    firmware_version = conn.get_firmware_version()
    print(f"Firmware Version: {firmware_version}")

    # Enable the device
    conn.enable_device()
    print("Device enabled")

    # Enroll a new user
    user_id = '1'
    user_name = 'Test User'
    privilege = 0  # Default privilege
    password = ''
    conn.set_user(uid=user_id, name=user_name, privilege=privilege, password=password)
    print(f"User {user_name} enrolled with ID {user_id}")

    # Capture a fingerprint for the enrolled user
    print("Please place your finger on the scanner to capture the fingerprint...")
    conn.enroll_user(user_id=user_id, temp_id=6)  # temp_id is the fingerprint template ID
    print("Fingerprint captured and enrolled")

    # Verify the fingerprint
    print("Please place your finger on the scanner to verify...")
    users = conn.get_users()
    for user in users:
        if user.user_id == user_id:
            print(f"Verifying user: {user.name}")
            if conn.verify_user(user):
                print("Fingerprint verified successfully!")
            else:
                print("Fingerprint verification failed!")
            break

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    if conn:
        conn.disconnect()
        print("Disconnected from the device")

        