Python用人类可读的字符串(en)中的GsmModem读取ussd响应

时间:2015-10-26 21:21:03

标签: python sms gsm modem ussd

我正在使用gsmmodem软件包,并尝试从我发送的USSD代码获取响应。 USSD代码执行工作正常,但响应格式不正确(非人类可读)我希望以可读格式获取它。

请在此处查看代码

from __future__ import print_function
import logging
PORT = 'COM11'
BAUDRATE = 921600
USSD_STRING = '*111#'
PIN = None # SIM card PIN (if any)

from gsmmodem.modem import GsmModem

def main():
    print('Initializing modem...')
    modem = GsmModem(PORT, BAUDRATE)
    modem.connect(PIN)
    modem.waitForNetworkCoverage(10)
    print('Sending USSD string: {0}'.format(USSD_STRING))
    response = modem.sendUssd(USSD_STRING) # response type: gsmmodem.modem.Ussd
    print('USSD reply received: {0}'.format(response.message))
    if response.sessionActive:
        print('Closing USSD session.')
        # At this point, you could also reply to the USSD message by using response.reply()
        response.cancel()
    else:
        print('USSD session was ended by network.')
    modem.close()

if __name__ == '__main__':
    main()

代码http://pastebin.com/SvYptykS

的链接

1 个答案:

答案 0 :(得分:-1)

您将以gsm hexadecimal类型获得答案。因此,您必须将response.message字符串解码为适当的格式,然后以encode等人类可读格式将其utf-8解码。

所以,在

之后
response = modem.sendUssd(USSD_STRING)

写:

ussd_message = unicode(response.message.decode('hex'), 'utf-16-be').encode('utf8')
print('USSD reply received: {0}'.format(ussd_message))