2016-04-23 206 views
0

我正在嘗試構建一個簡單的藍牙客戶端/服務器,其中我的Raspberry Pi是服務器,而我的筆記本電腦是客戶端。嘗試連接到藍牙服務器時拒絕連接

這是(我的樹莓派運行)的服務器代碼:

#!/usr/bin/python 
# -*- coding: utf-8 

import wifi, bluetooth 

uuid="1e0ca4ea-299d-4335-93eb-27fcfe7fa848" 

print "Setting up Bluetooth socket" 

try: 
    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 
    sock.bind(("", 0)) 
    sock.listen(1) 
except IOError as e: 
    print str(e) 


print "Registering service" 
try: 
    bluetooth.advertise_service(sock, "MyService", uuid) 

    while True: 
    print "Waiting for connection..." 
    client_sock,address = sock.accept() 
    print "Accepted connection from {0}".format(address) 

    data = client_sock.recv(1024) 
    print "Received data: {0}".format(data) 

    print "Closing client socket." 
    client_sock.close() 
except IOError as e: 
    print str(e) 

這似乎是工作,腳本運行,並與Waiting for connection...塊。

然後,我的客戶端代碼:

#!/usr/bin/python 
# -*- coding: utf-8 

import bluetooth, time 

mac = "00:15:83:E5:E2:46" 
uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848" 

service = [] 
retry = 1 
while len(service) == 0: 
    print "Looking for service on {0}, try {1}".format(mac, retry) 
    service = bluetooth.find_service(address=mac, uuid=uuid) 
    retry = retry + 1 
    time.sleep(1) 

if len(service) == 1: 
    service = service[0] 
    print "Service found. Name={0}".format(service["name"]) 

    print "Connecting to service." 

    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) 
    try: 
    sock.connect((mac, service["port"])) 
    print "Connected to service on {0} on port {1}".format(mac, service["port"]) 
    except bluetooth.btcommon.BluetoothError as e: 
    print "Connection failed: {0}".format(e) 

elif len(service) == 0: 
    print "No service found on mac {0}.".format(mac) 
else: 
    print "{0} services found for mac/uuid, ignored.".format(len(service)) 

而且工作,直到我試圖connect()到樹莓派。我得到以下錯誤:

Connecting to service. 
Connection failed: (111, 'Connection refused') 

我試圖連接筆記本到樹莓派(找到它,並說,這是「已連接」),並尋找更多的信息網上,但沒能發現任何東西。

回答

2

當你想連接到不偵聽端口時發生此錯誤。

U的監聽端口「0」 ..... 它更改爲例如9999,然後客戶端必須連接到該端口上的服務器ADRESS

+0

[文檔](HTTPS:// pybluez .googlecode.com/svn/www/docs-0.7/public/bluetooth-module.html#get_available_port)說:'不推薦使用。而不是綁定到端口0。 '。另外,當請求服務時,它說它在端口1上運行。當選擇不同的端口時,我得到一個不同的錯誤。 –

+0

模糊文檔的另一個例子。明確採取了港口的做法。端口1沒有工作。 –