# Python

##

## [เช็คความถูกต้องเลขบัตรประชาชน](https://python3.wannaphong.com/2016/07/python.html)&#x20;

หลักการตรวจเช็คความถูกต้องเลขบัตรประชาชน อ่านได้ที่ <http://www.thaiadmin.org/board/index.php?topic=53247.msg230422#msg230422>

```python
def checkPID(pid):
  if(len(pid) != 13): # ถ้า pid ไม่ใช่ 13 ให้คืนค่า False
    return False
  num=0 # ค่าสำหรับอ้างอิง index list ข้อมูลบัตรประชาชน
  num2=13 # ค่าประจำหลัก
  listdata=list(pid) # list ข้อมูลบัตรประชาชน
  sum=0 # ผลลัพธ์
  while num<12:
    sum+=int(listdata[num])*(num2-num) # นำค่า num เป็น index list แต่ละตัว * (num2 - num) แล้วรวมเข้ากับ sum
    num+=1 # เพิ่มค่า num อีก 1
  digit13 = sum%11 # sum หาร 11 เอาเศษ
  if digit13==0: # ถ้าเศษ = 0
    digit13=1 # ค่าหลักที่ 13 คือ 1
  elif digit13==1: # ถ้าเศษ = 1
    digit13=0 # ค่าหลักที่ 13 คือ 0
  else:
    digit13=11-digit13 # ถ้าเศษไม่ใช่กับอะไร ให้เอา 11 - digit13
  if digit13==int(listdata[12]): # ถ้าค่าหลักที่ 13 เท่ากับค่าหลักที่ 13 ที่ป้อนข้อมูลมา คืนค่า True
    return True
  else: # ถ้าค่าหลักที่ 13 ไม่เท่ากับค่าหลักที่ 13 ที่ป้อนข้อมูลมา คืนค่า False
    return False
```

```python
checkPID("เลขบัตรประชาชน")
```

Reference :  <https://python3.wannaphong.com/2016/07/python.html>

### ดึงข้อมูลจากวิกิพีเดีย

```python
import wikipedia
wikipedia.set_lang("th")
us = wikipedia.summary("สหรัฐอเมริกา", sentences=1)
print(us)
```

Output

```python
สหรัฐอเมริกา (อังกฤษ: United States of America) หรือมักย่อว่า สหรัฐฯ หรือ อเมริกา 
เป็นสหพันธรัฐประชาธิปไตย ปกครองภายใต้รัฐธรรมนูญ ประกอบด้วยรัฐ 50 รัฐ และหนึ่งเขตปกครองกลาง 
มี 48 รัฐและกรุงวอชิงตัน ดี.ซี.
```

### [Check Hardware & Software info](https://support.microsoft.com/th-th/topic/%E0%B8%84%E0%B8%B3%E0%B8%AD%E0%B8%98%E0%B8%B4%E0%B8%9A%E0%B8%B2%E0%B8%A2%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B7%E0%B8%AD%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5-msinfo32-exe-%E0%B8%A3%E0%B8%B0%E0%B8%9A%E0%B8%9A-microsoft-10d335d8-5834-90b4-8452-42c58e61f9fc)

```bash
msinfo32 /nfo C:\com_info.nfo
```

```bash
msinfo32 /report C:\com_info.txt
```

### เขียนโปรแกรม Bluetooth

ในภาษา Python มีโมดูลสำหรับใช้เขียนโปรแกรมควบคุม Bluetooth คือ โมดูล PyBluez

&#x20;สำหรับ Windows โหลด whl มาติดตั้งได้ที่ <http://www.lfd.uci.edu/~gohlke/pythonlibs/#pybluez>\
สำหรับ Linux และ Mac OS X ให้ทำการติดตั้ง Bluez ก่อน แล้วติดตั้งด้วยคำสั่ง

```python
pip install PyBluez
```

&#x20;**รับจำนวนและแสดง MAC address ของอุปกรณ์บลูทูธ**

```python
import bluetooth

nearby_devices = bluetooth.discover_devices(lookup_names=True)
print("found %d devices" % len(nearby_devices))

for addr, name in nearby_devices:
      print(" %s - %s" % (addr, name))
```

Output

```python
found 1 devices
 48:26:2C:92:A4:17 - iPhone ของ Sarawut
```

สามารถเขียนโค้ดโปรแกรมส่งข้อมูลโดยใช้ socket ผ่าน Bluetooth ดังนี้ ฝั่ง Client

```python
import bluetooth

serverMACAddress = '48:26:2C:92:A4:17'
port = 3
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect((serverMACAddress, port))
while True:
  text = input("Text : ")
  if text == "quit":
    break
  s.send(text)
s.close()
```

**ฝั่ง Server**

```python
import bluetooth

hostMACAddress = '48:26:2C:92:A4:17' # เป็น MAC address ของ Bluetooth adapter ใน server
port = 3
backlog = 1
size = 1024
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
try:
  client, clientInfo = s.accept()
  while 1:
    data = client.recv(size)
    if data:
      print(data)
      client.send(data) # Echo back to client
except:
  print("Closing socket")
client.close()
s.close()
```

&#x20;Code fork จาก <http://blog.kevindoran.co/bluetooth-programming-with-python-3/>\
เอกสารการใช้งาน <https://github.com/karulis/pybluez>\
ศึกษาโค้ดจากตัวอย่างได้ที่ <https://github.com/karulis/pybluez/tree/master/examples>\
บทความทั้งหมดในบล็อกนี้เขียนโดย นาย วรรณพงษ์ ภัททิยไพบูลย์ ที่ <https://python3.wannaphong.com/>

### cpuinfo()

&#x20;โมดูล Py-cpuinfo เป็นโมดูลสำหรับรับข้อมูล CPU เครื่องที่รัน โดยเป็น pure Python รองรับทั้ง Python 2 , 3 และใช้ MIT License\
\
ติดตั้งได้ด้วยคำสั่ง `pip install py-cpuinfo`\
\
**การใช้งาน**\
สามารถเรียกดูรายละเอียดได้ทันทีด้วยคำสั่ง `python -m cpuinfo`\
\
รับรายละเอียดในโค้ด Python ได้ด้วยคำสั่งตามตัวอย่างนี้

```python
import cpuinfo
info = cpuinfo.get_cpu_info()
print(info)
```

Output

```python
{'python_version': '3.8.10.final.0 (64 bit)', 'cpuinfo_version': [8, 0, 0], 
'cpuinfo_version_string': '8.0.0', 'arch': 'X86_64', 'bits': 64, 'count': 8, 
'arch_string_raw': 'AMD64', 'vendor_id_raw': 'GenuineIntel', 
'brand_raw': 'Intel(R) Core(TM) i3-10100 CPU @ 3.60GHz', 
'hz_advertised_friendly': '3.6000 GHz', 'hz_actual_friendly': '3.6000 GHz',
 'hz_advertised': [3600000000, 0], 'hz_actual': [3600000000, 0], 
 'l2_cache_size': 1048576, 'stepping': 3, 'model': 165, 'family': 6,
  'l3_cache_size': 6291456, 'flags': ['3dnow', '3dnowprefetch', 'abm', 'acpi', 
  'adx', 'aes', 'apic', 'avx', 'avx2', 'bmi1', 'bmi2', 'clflush', 'clflushopt',
   'cmov', 'cx16', 'cx8', 'de', 'ds_cpl', 'dtes64', 'dts', 'erms', 'est',
    'f16c', 'fma', 'fpu', 'fxsr', 'ht', 'ia64', 'intel_pt', 'invpcid', 
    'lahf_lm', 'mca', 'mce', 'mmx', 'monitor', 'movbe', 'mpx', 'msr', 'mtrr', 
    'osxsave', 'pae', 'pat', 'pbe', 'pcid', 'pclmulqdq', 'pdcm', 'pge', 'pni',
     'popcnt', 'pse', 'pse36', 'rdrnd', 'rdseed', 'sep', 'serial', 'sgx', 
     'sgx_lc', 'smap', 'smep', 'ss', 'sse', 'sse2', 'sse4_1', 'sse4_2', 
     'ssse3', 'tm', 'tm2', 'tsc', 'tscdeadline', 'vme', 'vmx', 'x2apic', 
     'xsave', 'xtpr'], 'l2_cache_line_size': 256, 'l2_cache_associativity': 6}
```

&#x20;อ่านรายละเอียดเพิ่มเติมได้ที่ <https://github.com/workhorsy/py-cpuinfo>\
Reference : <https://python3.wannaphong.com/2017/07/cpu-python.html>

### เล่นเสียง/เพลง MP3

&#x20;ติดตั้งได้ด้วยคำสั่ง `pip install playsound`\
\
สามารถเล่นไฟล์ได้ทั้งจากไฟล์และลิงค์จากเว็บ

```python
from playsound import playsound
playsound('เพลง.mp3')
```

หน้าหลักโมดูล playsound <https://github.com/TaylorSMarks/playsound>

### คำนวณดาราศาสตร์พื้นฐานด้วย PyEphem

&#x20;PyEphem เป็นโมดูลสำหรับงานคำนวณดาราศาสตร์พื้นฐานในภาษาไพทอน โดยสามารถคำนวณตำแหน่งของดวงอาทิตย์และดวงจันทร์ของโลก รวมไปถึงตำแหน่งของดาวหาง ตามเวลาที่กำหนดได้ และนอกจากนั้น สามารถคำนวณวันเวลาวันพระจันทร์เต็มดวงและดับได้ด้วย และมีความสามารถอื่น ๆ อีก\
\
รองรับทั้ง Python 2 และ Python 3\
ใช้ License: LGPL\
\
ติดตั้งได้ด้วยคำสั่ง `pip install pyephem`\
\
**ตัวอย่างการใช้งาน**

```python
>>> import ephem
>>> mars = ephem.Mars()
>>> mars.compute('2008/1/1')
>>> print mars.ra, mars.dec
# 5:59:27.35 26:56:27.4
```

เรามาคำนวณหาวันเวลาพระจันทร์เต็มดวงและดับด้วยกันครับ

```python
import ephem
d1 = ephem.next_full_moon('2017') # คำนวณในปี 2017
print(d1)
d2 = ephem.next_new_moon(d1)
print(d2)
```

Output

```bash
2017/1/12 11:33:58
2017/1/28 00:07:02
```

&#x20;อ่านเอกสารการใช้งานได้ที่ <http://rhodesmill.org/pyephem/>

### QR Code PromptPay

### Install

```python
pip install pypromptpay
```

### Using

```python
from pypromptpay import qr_code
qr_code(account,one_time=True,path_qr_code="",country="TH",money="",currency="THB")
```

* account is phone number or identification number.
* one\_time : if you use once than it's True.
* path\_qr\_code : path save file qr code image.
* country : TH
* money : money (if have)
* currency : THB

return True (if have path\_qr\_code) or text (if haven't path\_qr\_code)

### License

Apache Software License 2.0

### Develop

Wannaphong Phatthiyaphaibun (<wannaphong@kkumail.com>)

### Reference

[แนวนโยบายการใช้มาตรฐาน Thai QR Code ในธุรกรรมการชำระเงิน](https://www.bot.or.th/Thai/FIPCS/Documents/FPG/2562/ThaiPDF/25620084.pdf)

```bash
# -*- coding: utf-8 -*-
import crc16
import qrcode
def qr_code(account,one_time=True,path_qr_code="",country="TH",money="",currency="THB"):
    """
    qr_code(account,one_time=True,path_qr_code="",country="TH",money="",currency="THB")
    account is phone number or  identification number.
    one_time : if you use once than it's True.
    path_qr_code : path save qr code.
    country : TH
    money : money (if have)
    currency : THB
    """
    Version = "0002"+"01" # เวชั่นของ  PromptPay
    if one_time == True: # one_time คือ ต้องการให้โค้ดนี้ครั้งเดียวหรือไม่
        one_time = "010212" # 12 ใช้ครั้งเดียว
    else:
        one_time ="010211" # 11 ใช้ได้้หลายครั้ง
    
    if len(account) == 10 or len(account) == 13 : 
        merchant_account_information = "2937" # ข้อมูลผู้ขาย (เฉพาะเบอร์โทร และ บัตรประชาชน)
    else :
        merchant_account_information = "2939" # ข้อมูลผู้ขาย (เฉพาะเลขอ้างอิง)
        
    merchant_account_information += "0016"+"A000000677010111" # หมายเลขแอปพลิเคชั่น PromptPay
    if len(account) == 10: #ถ้าบัญชีนี้เป็นเบอร์โทร
        account = list(account)
        merchant_account_information += "011300" # 01 หมายเลขโทรศัพท์ ความยาว 13 ขึ้นต้น 00
        if country == "TH":
            merchant_account_information += "66" # รหัสประเทศ 66 คือประเทศไทย
        del account[0] # ตัดเลข 0 หน้าเบอร์ออก
        merchant_account_information += ''.join(account)
    elif len(account) == 13 : #ถ้าบัญชีนี้เป็นบัตรประชาชน
        merchant_account_information += "0213" + account.replace('-','')
    else : #ไม่ใช่เบอร์โทร และ บัตรประชาชน เป็นเลขอ้างอิง
        merchant_account_information += "0315" + account + "5303764"
    country = "5802" + country # ประเทศ
    if currency == "THB":
        currency = "5303" + "764" # "764"  คือเงินบาทไทย ตาม https://en.wikipedia.org/wiki/ISO_4217
    if money != "": # กรณีกำหนดเงิน
        check_money = money.split('.') # แยกจาก .
        if len(check_money) == 1 or len(check_money[1]) == 1: # กรณีที่ไม่มี . หรือ มีทศนิยมแค่หลักเดียว
            money = "54" + "0" + str(len(str(float(money))) + 1) + str(float(money)) + "0"
        else:
            money = "54" + "0" + str(len(str(float(money)))) + str(float(money)) # กรณีที่มีทศนิยมครบ
    check_sum = Version+one_time+merchant_account_information+country+currency+money+"6304" # เช็คค่า check sum
    check_sum1 = hex(crc16.crc16xmodem(check_sum.encode('ascii'),0xffff)).replace('0x','')
    if len(check_sum1) < 4: # # แก้ไขข้อมูล check_sum ไม่ครบ 4 หลัก
        check_sum1 = ("0"*(4-len(check_sum1))) + check_sum1
    check_sum += check_sum1
    if path_qr_code != "":
        img = qrcode.make(check_sum.upper())
        imgload = open(path_qr_code,'wb')
        img.save(imgload, 'PNG')
        imgload.close()
        return True
    else:
        return check_sum.upper() # upper ใช้คืนค่าสตริงเป็นตัวพิมพ์ใหญ่
```

Reference : <https://github.com/wannaphong/pypromptpay>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yo-sarawut.gitbook.io/snippet/mini-lab/python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
