Thursday, March 5, 2020

Python3 example auto Monitor SmartCard and MySQL Query with tkinter

from __future__ import print_function
from smartcard.CardMonitoring import CardMonitor, CardObserver
#from smartcard.util import toHexString
import binascii
import io
import os
import sys
from PIL import Image
from smartcard.System import readers
from smartcard.util import HexListToBinString, toHexString, toBytes
from smartcard.CardMonitoring import CardMonitor, CardObserver
# from tkinter import *
from tkinter import *
from time import sleep
# import mysmartcard_monitor
import mysql.connector

# a simple card observer that prints inserted/removed cards
class PrintObserver(CardObserver):
    """A simple card observer that is notified
    when cards are inserted/removed from the system and
    prints the list of cards    """

    def __init__(selftv_cidtv_nametv_hntv_mothertv_father):
        self.tv_cid = tv_cid
        self.tv_name = tv_name
        self.tv_hn = tv_hn
        self.tv_mother = tv_mother
        self.tv_father = tv_father

    #  # Check card
    # SELECT = [0x00, 0xA4, 0x04, 0x00, 0x08]
    # THAI_CARD = [0xA0, 0x00, 0x00, 0x00, 0x54, 0x48, 0x00, 0x01]
    # # CID
    # CMD_CID = [0x80, 0xb0, 0x00, 0x04, 0x02, 0x00, 0x0d]

    # Thailand ID Smartcard
    # def thai2unicode(data):
    #     result = ''
    #     result = bytes(data).decode('tis-620')
    #     return result.strip()

    # tis-620 to utf-8
    def thai2unicode(selfdata): # for python 2 convert thai to unicode
        # print("in th2uni")
        result = ''
        if isinstance(data, list):
            for d in data:
                if (sys.version_info.major < 3):
                    result += unicode(chr(d),"tis-620")
                else :
                    result += chr(d).decode("tis-620").encode("utf-8")
        else :
            result = data.decode("tis-620").encode("utf-8")
        return result.strip()

    def thai2unicode2(selfdata): # for python 3 convert thai to unicode
        result = ''
        result = bytes(data).decode('tis-620')
        return result.strip();

    def getData(self,connectioncmdreq = [0x000xc00x000x00]):
        # print("getdata")
        data, sw1, sw2 = connection.transmit(cmd)
        data, sw1, sw2 = connection.transmit(req + [cmd[-1]])       
        return [data, sw1, sw2]

    def readCard(self):
        print("in readCard()")
        # Check card
        SELECT = [0x000xA40x040x000x08]
        THAI_CARD = [0xA00x000x000x000x540x480x000x01]
        # CID
        CMD_CID = [0x800xb00x000x040x020x000x0d]

        # Photo_Part1/20
        CMD_PHOTO1 = [0x800xb00x010x7B0x020x000xFF]
        # Photo_Part2/20
        CMD_PHOTO2 = [0x800xb00x020x7A0x020x000xFF]
        # Photo_Part3/20
        CMD_PHOTO3 = [0x800xb00x030x790x020x000xFF]
        # Photo_Part4/20
        CMD_PHOTO4 = [0x800xb00x040x780x020x000xFF]
        # Photo_Part5/20
        CMD_PHOTO5 = [0x800xb00x050x770x020x000xFF]
        # Photo_Part6/20
        CMD_PHOTO6 = [0x800xb00x060x760x020x000xFF]
        # Photo_Part7/20
        CMD_PHOTO7 = [0x800xb00x070x750x020x000xFF]
        # Photo_Part8/20
        CMD_PHOTO8 = [0x800xb00x080x740x020x000xFF]
        # Photo_Part9/20
        CMD_PHOTO9 = [0x800xb00x090x730x020x000xFF]
        # Photo_Part10/20
        CMD_PHOTO10 = [0x800xb00x0A0x720x020x000xFF]
        # Photo_Part11/20
        CMD_PHOTO11 = [0x800xb00x0B0x710x020x000xFF]
        # Photo_Part12/20
        CMD_PHOTO12 = [0x800xb00x0C0x700x020x000xFF]
        # Photo_Part13/20
        CMD_PHOTO13 = [0x800xb00x0D0x6F0x020x000xFF]
        # Photo_Part14/20
        CMD_PHOTO14 = [0x800xb00x0E0x6E0x020x000xFF]
        # Photo_Part15/20
        CMD_PHOTO15 = [0x800xb00x0F0x6D0x020x000xFF]
        # Photo_Part16/20
        CMD_PHOTO16 = [0x800xb00x100x6C0x020x000xFF]
        # Photo_Part17/20
        CMD_PHOTO17 = [0x800xb00x110x6B0x020x000xFF]
        # Photo_Part18/20
        CMD_PHOTO18 = [0x800xb00x120x6A0x020x000xFF]
        # Photo_Part19/20
        CMD_PHOTO19 = [0x800xb00x130x690x020x000xFF]
        # Photo_Part20/20
        CMD_PHOTO20 = [0x800xb00x140x680x020x000xFF]
        # Get all the available readers

        readerList = readers()
        reader = readerList[0]
        print ("Using:", reader)

        connection = reader.createConnection()       
        connection.connect()
        atr = connection.getATR()
        print ("ATR: " + toHexString(atr))

        if (atr[0] == 0x3B & atr[1] == 0x67):
            req = [0x000xc00x000x01]
        else:
            req = [0x000xc00x000x00]

        data, sw1, sw2 = connection.transmit(SELECT + THAI_CARD)
        print ("Select Applet: %02X %02X" % (sw1, sw2))

        data = self.getData(connection, CMD_CID, req)
        cid = self.thai2unicode2(data[0])
        print("CID: " + cid)       
        self.tv_cid.set(cid)

        mydb = mysql.connector.connect(
        host="192.168.1.2",
        user="user1",
        passwd="user1",
        database="mydb"
        )

        mycursor = mydb.cursor()

        mycursor.execute(f"SELECT concat(title,name,' ', surname) as name, id, mother, father FROM tb_user where cid = '{cid}' order by id desc limit 1")

        myresult = mycursor.fetchall()

        # for x in myresult:
        #     print(x[0])

        myname = myresult[0][0]
        myhn = myresult[0][1]
        mymother = myresult[0][2]
        myfather = myresult[0][3]

        print(myname)
        self.tv_name.set(myname)

        print(myhn)
        self.tv_hn.set(myhn)

        print(mymother)
        self.tv_mother.set(mymother)

        print(myfather)
        self.tv_father.set(myfather)

        '''
        # PHOTO
        photo = self.getData(connection, CMD_PHOTO1, req)[0]
        photo += self.getData(connection, CMD_PHOTO2, req)[0]
        photo += self.getData(connection, CMD_PHOTO3, req)[0]
        photo += self.getData(connection, CMD_PHOTO4, req)[0]
        photo += self.getData(connection, CMD_PHOTO5, req)[0]
        photo += self.getData(connection, CMD_PHOTO6, req)[0]
        photo += self.getData(connection, CMD_PHOTO7, req)[0]
        photo += self.getData(connection, CMD_PHOTO8, req)[0]
        photo += self.getData(connection, CMD_PHOTO9, req)[0]
        photo += self.getData(connection, CMD_PHOTO10, req)[0]
        photo += self.getData(connection, CMD_PHOTO11, req)[0]
        photo += self.getData(connection, CMD_PHOTO12, req)[0]
        photo += self.getData(connection, CMD_PHOTO13, req)[0]
        photo += self.getData(connection, CMD_PHOTO14, req)[0]
        photo += self.getData(connection, CMD_PHOTO15, req)[0]
        photo += self.getData(connection, CMD_PHOTO16, req)[0]
        photo += self.getData(connection, CMD_PHOTO17, req)[0]
        photo += self.getData(connection, CMD_PHOTO18, req)[0]
        photo += self.getData(connection, CMD_PHOTO19, req)[0]
        photo += self.getData(connection, CMD_PHOTO20, req)[0]
        data = HexListToBinString(photo)
        f = open(cid + ".jpg", "wb")
        f.write(data)
        f.close

        print("Photo successed")
        # connection.close()
        # sleep(10)   
        # reader.close()     
        return reader;
        '''
        # connection.close()
        reader.close() 
        

    def update(selfobservableactions):
        (addedcards, removedcards) = actions
        for card in addedcards:
            print("+Inserted: ", toHexString(card.atr))    
            try:     
                self.readCard()                
            except:
                print("Exception reader")

            im = Image.open(self.tv_cid.get() + ".jpg")
            im.save(self.tv_cid.get() + ".png")
            # print("CID2: ")
            # self.tv_cid.set(cid)

        for card in removedcards:
            self.tv_cid.set("")
            self.tv_name.set("")
            self.tv_hn.set("")
            self.tv_mother.set("")
            self.tv_father.set("")
            # connection.close()
            # reader.close()
            print("-Removed: ", toHexString(card.atr))

