python3 串口控制USB轉GSM模塊打電話發短信


1. 安裝依賴

pip install pyserial

2. 串口連接

import serial
s = serial.Serial("/dev/ttyUSB0")

3. 打電話

s.write("ATD10086;\r\n".encode())

4. 發短信

# 設置短信模式為PDU
s.write(b'AT+CMGF=0\r\n')

# 設置短信編碼
s.write(b'AT+CSCS="UCS2"\r\n')

# 手機號碼 16進制unicode碼
s.write('AT+CMGS="00310030003000380036"\r\n'.encode())

# 短信內容 16進制unicode碼
s.write('00680065006c006c006f00204e16754c'.encode())

# 發送代碼
s.write(b'\x1A\r\n')

5. 讀取短信

import re

# 讀取所有短信
s.write(b'AT+CMGL="ALL"\r\n')

# 獲取全部返回
res = s.read()
while True:
    count = s.inWaiting()
    if count == 0:
        break
    res += s.read(count)

# 匹配短信文本
msg_list = re.findall('\+CMGL\: (\d+),"REC READ","(.*?)","","(.*?)"\\r\\n(.*?)\\r\\n', res.decode())
msg_list = [list(i) for i in msg_list]
for msg in msg_list:
    msg[1] = unicode2str(msg[1])
    msg[-1] = unicode2str(msg[-1])
print(msg_list)

6. 字符串轉16進制unicode碼

def str2unicode(text):
    code = ''
    for i in text:
        hex_i = hex(ord(i))
        if len(hex_i) == 4:
            code += hex_i.replace('0x', '00')
        else:
            code += hex_i.replace('0x', '')
    return code

7. 16進制unicode碼轉字符串

def unicode2str(code):
    text = ''
    tmp = ''
    for i in range(len(code)):
        tmp += code[i]
        if len(tmp) == 4:
            text += "\\u" + tmp
            tmp = ''
    text = eval(f'"{text}"')
    return text


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM