Skip to content

Instantly share code, notes, and snippets.

@yoyicue
Last active August 29, 2015 14:03
Show Gist options
  • Save yoyicue/edbf009aab9243e39b65 to your computer and use it in GitHub Desktop.
Save yoyicue/edbf009aab9243e39b65 to your computer and use it in GitHub Desktop.
RG-BLE-12 模块的 AT 指令封装
#!/usr/bin/env python
#coding=utf-8
import serial
import time
class BLEPrinter(object):
SERIALPORT = '/dev/tty.usbserial-AM021OAT'
BAUDRATE = 9600
TIMEOUT = 3
def __init__(self, serialport=SERIALPORT):
"""
初始化, 打开势能
"""
self.serialport=serialport
self.bt = serial.Serial(port=serialport,
baudrate=self.BAUDRATE,
timeout=self.TIMEOUT)
self.bt.write('AT+EN1\r\n')
time.sleep(0.5)
print '%s' % self.bt.readline()
def get_name(self):
"""
获得名称
"""
self.bt.write('AT+NAME\r\n')
time.sleep(0.5)
print '%s' % self.bt.readline()
print '%s' % self.bt.readline()
print '%s' % self.bt.readline()
def set_name(self, name='美团外卖'):
"""
设置名称
"""
self.bt.write('AT+NAME %s\r\n' % name)
time.sleep(0.5)
print '%s' % self.bt.readline()
print '%s' % self.bt.readline()
def get_pin(self):
"""
获得 PIN
"""
self.bt.write('AT+PIN\r\n')
time.sleep(0.5)
print '%s' % self.bt.readline()
print '%s' % self.bt.readline()
print '%s' % self.bt.readline()
def set_pin(self, pin='1234'):
"""
设置 PIN
* 注意 String 不是 Int
"""
self.bt.write('AT+PIN %s\r\n' % pin)
time.sleep(0.5)
print '%s' % self.bt.readline()
print '%s' % self.bt.readline()
def get_baud(self):
"""
获得 波特率
"""
self.bt.write('AT+BAUD\r\n')
time.sleep(0.5)
print '%s' % self.bt.readline()
print '%s' % self.bt.readline()
print '%s' % self.bt.readline()
def set_baud(self, baud=9600):
"""
设置 波特率
"""
self.bt.write('AT+BAUD %s\r\n' % baud)
time.sleep(0.5)
print '%s' % self.bt.readline()
def get_addr(self):
"""
获得 Mac address
"""
self.bt.write('AT+ADDR\r\n')
time.sleep(0.5)
result = self.bt.readline().rstrip('\r\n')
print '%s' % result
print '%s' % self.bt.readline()
if result:
return result[-12:]
def close(self):
"""
关闭势能
"""
self.bt.write('AT+EN0\r\n')
self.bt.close()
if __name__ == '__main__':
import sys, os
if len(sys.argv) == 2:
serialport = sys.argv[1]
else:
serialport = BLEPrinter.SERIALPORT
if not os.path.exists(serialport):
sys.exit("ERROR: Serial port not found at: %s" % serialport)
print "Testing on port %s" % serialport
ble = BLEPrinter(serialport=serialport)
mac = ble.get_addr()
ble.set_name('美团外卖 %s' % mac[-6:])
ble.get_name()
ble.set_pin('0000')
ble.get_pin()
# ble.set_baud(9600)
# ble.get_baud()
ble.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment