示例#1
0
	def __init__(self, com_port):
		self.serial_port = serial.Serial(port=com_port, baudrate=57600)
		self.ble_builder = BLEBuilder(self.serial_port)
		self.ble_parser = BLEParser(self.serial_port, callback=self.analyse_packet)
		self.devicecnt = 0
		#initialise the device
		self.ble_builder.send("fe00")
		#get an operating parameter value
		self.ble_builder.send("fe31", param_id="\x15")
		self.scan()
示例#2
0
文件: bluetooth.py 项目: mzxu/pyble
    def __init__(self, port='COM3'):

        self.port = port

        #init serial port
        self._init_serial_port()
        #init ble builder
        self.ble_builder = BLEBuilder(self.serial_port)
        #init ble parser
        self.ble_parser = BLEParser(self.serial_port,
                                    callback=self._display_packet)
        #gatt server configuration
        self.gatt_server = BLEGattHelper(self.ble_builder)

        #init device
        time.sleep(1)
示例#3
0
 def __init__(self, com_port):
     self.serial_port = serial.Serial(port=com_port, baudrate=57600)
     self.ble_builder = BLEBuilder(self.serial_port)
     self.ble_parser = BLEParser(self.serial_port,
                                 callback=self.analyse_packet)
     self.devicecnt = 0
     #initialise the device
     self.ble_builder.send("fe00")
     #get an operating parameter value
     #self.ble_builder.send("fe31", param_id="\x15")
     #set Mini Connection Interval to 7.5ms
     self.ble_builder.send('fe30', param_id='\x15', param_value='\x06\x00')
     self.ble_builder.send('fe30', param_id='\x16', param_value='\x0C\x00')
     self.ble_builder.send("fe31", param_id="\x15")
     self.ble_builder.send("fe31", param_id="\x16")
     self.getmini = False
     self.scan()
示例#4
0
 def __init__(self, port = 'COM3'):
     
     
     self.port = port
     
     #init serial port
     self._init_serial_port()
     #init ble builder
     self.ble_builder = BLEBuilder(self.serial_port)
     #init ble parser
     self.ble_parser = BLEParser(self.serial_port, callback=self._display_packet)       
     #gatt server configuration
     self.gatt_server = BLEGattHelper(self.ble_builder)
     
    
     
     #init device
     time.sleep(1)
示例#5
0
文件: bluetooth.py 项目: mzxu/pyble
class ble:
    def __init__(self, port='COM3'):

        self.port = port

        #init serial port
        self._init_serial_port()
        #init ble builder
        self.ble_builder = BLEBuilder(self.serial_port)
        #init ble parser
        self.ble_parser = BLEParser(self.serial_port,
                                    callback=self._display_packet)
        #gatt server configuration
        self.gatt_server = BLEGattHelper(self.ble_builder)

        #init device
        time.sleep(1)
#         #get an operating parameter value
#         print("COMMAND: Getting operating parameter value")
#         print(print_output(self.ble_builder.send("fe31", param_id="\x15")))

    def _init_serial_port(self):
        print "Port is set to %s" % self.port
        self.serial_port = serial.Serial()
        self.serial_port.port = self.port
        self.serial_port.baudrate = 115200
        if self.serial_port.isOpen():
            self.serial_port.close()
        self.serial_port.open()

    def DoInitDevice(self, role=Role.central):
        self.role = role
        print("COMMAND: Initializing device as %s role" % self.role)
        if self.role == Role.central:
            print(utils.printOutput(self.ble_builder.send("fe00")))
        elif self.role == Role.periphral:
            #init device as peripheral mode
            print(
                utils.printOutput(
                    self.ble_builder.send("fe00", profile_role="\x04")))

    def DoUpdateAdvertisingData(self, data, ad_type=adType.ADVERTISEMENT_DATA):
        print("COMMAND: Set advertising data as %s " % data)
        data_length = utils.getByteDataLengh(data)
        print(
            utils.printOutput(
                self.ble_builder.send("fe07",
                                      advert_data=data,
                                      data_length=data_length,
                                      ad_type=ad_type)))

    def DoMakeDiscoverable(self,
                           event_type=eventType.NON_CONN_UNDIRECT_AD,
                           init_addr_type=initiatorAddrType.PrivateResolve,
                           filter_policy=filterPolicy.All):
        print("COMMAND: GAP_MakeDeviceDiscoverable")
        print(
            utils.printOutput(
                self.ble_builder.send("fe06",
                                      event_type=event_type,
                                      init_addr_type=init_addr_type,
                                      filter_policy=filter_policy)))

    def DoEndDiscoverable(self):
        print("COMMAND: GAPT_EndDiscoverable")
        print(utils.printOutput(self.ble_builder.send("fe08")))

    def DoAddService(self,
                     service_type=declarations.GATTPrimaryService,
                     number=1):
        print("COMMAND: GATT_AddService")
        print(
            utils.printOutput(
                self.ble_builder.send("fdfc",
                                      uuid=service_type,
                                      numAttrs=number)))

    def DoDelService(self, handle):
        print("COMMAND: GATT_DelService")
        print(utils.printOutput((self.ble_builder.send("fdfd", handle))))

    def DoAddAttribute(self,
                       uuid,
                       permissions=attrPermission.GATT_PERMIT_READ_AND_WRITE):
        print("COMMAND: GATT_AddAttribute")
        print(
            utils.printOutput(
                self.ble_builder.send("fdfe",
                                      uuid=uuid,
                                      permissions=permissions)))

    def DoFindInfo(self,
                   conn_handle='\xfe\xff',
                   start_handle='\x01\x00',
                   end_handle='\xff\xff'):
        print("COMMAND: ATT_FindInfoReq")
        print(
            utils.printOutput(
                self.ble_builder.send("fd04",
                                      conn_handle=conn_handle,
                                      start_handle=start_handle,
                                      end_handle=end_handle)))

    def DoSendNotification(self, conn_handle, handle, value):
        print("COMMAND: ATT_HandleValueNotification")
        print(
            utils.printOutput(
                self.ble_builder.send("fd1b",
                                      conn_handle=conn_handle,
                                      handle=handle,
                                      value=value)))

    def stop(self):
        self.ble_parser.stop()

