การเขียนโปรแกรมเพื่อเชื่อมต่อ Smart Card Reader

การเขียนโปรแกรมเพื่อเชื่อมต่อ Smart Card Reader และตรวจสอบสถานะด้วย Python สามารถทำได้โดยใช้ไลบรารี pyscard ซึ่งเป็นไลบรารีที่ช่วยในการเชื่อมต่อและทำงานกับ Smart Card Reader ผ่านโปรโตคอล PC/SC (Personal Computer/Smart Card). โดยขั้นตอนพื้นฐานมีดังนี้:
ขั้นตอนการติดตั้ง
- ติดตั้งไลบรารี pyscard โดยใช้คำสั่ง
pip install pyscard
Code language: Python (python)โค้ดตัวอย่างสำหรับการเชื่อมต่อและตรวจสอบสถานะ
from smartcard.System import readers
from smartcard.util import toHexString
# ค้นหา Reader ที่เชื่อมต่ออยู่
reader_list = readers()
if not reader_list:
    print("ไม่พบ Smart Card Reader ที่เชื่อมต่ออยู่")
else:
    # เลือก Reader ตัวแรก
    reader = reader_list[0]
    print(f"กำลังใช้ Reader: {reader}")
    # เริ่มการเชื่อมต่อกับ Smart Card
    connection = reader.createConnection()
    try:
        connection.connect()
        print("เชื่อมต่อกับ Smart Card สำเร็จแล้ว")
        # ส่งคำสั่ง APDU เพื่ออ่านข้อมูลเบื้องต้น (ตัวอย่างเช่น Select File หรือ Get Response)
        command = [0x00, 0xA4, 0x04, 0x00, 0x00]  # ตัวอย่างคำสั่ง APDU
        data, sw1, sw2 = connection.transmit(command)
        # ตรวจสอบสถานะการส่งคำสั่ง
        if sw1 == 0x90 and sw2 == 0x00:
            print("คำสั่งสำเร็จ")
            print("ข้อมูลที่ได้:", toHexString(data))
        else:
            print(f"คำสั่งล้มเหลว, สถานะ: {sw1:X} {sw2:X}")
    except Exception as e:
        print("ไม่สามารถเชื่อมต่อกับ Smart Card:", e)
    finally:
        connection.disconnect()
Code language: Python (python)คำอธิบาย
- เราใช้ readers()เพื่อค้นหา Reader ที่เชื่อมต่ออยู่ และใช้ตัวแรกในรายการนี้
- createConnection()สร้างการเชื่อมต่อกับ Smart Card ที่มีการใส่เข้าไปใน Reader
- ใช้ transmit()ส่งคำสั่ง APDU เพื่อโต้ตอบกับการ์ด เช่น การอ่านข้อมูลพื้นฐาน
- ตรวจสอบรหัสสถานะ (sw1,sw2) เพื่อดูว่าการส่งคำสั่งสำเร็จหรือไม่ (สถานะ0x9000หมายถึงสำเร็จ)






