我正在使用Mac尝试使用带python的蓝牙将字符串无线发送到树莓派。但是,我找不到与Mac兼容的API。我尝试了pybluez和lightblue之类的选项,但似乎它们不适用于mac。有解决方案吗?最好使用蓝牙通信,但我愿意接受其他建议。预先感谢
答案 0 :(得分:1)
更新后的答案
仍然使用netcat
方法,但这是从this answer改编的Python中实现的发送方,并且可以与下面的接收方一起使用:
#!/usr/local/bin/python3
import socket
def netcat(host, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, int(port)))
s.sendall(content.encode())
s.shutdown(socket.SHUT_WR)
while True:
data = s.recv(4096)
if not data:
break
print(repr(data))
s.close()
netcat('192.168.0.131', 40000, 'Hi')
这里是一个已实现的here匹配的侦听器/服务器,可与上面的发送者或从命令行使用简单的netcat发送者一起使用。
#!/usr/bin/env python
import socket
import select
class SocketServer:
""" Simple socket server that listens to one single client. """
def __init__(self, host = '0.0.0.0', port = 2010):
""" Initialize the server with a host and port to listen to. """
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host = host
self.port = port
self.sock.bind((host, port))
self.sock.listen(1)
def close(self):
""" Close the server socket. """
print('Closing server socket (host {}, port {})'.format(self.host, self.port))
if self.sock:
self.sock.close()
self.sock = None
def run_server(self):
""" Accept and handle an incoming connection. """
print('Starting socket server (host {}, port {})'.format(self.host, self.port))
client_sock, client_addr = self.sock.accept()
print('Client {} connected'.format(client_addr))
stop = False
while not stop:
if client_sock:
# Check if the client is still connected and if data is available:
try:
rdy_read, rdy_write, sock_err = select.select([client_sock,], [], [])
except select.error:
print('Select() failed on socket with {}'.format(client_addr))
return 1
if len(rdy_read) > 0:
read_data = client_sock.recv(255)
# Check if socket has been closed
if len(read_data) == 0:
print('{} closed the socket.'.format(client_addr))
stop = True
else:
print('>>> Received: {}'.format(read_data.rstrip()))
if read_data.rstrip() == 'quit':
stop = True
else:
client_sock.send(read_data)
else:
print("No client is connected, SocketServer can't receive data")
stop = True
# Close socket
print('Closing connection with {}'.format(client_addr))
client_sock.close()
return 0
def main():
server = SocketServer(port=40000)
server.run_server()
print('Exiting')
if __name__ == "__main__":
main()
原始答案
尝试使用netcat
或nc
。
在RaspberryPi上,使用TCP侦听端口40,000:
nc -l 40000
在Mac上,假设RaspberryPi的IP地址为192.168.0.131:
echo "hi" | /usr/bin/nc 192.168.0.131 40000
RaspberryPi显示:
hi