#     def DoHCIReset(self):
#         print("COMMAND: HCI reset")
#         print(utils.printOutput(self.ble_builder.send("0c03")))

    def DoDiscover(self):
        #start a device discovery scan
        print("COMMAND: Starting device scan")
        #        print(utils.printOutput(self.ble_builder.send("fe05")))
        #        time.sleep(0.1)
        print(utils.printOutput(self.ble_builder.send("fe04", mode="\x03")))

    def DoCancelDiscover(self):
        print("COMMAND: GAP_DeviceDiscoveryRequest")
        print(utils.printOutput(self.ble_builder.send("fe05")))

    def DoConnect(self, devAddr):
        print("COMMAND: Starting establishing connection to %s" % devAddr)
        print(utils.printOutput(self.ble_builder.send("fe05")))
        time.sleep(0.1)
        #         print(utils.printOutput(self.ble_builder.send("fe0a", mode="\xFE\xFF")))
        time.sleep(0.1)
        print("COMMAND: GAP_EstablishLinkRequest")
        print(
            utils.printOutput(
                self.ble_builder.send("fe09",
                                      peer_addr=devAddr,
                                      addr_type_peer="\x03")))

    def DoReset(self, resetType):
        print("COMMAND: UTIL_Reset")
        print(
            utils.printOutput(
                self.ble_builder.send("fe80", resetType=resetType)))
        time.sleep(1)

    def DoDisconnect(self, conn_handle):
        print("COMMAND: GAP_TerminateLinkRequest")
        print(
            utils.printOutput(
                self.ble_builder.send("fe0a", conn_handle=conn_handle[0])))
        time.sleep(1)

    def DoFindPrimaryServices(self):
        pass

    def DoFindPrimaryServiceByUUID(self, serviceUUID, conn_handle):
        print("COMMAND: GATT_DiscPrimaryServiceByUUID")
        print(
            utils.printOutput(
                self.ble_builder.send("fd86",
                                      value=serviceUUID,
                                      conn_handle=conn_handle[0])))
        pass

    def DoDiscCharsByUUID(self, charUUID, start_handle, end_handle,
                          conn_handle):
        print("COMMAND: GATT_DiscCharsByUUID")
        print(
            utils.printOutput(
                self.ble_builder.send("fd88",
                                      conn_handle=conn_handle[0],
                                      start_handle=start_handle[0],
                                      end_handle=end_handle[0],
                                      type=charUUID)))

    def DoEnableNotification(self, conf_handle, conn_handle):
        print("COMMAND: GATT_WriteCharValue")
        value = "\x01\x00"
        print(
            utils.printOutput(
                self.ble_builder.send("fd92",
                                      handle=conf_handle,
                                      value=value,
                                      conn_handle=conn_handle)))

    def DoReadUsingCharUUID(self, charUUID):
        print("COMMAND: Starting establishing connection")
        print(
            utils.printOutput(self.ble_builder.send("fdb4",
                                                    read_type=charUUID)))

    def register_callback(self, command=None):
        print "register callback"
        #        self._callback = command
        setattr(self, command.func_name, command)

    def _DoExchangeMTURsp(self, conn_handle, rxServerMTU):
        print("COMMAND: ATT_ExchangeMTURsp")
        print(
            utils.printOutput(
                self.ble_builder.send("fd03",
                                      conn_handle=conn_handle,
                                      server_rx_mtu=rxServerMTU)))

    def _DoCancelPendingConnectionRequest(self):
        print("COMMAND: Cancel pending connection request")
        print(
            utils.printOutput(
                self.ble_builder.send("fe0a", conn_handle="\xFE\xFF")))

    def _display_packet(self, (packet, dictionary)):
        print("EVENT: Response received from the device")
        print(utils.printOutput((packet, dictionary)))
        event = dictionary['event'][1]
        status = dictionary['status'][1]
        #         op_code = dictionary['op_code'][1]
        if event == hci_event.GAP_DeviceInformation:
            if hasattr(self, "DidDiscoverSuccess"):
                Data = dictionary['data_field']
                RSSI = int(dictionary['rssi'][1], 16)
                Addr = dictionary['addr']
                AddrType = dictionary['addr_type']
                EventType = dictionary['event_type']
                func = getattr(self, "DidDiscoverSuccess")
                func(Addr, RSSI, Data, AddrType, EventType)
        if event == hci_event.GAP_LinkEstablished:
            if hasattr(self, "DidConnectSuccess"):
                Addr = dictionary['dev_addr']
                ConnHandle = dictionary['conn_handle']
                func = getattr(self, "DidConnectSuccess")
                func(Addr, ConnHandle)

        #resp handler, mainly used in central mode
        if event == hci_event.ATT_ErrorRsp:
            print "Error found!"

        if event == hci_event.ATT_FindByTypeValueRsp:
            if status == "00" and hasattr(
                    self, "DidDiscPrimaryServiceByUUIDSuccess"):
                start_handle = dictionary['start_handle']
                end_handle = dictionary['end_handle']
                ConnHandle = dictionary['conn_handle']
                time.sleep(0.5)
                func = getattr(self, "DidDiscPrimaryServiceByUUIDSuccess")
                func(start_handle, end_handle, ConnHandle)

        if event == hci_event.ATT_ReadByTypeRsp:
            if dictionary.has_key('handle') and dictionary.has_key('value'):
                ConnHandle = dictionary['conn_handle']
                handle = dictionary['handle'][0]  #dictionary['results']
                data = dictionary['value'][0]
                if len(data) > 3 and utils.hexMinusInHex(handle,
                                                         -1) == data[1:3]:
                    #It's DiscUsingCharUUID event
                    charType = data[0]
                    charHandle = data[1:3]
                    confHandle = None
                    value = data[3::]
                    if charType.encode('hex')[0] == "1":  #type is notify
                        confHandle = utils.hexMinusInHex(handle, -2)
                    if hasattr(self, "DidDiscCharByUUIDSuccess"):
                        time.sleep(0.5)
                        func = getattr(self, "DidDiscCharByUUIDSuccess")
                        func(charType.encode('hex'), charHandle, confHandle,
                             value, ConnHandle[0])
                else:
                    #It's ReadUsingCharUUID event
                    if hasattr(self, "DidReadCharByUUIDSuccess"):
                        func = getattr(self, "DidReadCharByUUIDSuccess")
                        func(handle, data, ConnHandle)
            else:
                pass

        if event == hci_event.ATT_ReadByGrpTypeRsp:
            pass

        if event == hci_event.ATT_HandleValueNotification:
            conn_handle = dictionary['conn_handle']
            handle = dictionary['handle']
            value = utils.hexToAscii(dictionary['values'][0])
            if hasattr(self, "DidReciNotification"):
                func = getattr(self, "DidReciNotification")
                func(value, handle, conn_handle)
        if event == hci_event.ATT_HandleValueConfirmation:
            pass

        #Request handler mainly used in peripheral mode
        if event == hci_event.ATT_ReadByTypeReq:
            self.gatt_server.ATTReadByTypeRspHandler(dictionary)

        if event == hci_event.ATT_WriteReq:
            #if a write req recievied, it's probably to enable a notification or a indication
            #so pass the call back func to gatt helper in case a callback is needed.
            if hasattr(self, "DidRequestNotificationByCharUUID"):
                func = getattr(self, "DidRequestNotificationByCharUUID")
            else:
                func = None
            self.gatt_server.ATTWriteReqHandler(dictionary, func)

        if event == hci_event.ATT_ReadByGrpTypeReq:
            self.gatt_server.AttGrpTypeRspHandler(dictionary)

        if event == hci_event.ATT_ReadBlobReq:

            self.gatt_server.ATTReadBlobRspHandler(dictionary)

        if event == hci_event.ATT_ExchangeMTUReq:
            conn_handle = dictionary['conn_handle'][0]
            self._DoExchangeMTURsp(conn_handle, rxServerMTU)

        if event == hci_event.GAP_DeviceDiscoveryDone:
            pass

        if event == hci_event.GAP_LinkTerminated:
            pass

        if event == hci_event.GAP_HCI_ExtensionCommandStatus:
            op_code = dictionary['op_code'][1]
            status = dictionary['status'][1]
            if op_code == "GAP_EstablishLinkRequest":
                if status == "11":  #cancel pending establish link request
                    self._DoCancelPendingConnectionRequest()
示例#6
0
class CodeGen():

    TRANSMIT = 0
    RECIEVE = 1
    DATA = 0
    ACK = 1
    devicecnt = 0
    addr_dic = {}
    packet_list = []
    mcu_list = []
    id_dic = {1: '0000', 2: '0001', 3: '0002', 4: '0003'}
    ch_dic = {'0000': 1, '0001': 2, '0002': 3, '0003': 4}
    mutex = threading.Lock()
    state = 0
    max_len = 0

    def __init__(self, com_port):
        self.serial_port = serial.Serial(port=com_port, baudrate=57600)
        self.ble_builder = BLEBuilder(self.serial_port)
        self.ble_parser = BLEParser(self.serial_port,
                                    callback=self.analyse_packet)
        self.devicecnt = 0
        #initialise the device
        self.ble_builder.send("fe00")
        #get an operating parameter value
        self.ble_builder.send("fe31", param_id="\x15")
        self.scan()

    def analyse_packet(self, (packet, dictionary)):

        packet = packet.encode("hex")
        if packet[6:10] == "0d06" and packet[12:14] == "04":
            addr1, addr2, addr3, addr4, addr5, addr6 = struct.unpack(
                '2s2s2s2s2s2s', packet[16:28])
            address = addr1.upper() + ":" + addr2.upper() + ":" + addr3.upper(
            ) + ":" + addr4.upper() + ":" + addr5.upper() + ":" + addr6.upper(
            )
            self.devicecnt += 1
            self.addr_dic.update({self.devicecnt: address})
            print str(self.devicecnt) + ": " + address

        elif packet[6:10] == "1b05":
            """
			Type: 0x04 (Event)
			EventCode: 0xFF (HCI_LE_ExtEvent)
			Data Length: 0x0A bytes(s)
			Event: 0x051B (ATT_HandleValueNotification)
			Status: 0x00 (Success)
			ConnHandle: 0x0000
			EventLen: 0x04
			AttrHandle: 0x003A
			Value: 4A 04
			Dump(Rx):
			04 FF 0A 1B 05 00 00 00 04 3A 00 4A 04
			"""
            conn_handle = packet[12:16]
            value = packet[22:len(packet)].decode("hex")
            #revc_seq = int(value[0:2])
            #revc_result = value[3:len(value)]
            i = 0
            for item in self.packet_list:
                if item[2] == self.ch_dic[conn_handle]:
                    self.packet_list[i].append(value)
                    self.packet_list[i][0] = 1
                    break
                else:
                    i += 1
示例#7
0
class CG_Comm():

	TRANSMIT = 0
	RECIEVE = 1
	DATA = 0
	ACK = 1
	devicecnt = 0
	addr_dic = {}
	packet_list = []
	mcu_list = []
	id_dic = {1: '0000', 2: '0001', 3: '0002', 4: '0003'}
	ch_dic = {'0000': 1, '0001': 2, '0002': 3, '0003': 4}
	mutex = threading.Lock()
	state = 0
	max_len = 0
	connect_cnt = 0
	ble_header_handle = "\x49\x00"
	ble_code_handle =  "\x4C\x00" 
	ble_isflashcode_handle = "\x52\x00"
	ble_codesection_handle = "\x55\x00"
	
	isConnected = False;
	isWrote = False;
	
	def __init__(self, com_port):
		self.serial_port = serial.Serial(port=com_port, baudrate=57600)
		self.ble_builder = BLEBuilder(self.serial_port)
		self.ble_parser = BLEParser(self.serial_port, callback=self.analyse_packet)
		self.devicecnt = 0
		#initialise the device
		self.ble_builder.send("fe00")
		#get an operating parameter value
		self.ble_builder.send("fe31", param_id="\x15")
		self.scan()
		
	def analyse_packet(self, (packet, dictionary)):
		duplicate = 0
		packet = packet.encode("hex")
		if packet[6:10] == "0d06" and packet[12:14] == "04":
			addr1, addr2, addr3, addr4, addr5, addr6 = struct.unpack('2s2s2s2s2s2s',packet[16:28])
			address = addr1.upper()+":"+addr2.upper()+":"+addr3.upper()+":"+addr4.upper()+":"+addr5.upper()+":"+addr6.upper()
			for value in self.addr_dic.values():
				if value == address:
					duplicate = 1
					break
			if duplicate == 0 :
				self.devicecnt += 1
				self.addr_dic.update({self.devicecnt:address})
				if self.devicecnt < 10:
					print str(self.devicecnt) + ":  " + address
				else:
					print str(self.devicecnt) + ": " + address
		elif packet[6:10] == "1b05":
			"""
			Type: 0x04 (Event)
			EventCode: 0xFF (HCI_LE_ExtEvent)
			Data Length: 0x0A bytes(s)
			Event: 0x051B (ATT_HandleValueNotification)
			Status: 0x00 (Success)
			ConnHandle: 0x0000
			EventLen: 0x04
			AttrHandle: 0x003A
			Value: 4A 04
			Dump(Rx):
			04 FF 0A 1B 05 00 00 00 04 3A 00 4A 04
			"""
			conn_handle = packet[12:16]
			value = packet[22:len(packet)].decode("hex")
			#revc_seq = int(value[0:2])
			#revc_result = value[3:len(value)]
			i = 0
			for item in self.packet_list:
					if item[2] == self.ch_dic[conn_handle]:
						self.packet_list[i].append(value)
						self.packet_list[i][0] = 1	
						break
					else:
						i += 1
		elif packet[6:10] == "1305" and packet[10:12] == "00": # writeRsp
			self.set_write_attr_status()
			#print "writeRsp\n"
			"""
			-Type		: 0x04 (Event)
			-EventCode	: 0xFF (HCI_LE_ExtEvent)
			-Data Length	: 0x06 (6) bytes(s)
			 Event		: 0x0513 (ATT_WriteRsp)
			 Status		: 0x00 (Success)
			 ConnHandle	: 0x0000 (0)
			 PduLen		: 0x00 (0)
			Dump(Rx):
			04 FF 06 13 05 00 00 00 00 
			"""
		elif packet[6:10] == "0506" and packet[10:12] == "00": # GAP_EstablishLink
			self.set_connection_status()
			"""
示例#8
0
class CG_Comm():

    TRANSMIT = 0
    RECIEVE = 1
    DATA = 0
    ACK = 1
    devicecnt = 0
    addr_dic = {}
    packet_list = []
    mcu_list = []
    id_dic = {1: '0000', 2: '0001', 3: '0002', 4: '0003'}
    ch_dic = {'0000': 1, '0001': 2, '0002': 3, '0003': 4}
    mutex = threading.Lock()
    state = 0
    max_len = 0
    connect_cnt = 0
    ble_header_handle = "\x49\x00"
    ble_code_handle = "\x4C\x00"
    ble_isflashcode_handle = "\x52\x00"
    ble_codesection_handle = "\x55\x00"

    isConnected = False
    isWrote = False

    def __init__(self, com_port):
        self.serial_port = serial.Serial(port=com_port, baudrate=57600)
        self.ble_builder = BLEBuilder(self.serial_port)
        self.ble_parser = BLEParser(self.serial_port,
                                    callback=self.analyse_packet)
        self.devicecnt = 0
        #initialise the device
        self.ble_builder.send("fe00")
        #get an operating parameter value
        #self.ble_builder.send("fe31", param_id="\x15")
        #set Mini Connection Interval to 7.5ms
        self.ble_builder.send('fe30', param_id='\x15', param_value='\x06\x00')
        self.ble_builder.send('fe30', param_id='\x16', param_value='\x0C\x00')
        self.ble_builder.send("fe31", param_id="\x15")
        self.ble_builder.send("fe31", param_id="\x16")
        self.getmini = False
        self.scan()

    def analyse_packet(self, (packet, dictionary)):
        duplicate = 0
        packet = packet.encode("hex")

        if packet[6:10] == "0d06" and packet[12:14] == "04":
            addr1, addr2, addr3, addr4, addr5, addr6 = struct.unpack(
                '2s2s2s2s2s2s', packet[16:28])
            address = addr1.upper() + ":" + addr2.upper() + ":" + addr3.upper(
            ) + ":" + addr4.upper() + ":" + addr5.upper() + ":" + addr6.upper(
            )
            for value in self.addr_dic.values():
                if value == address:
                    duplicate = 1
                    break
            if duplicate == 0:
                self.devicecnt += 1
                self.addr_dic.update({self.devicecnt: address})
                if self.devicecnt < 10:
                    print str(self.devicecnt) + ":  " + address
                else:
                    print str(self.devicecnt) + ": " + address
        elif packet[6:10] == "1b05":
            """
			Type: 0x04 (Event)
			EventCode: 0xFF (HCI_LE_ExtEvent)
			Data Length: 0x0A bytes(s)
			Event: 0x051B (ATT_HandleValueNotification)
			Status: 0x00 (Success)
			ConnHandle: 0x0000
			EventLen: 0x04
			AttrHandle: 0x003A
			Value: 4A 04
			Dump(Rx):
			04 FF 0A 1B 05 00 00 00 04 3A 00 4A 04
			"""
            conn_handle = packet[12:16]
            value = packet[22:len(packet)].decode("hex")
            #revc_seq = int(value[0:2])
            #revc_result = value[3:len(value)]
            i = 0
            for item in self.packet_list:
                if item[2] == self.ch_dic[conn_handle]:
                    self.packet_list[i].append(value)
                    self.packet_list[i][0] = 1
                    break
                else:
                    i += 1
        elif packet[6:10] == "1305" and packet[10:12] == "00":  # writeRsp
            self.set_write_attr_status()
            #print "writeRsp\n"
            """
			-Type		: 0x04 (Event)
			-EventCode	: 0xFF (HCI_LE_ExtEvent)
			-Data Length	: 0x06 (6) bytes(s)
			 Event		: 0x0513 (ATT_WriteRsp)
			 Status		: 0x00 (Success)
			 ConnHandle	: 0x0000 (0)
			 PduLen		: 0x00 (0)
			Dump(Rx):
			04 FF 06 13 05 00 00 00 00 
			"""
        elif packet[6:10] == "0506" and packet[
                10:12] == "00":  # GAP_EstablishLink
            self.set_connection_status()
            """
			-Type		: 0x04 (Event)
			-EventCode	: 0xFF (HCI_LE_ExtEvent)
			-Data Length	: 0x13 (19) bytes(s)
			 Event		: 0x0605 (GAP_EstablishLink)
			 Status		: 0x00 (Success)
			 DevAddrType	: 0x00 (Public)
			 DevAddr		: AA:AA:AA:AA:AA:15
			 ConnHandle	: 0x0000 (0)
			 ConnInterval	: 0x0050 (80)
			 ConnLatency	: 0x0000 (0)
			 ConnTimeout	: 0x07D0 (2000)
			 ClockAccuracy	: 0x00 (0)
			Dump(Rx):
			04 FF 13 05 06 00 00 15 AA AA AA AA AA 00 00 50 
			00 00 00 D0 07 00 
			"""
        elif packet[6:10] == '7f06' and packet[10:12] == '00' and packet[
                12:16] == '31fe':
            """
			-Type		: 0x04 (Event)
			-EventCode	: 0xFF (HCI_LE_ExtEvent)
			-Data Length	: 0x08 (8) bytes(s)
			 Event		: 0x067F (GAP_HCI_ExtentionCommandStatus)
			 Status		: 0x00 (Success)
			 OpCode		: 0xFE31 (GAP_GetParam)
			 DataLength	: 0x02 (2)
			 ParamValue	: 0x0050 (80)
			Dump(Rx):
			04 FF 08 7F 06 00 31 FE 02 50 00 
			"""
            if self.getmini == True:
                print '> Max Connection Interval: ', int(
                    packet[20:22] + packet[18:20], 16) * 1.25, 'ms'

            if self.getmini == False:
                print '> Mini Connection Interval: ', int(
                    packet[20:22] + packet[18:20], 16) * 1.25, 'ms'
                self.getmini = True
示例#9
0
class ble:

    def __init__(self, port = 'COM3'):
        
        
        self.port = port
        
        #init serial port
        self._init_serial_port()
        #init ble builder
        self.ble_builder = BLEBuilder(self.serial_port)
        #init ble parser
        self.ble_parser = BLEParser(self.serial_port, callback=self._display_packet)       
        #gatt server configuration
        self.gatt_server = BLEGattHelper(self.ble_builder)
        
       
        
        #init device
        time.sleep(1)
#         #get an operating parameter value
#         print("COMMAND: Getting operating parameter value")
#         print(print_output(self.ble_builder.send("fe31", param_id="\x15"))) 
    def _init_serial_port(self):
        print "Port is set to %s" % self.port
        self.serial_port = serial.Serial()
        self.serial_port.port = self.port
        self.serial_port.baudrate = 115200
        if self.serial_port.isOpen():
            self.serial_port.close()
        self.serial_port.open()
        
    def DoInitDevice(self, role = Role.central):
        self.role = role
        print("COMMAND: Initializing device as %s role" % self.role)
        if self.role == Role.central:
            print(utils.printOutput(self.ble_builder.send("fe00")))
        elif self.role == Role.periphral:
            #init device as peripheral mode
            print(utils.printOutput(self.ble_builder.send("fe00", profile_role = "\x04")))  
    
    def DoUpdateAdvertisingData(self, data, ad_type = adType.ADVERTISEMENT_DATA):
        print("COMMAND: Set advertising data as %s " % data)
        data_length = utils.getByteDataLengh(data)
        print(utils.printOutput(self.ble_builder.send("fe07", advert_data = data, data_length = data_length, ad_type= ad_type)))        

    def DoMakeDiscoverable(self, event_type = eventType.NON_CONN_UNDIRECT_AD, init_addr_type = initiatorAddrType.PrivateResolve, filter_policy = filterPolicy.All):
        print("COMMAND: GAP_MakeDeviceDiscoverable")
        print(utils.printOutput(self.ble_builder.send("fe06", event_type = event_type, init_addr_type = init_addr_type, filter_policy = filter_policy)))
        
    def DoEndDiscoverable(self):
        print("COMMAND: GAPT_EndDiscoverable")
        print(utils.printOutput(self.ble_builder.send("fe08")))
        
    def DoAddService(self, service_type = declarations.GATTPrimaryService, number = 1):
        print("COMMAND: GATT_AddService")
        print(utils.printOutput(self.ble_builder.send("fdfc", uuid = service_type, numAttrs = number)))
    
    def DoDelService(self, handle):
        print("COMMAND: GATT_DelService")
        print(utils.printOutput((self.ble_builder.send("fdfd", handle))))

    def DoAddAttribute(self, uuid, permissions = attrPermission.GATT_PERMIT_READ_AND_WRITE):
        print("COMMAND: GATT_AddAttribute")
        print(utils.printOutput(self.ble_builder.send("fdfe", uuid = uuid, permissions = permissions)))
    
    def DoFindInfo(self, conn_handle = '\xfe\xff', start_handle = '\x01\x00', end_handle = '\xff\xff'):
        print("COMMAND: ATT_FindInfoReq")
        print(utils.printOutput(self.ble_builder.send("fd04", conn_handle = conn_handle, start_handle = start_handle, end_handle = end_handle)))
        
    def DoSendNotification(self, conn_handle, handle, value):
        print("COMMAND: ATT_HandleValueNotification")
        print(utils.printOutput(self.ble_builder.send("fd1b", conn_handle = conn_handle, handle = handle, value = value)))
        
    def stop(self):
        self.ble_parser.stop()       
    
#     def DoHCIReset(self):
#         print("COMMAND: HCI reset")
#         print(utils.printOutput(self.ble_builder.send("0c03")))
        
        
    def DoDiscover(self):
        #start a device discovery scan
        print("COMMAND: Starting device scan")
#        print(utils.printOutput(self.ble_builder.send("fe05")))
#        time.sleep(0.1)
        print(utils.printOutput(self.ble_builder.send("fe04", mode="\x03")))
        
    def DoCancelDiscover(self):
        print("COMMAND: GAP_DeviceDiscoveryRequest")        
        print(utils.printOutput(self.ble_builder.send("fe05")))        

    def DoConnect(self, devAddr):
        print("COMMAND: Starting establishing connection to %s" % devAddr)
        print(utils.printOutput(self.ble_builder.send("fe05")))
        time.sleep(0.1)
#         print(utils.printOutput(self.ble_builder.send("fe0a", mode="\xFE\xFF")))
        time.sleep(0.1)
        print("COMMAND: GAP_EstablishLinkRequest")
        print(utils.printOutput(self.ble_builder.send("fe09", peer_addr=devAddr, addr_type_peer="\x03")))
    
    def DoReset(self, resetType):
        print("COMMAND: UTIL_Reset")
        print(utils.printOutput(self.ble_builder.send("fe80", resetType = resetType)))
        time.sleep(1)
    
    def DoDisconnect(self, conn_handle):
        print("COMMAND: GAP_TerminateLinkRequest")
        print(utils.printOutput(self.ble_builder.send("fe0a", conn_handle = conn_handle[0])))
        time.sleep(1)
        
    def DoFindPrimaryServices(self):
        pass
    
    def DoFindPrimaryServiceByUUID(self, serviceUUID, conn_handle):
        print("COMMAND: GATT_DiscPrimaryServiceByUUID")
        print(utils.printOutput(self.ble_builder.send("fd86", value = serviceUUID, conn_handle = conn_handle[0])))        
        pass
    
    def DoDiscCharsByUUID(self, charUUID, start_handle, end_handle, conn_handle):
        print("COMMAND: GATT_DiscCharsByUUID")
        print(utils.printOutput(self.ble_builder.send("fd88", conn_handle = conn_handle[0], start_handle = start_handle[0], end_handle = end_handle[0], type=charUUID)))
    

    def DoEnableNotification(self, conf_handle, conn_handle):
        print("COMMAND: GATT_WriteCharValue")
        value = "\x01\x00"
        print(utils.printOutput(self.ble_builder.send("fd92", handle = conf_handle, value = value, conn_handle = conn_handle)))
    
    def DoReadUsingCharUUID(self, charUUID):
        print("COMMAND: Starting establishing connection")
        print(utils.printOutput(self.ble_builder.send("fdb4", read_type=charUUID)))
                

                
    def register_callback(self, command = None):
        print "register callback"
#        self._callback = command
        setattr(self, command.func_name, command)    
        
    def _DoExchangeMTURsp(self,conn_handle, rxServerMTU):
        print("COMMAND: ATT_ExchangeMTURsp")
        print(utils.printOutput(self.ble_builder.send("fd03",conn_handle = conn_handle, server_rx_mtu = rxServerMTU)))    
    
    def _DoCancelPendingConnectionRequest(self):
        print("COMMAND: Cancel pending connection request")
        print(utils.printOutput(self.ble_builder.send("fe0a", conn_handle="\xFE\xFF")))
    
    def _display_packet(self, (packet, dictionary)):
        print("EVENT: Response received from the device")
        print(utils.printOutput((packet, dictionary)))   
        event = dictionary['event'][1]
        status = dictionary['status'][1]
#         op_code = dictionary['op_code'][1]
        if event == hci_event.GAP_DeviceInformation:
            if hasattr(self, "DidDiscoverSuccess"):
                Data = dictionary['data_field']
                RSSI = int(dictionary['rssi'][1], 16)
                Addr = dictionary['addr']
                AddrType = dictionary['addr_type']
                EventType = dictionary['event_type']
                func = getattr(self, "DidDiscoverSuccess") 
                func(Addr, RSSI, Data, AddrType, EventType)
        if event == hci_event.GAP_LinkEstablished:
            if hasattr(self, "DidConnectSuccess"):
                Addr = dictionary['dev_addr']
                ConnHandle = dictionary['conn_handle']
                func = getattr(self, "DidConnectSuccess")
                func(Addr, ConnHandle)
                
        #resp handler, mainly used in central mode        
        if event == hci_event.ATT_ErrorRsp:
            print "Error found!"

        if event == hci_event.ATT_FindByTypeValueRsp:
            if status == "00" and hasattr(self, "DidDiscPrimaryServiceByUUIDSuccess"):
                start_handle = dictionary['start_handle']
                end_handle = dictionary['end_handle']
                ConnHandle = dictionary['conn_handle']
                time.sleep(0.5)
                func = getattr(self, "DidDiscPrimaryServiceByUUIDSuccess")
                func(start_handle, end_handle, ConnHandle)
            
        if event == hci_event.ATT_ReadByTypeRsp:
            if dictionary.has_key('handle') and dictionary.has_key('value'):
                ConnHandle = dictionary['conn_handle']
                handle = dictionary['handle'][0]#dictionary['results']
                data = dictionary['value'][0]
                if len(data) > 3 and utils.hexMinusInHex(handle, -1) == data[1:3]:
                    #It's DiscUsingCharUUID event
                    charType = data[0]
                    charHandle = data[1:3]
                    confHandle = None
                    value = data[3::]
                    if charType.encode('hex')[0] == "1": #type is notify
                        confHandle = utils.hexMinusInHex(handle, -2)        
                    if hasattr(self, "DidDiscCharByUUIDSuccess"):     
                        time.sleep(0.5)       
                        func = getattr(self, "DidDiscCharByUUIDSuccess")
                        func(charType.encode('hex'), charHandle, confHandle, value, ConnHandle[0])     
                else:
                    #It's ReadUsingCharUUID event             
                    if hasattr(self, "DidReadCharByUUIDSuccess"):            
                        func = getattr(self, "DidReadCharByUUIDSuccess")
                        func(handle, data, ConnHandle)                    
            else:
                pass

        if event == hci_event.ATT_ReadByGrpTypeRsp:
            pass
        
        if event == hci_event.ATT_HandleValueNotification:
            conn_handle = dictionary['conn_handle']
            handle = dictionary['handle']
            value = utils.hexToAscii(dictionary['values'][0])
            if hasattr(self, "DidReciNotification"):
                func = getattr(self, "DidReciNotification")
                func(value, handle, conn_handle)
        if event == hci_event.ATT_HandleValueConfirmation:
            pass
        
        #Request handler mainly used in peripheral mode
        if event == hci_event.ATT_ReadByTypeReq:         
            self.gatt_server.ATTReadByTypeRspHandler(dictionary) 
            
        if event == hci_event.ATT_WriteReq:
            #if a write req recievied, it's probably to enable a notification or a indication
            #so pass the call back func to gatt helper in case a callback is needed.
            if hasattr(self, "DidRequestNotificationByCharUUID"):
                func = getattr(self, "DidRequestNotificationByCharUUID")
            else:
                func = None
            self.gatt_server.ATTWriteReqHandler(dictionary, func)
            
        if event == hci_event.ATT_ReadByGrpTypeReq:    
            self.gatt_server.AttGrpTypeRspHandler(dictionary)     
                   

        
        if event == hci_event.ATT_ReadBlobReq:

            self.gatt_server.ATTReadBlobRspHandler(dictionary)
            
        if event == hci_event.ATT_ExchangeMTUReq:
            conn_handle = dictionary['conn_handle'][0]
            self._DoExchangeMTURsp(conn_handle, rxServerMTU)  
            
                
        if event == hci_event.GAP_DeviceDiscoveryDone:            
            pass
        

        if event == hci_event.GAP_LinkTerminated:
            pass
        

        
        if event == hci_event.GAP_HCI_ExtensionCommandStatus:
            op_code = dictionary['op_code'][1]
            status = dictionary['status'][1]
            if op_code == "GAP_EstablishLinkRequest":
                if status == "11":   #cancel pending establish link request
                    self._DoCancelPendingConnectionRequest()