def gui():

    def on_click(e):    
        val = readCard()
        #print(f'cid {val}')
        # tv_cid.set(f'{lbs:.2f} lbs.')
        tv_cid.set(val)

    root = Tk()
    # root.option_add("*Font", "Loma 16")

    tv_cid = StringVar()
    tv_name = StringVar()
    tv_hn = StringVar()
    tv_mother = StringVar()
    tv_father = StringVar()

    f1 = Frame(root, padx=10pady=10)
    f1.option_add("*Font""Loma 10")
    f1.pack()

    f2 = Frame(root, padx=10pady=10)
    f2.option_add("*Font""Loma 10")
    f2.pack()
    # f2.pack(ipadx=10, ipady=10)

    f3 = Frame(root, padx=10pady=10)
    f3.option_add("*Font""Loma 10")
    f3.pack()

    f4 = Frame(root, padx=10pady=10)
    f4.option_add("*Font""Loma 10")
    f4.pack()

    f5 = Frame(root, padx=10pady=10)
    f5.option_add("*Font""Loma 10")
    f5.pack()

    Label(f1, text="เลขประจำตัวประชาชน:"width=20bg="yellow"anchor=E).pack(side=LEFT)
    lbl_cid = Entry(f1, width=50textvariable=tv_cid)
    lbl_cid.pack(side=LEFT)

    Label(f2, text="ชื่อ-สกุล:"width=20bg="yellow"anchor=E).pack(side=LEFT)
    lbl_name = Entry(f2, width=50textvariable=tv_name)
    lbl_name.pack(side=LEFT)

    Label(f3, text="เลขประจำตัวผู้ป่วย:"width=20bg="yellow"anchor=E).pack(side=LEFT)
    lbl_hn = Entry(f3, width=50textvariable=tv_hn)
    lbl_hn.pack(side=LEFT)

    Label(f4, text="ชื่อมารดา:"width=20bg="yellow"anchor=E).pack(side=LEFT)
    lbl_mother = Entry(f4, width=50textvariable=tv_mother)
    lbl_mother.pack(side=LEFT)

    Label(f5, text="ชื่อบิดา:"width=20bg="yellow"anchor=E).pack(side=LEFT)
    lbl_father = Entry(f5, width=50textvariable=tv_father)
    lbl_father.pack(side=LEFT)

    # btn_read = Button(root, text="Read")
    # btn_read.pack(side=LEFT)

    # btn_read.bind("", on_click)

    cardmonitor = CardMonitor()
    cardobserver = PrintObserver(tv_cid, tv_name, tv_hn, tv_mother, tv_father)
    cardmonitor.addObserver(cardobserver)

    root.mainloop()

def main():
    # readCard()
    gui()

if __name__ == "__main__":    
    gui()

No comments:

Post a Comment