I need to transfer a file from my Windows laptop to a Raspberry Pi, and also measure the speed and transfer time of the file. Looking on the internet I chose to use Pybluez, but I am sure there is something missing to realise the transfer to a Raspberry Pi and I don't understand what. I should probably figure out how to merge the pieces of code.This is the inquiry code:
import bluetooth
print("performing inquiry...")
nearby_devices = bluetooth.discover_devices(
duration=8, lookup_names=True, flush_cache=True, lookup_class=False)
print("found %d devices" % len(nearby_devices))
for addr, name in nearby_devices:
try:
print(" %s - %s" % (addr, name))
except UnicodeEncodeError:
print(" %s - %s" % (addr, name.encode('utf-8', 'replace')))
This is the code for the server (i.e. the device that has to send the file, in my case it's my laptop, right?):
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service( server_sock, "SampleServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
# protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" % data)
except IOError:
pass
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
This is the code for the client (which in my case would then be the Raspberry Pi):
from bluetooth import *
import sys
if sys.version < '3':
input = raw_input
addr = None
if len(sys.argv) < 2:
print("no device specified. Searching all nearby bluetooth devices for")
print("the SampleServer service")
else:
addr = sys.argv[1]
print("Searching for SampleServer on %s" % addr)
# search for the SampleServer service
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
service_matches = find_service( uuid = uuid, address = addr )
if len(service_matches) == 0:
print("couldn't find the SampleServer service =(")
sys.exit(0)
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print("connecting to \"%s\" on %s" % (name, host))
# Create the client socket
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
print("connected. type stuff")
while True:
data = input()
if len(data) == 0: break
sock.send(data)
sock.close()
What should i do? does the client-server code work directly by running the client programme on the Raspberry and the server on the computer? How can i then transfer the file? Is this a correct method or not?
Help me please!
Related
I am running Windows 11 and ideally I would like to 'talk' with my PS5 controller via the internal bluetooth of my laptop using python.
I was going to run this sample code for PyBluez, but I get the error message 'bad bluetooth address'.
from bluetooth import *
server_sock=BluetoothSocket()
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service( server_sock, "SampleServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
# protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" % data)
except IOError as e:
print(e)
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
Since PyBluez has a very suboptimal documentation I can't figure out a solution.
I have two computer(A and B) in the different VLAN.
the IP of the computer A server is x.x.180.70 and IP of the computer B is x.x.181.52.
the computer A bind 19999 port as the UDP server and B as the client.
A can recv the packet from B, but B can't recv the packet from A.
so i capture the packet with wireshark, the results shown that the server reply packet with another port. In common the server reply packet with the bound port. Why does the server use the different port?
Then I wrote a TCP Server on computer A, it works well.
The udp server works if A and B at the same vlan. Is there any body have idea? thanks!
Code(Python):
#!/usr/bin/python3
#coding=utf-8
import socket
import sys
def server(addr):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(addr)
print("server started, listen on %s" % str(addr))
while True:
print("wait msg....")
data, cconn = sock.recvfrom(1024)
client_addr = "%s:%d" % (cconn[0], cconn[1])
resp = "hello client"
print("recv msg from %s <- %s" % (client_addr, data.decode('utf-8')))
sock.sendto(resp.encode("utf-8"), cconn)
print("send msg to %s -> %s" % (client_addr, resp))
def client(addr):
server_addr = "%s:%d" % (addr[0], addr[1])
print("send msg to %s" % server_addr)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(addr)
sock.sendto("hello server".encode("utf-8"), addr)
data, conn = sock.recvfrom(1024)
resp = data.decode("utf-8")
print("recv msg from %s <- %s" % (server_addr, resp))
def usage():
print("Usage:")
print(" python3 udp.py server [ip:port]")
print(" python3 udp.py client [ip:port]")
if __name__ == "__main__":
if len(sys.argv) < 3:
usage()
exit(0)
role = sys.argv[1]
array = sys.argv[2].split(":")
address = (array[0], int(array[1]))
if role == "server":
server(address)
elif role == "client":
client(address)
else:
usage()
I have been writing a transparent proxy server in python to log where the request is going. Most pages load e.g. google.co.uk, however, pages such as google.com get stuck loading and some pages such as a local IP get the "Connection reset" error in the browser.
Any help would be greatly appreciated.
#!/usr/bin/env python
import socket, optparse, thread
def proxy(url, port, connection, address, data):
try:
get = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
get.connect((url, port))
get.send(data)
while True:
reply = get.recv(BUFFER)
if len(reply) > 0:
connection.send(reply)
info = float(len(reply))
info = float(info / 1024)
info = "%.3s" %(str(info))
info = "%s KB" %(info)
print("[*] Request Complete: %s => %s <=" %(str(address[0]), str(info)))
else:
break
get.close()
connection.close()
except Exception as e:
get.close()
connection.close()
def handle(connection, address, data):
first = data.split("\n")[0]
url = first.split(" ")[1]
protocolPosition = url.find("://")
if protocolPosition == -1:
# No protocol so default
temp = url
else:
temp = url[(protocolPosition + 3):]
if ":" in temp:
# Port other than 80 has been specified
port = temp.split(":")[-1].strip("/")
webserver = temp.split(":")[:-1]
try:
# Incase there is ':' in the URL
webserver = "".join(webserver)
except:
pass
else:
port = 80
webserver = temp.strip("/")
print("[*] '%s' => '%s'" %(address[0], webserver))
proxy(webserver, port, connection, address, data)
receive = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
receive.bind(("0.0.0.0", PORT))
except socket.error as e:
print("Failed to bind to 0.0.0.0:%d" %(PORT))
print("Error: " + str(e))
raise SystemExit
receive.listen(MAXCONNECTIONS)
print("Listening on 0.0.0.0:%d" %(PORT))
while True:
try:
connection, address = receive.accept()
data = connection.recv(BUFFER)
thread.start_new_thread(handle, (connection, address, data,))
except KeyboardInterrupt:
break
print("\nReleasing socket")
receive.close()
Edit: After some digging around and error handling I narrowed the error down to
[Errno -2] Name or service not known
After long hours of research and testing I finally ask here.
My script has to handle multiple client connections and in the same time has to get and send a stream from another socket.
Finally I've been able to make it work but only for one user. That user connects to the socket, the script connects to the other socket, then return the stream to the client.
The script works pretty well but has a some hard limitations :
- it send the stream to the client but,
- even if the socket is in non-blocking mode I think that calling a socket inside another one is the main reason why it reacts like it was in blocking mode (because one ot these is continuously sending datas ?)
By the way I think that the select() method could allow me to do what I want, but I don't clearly understand how.
Here is the server code taht works for one client, but is blocking
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
import sys, time, base64, socket
server_ip = 'XX.XX.XX.XX'
def caster_connect(connected_client, address):
username = 'XXXXXXX'
password = 'XXXXXXXXX'
host = 'XX.XX.XX.XX'
port = 2102
pwd = base64.b64encode("{}:{}".format(username, password).encode('ascii'))
pwd = pwd.decode('ascii')
u_message = ''
stream_type = 'CMRp'
header = \
"GET /" + str(stream_type) + " HTTP/1.1\r\n" +\
"Host " + str(host) + "\r\n" +\
"Ntrip-Version: Ntrip/1.0\r\n" +\
"User-Agent: my_script.py/0.1\r\n" +\
"Accept: */*\r\n" +\
"Authorization: Basic {}\r\n\r\n".format(pwd) +\
"Connection: close\r\n"
print("Connecting to caster...\n")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,int(port)))
s.send(header.encode('ascii'))
print("Waiting answer from caster...\n")
while True:
try:
data = s.recv(2048)
connected_client.send(data)
print("Sending data from caster at %s" % time.time())
sys.stdout.flush()
# On any error, close sockets
except socket.error, e:
print("No data received from caster : %s" % e)
print("Close client connection at %s" % format(address))
s.close()
break
return
#----------------
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((server_ip, 5680))
sock.settimeout(3)
try:
while True:
try:
sock.listen(5)
client, address = sock.accept()
print ("%s connected" % format(address) )
msg = client.recv(4096)
except socket.timeout, e:
err = e.args[0]
if err == 'timed out':
print("Timed out, retry later")
continue
else:
print(socket.error)
sock.close()
except socket.error:
print(socket.error)
sock.close()
else:
if len(msg) == 0:
print("Shutdown on client end")
sock.close()
else:
print(msg)
caster_response = caster_connect(client, address)
sys.stdout.flush()
print("Close")
client.close()
sock.close()`enter code here`
except KeyboardInterrupt:
print("W: Keyboard interrupt, closing socket")
finally:
sock.close()
And this is the code I found to handle select()
#!/usr/bin/env python
# coding: utf-8
import select, socket, sys, Queue
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server.bind(('XX.XX.XX.XX', 64000))
server.listen(5)
inputs = [server]
outputs = []
message_queues = {}
while inputs:
readable, writable, exceptional = select.select(
inputs, outputs, inputs)
for s in readable:
if s is server:
connection, client_address = s.accept()
print("New connection from %s" % client_address)
connection.setblocking(0)
inputs.append(connection)
message_queues[connection] = Queue.Queue()
else:
data = s.recv(1024)
print("Data received : %s" % data)
if data:
message_queues[s].put(data)
if s not in outputs:
outputs.append(s)
else:
if s in outputs:
outputs.remove(s)
inputs.remove(s)
s.close()
del message_queues[s]
for s in writable:
try:
next_msg = message_queues[s].get_nowait()
print("Next msg : %s" % next_msg)
except Queue.Empty:
outputs.remove(s)
else:
s.send(next_msg)
for s in exceptional:
inputs.remove(s)
if s in outputs:
outputs.remove(s)
s.close()
del message_queues[s]
In this code (found at this page) I didn't make changes as I don't know how to handle this.
Maybe by creating another server script that would only handle the stream part, so the main script would act as a server for clients, but as client for the stream part ?
I have encountered an error, i'm trying to render a character using coordinates of the character and then using the code reparentTo(render), however i get the following error: "TypeError: must be string or buffer, not None".
Traceback:
File "C:\On
line.py", line 1857, in <module>
run()
File "C:\Panda3D-1.8.1\direct\showbase\ShowBase.py", line 2921, in run
self.taskMgr.run()
File "C:\Panda3D-1.8.1\direct\task\Task.py", line 502, in run
self.step()
File "C:\Panda3D-1.8.1\direct\task\Task.py", line 460, in step
self.mgr.poll()
File "C:\On
line.py", line 1591, in updaterender
s.send(x)
TypeError: must be string or buffer, not None
Part of the Client code:
import direct.directbase.DirectStart
import pickle
from direct.gui.OnscreenText import OnscreenText
from direct.gui.DirectGui import *
from panda3d.core import *
from pandac.PandaModules import CardMaker
from pandac.PandaModules import NodePath
import socket
import sys
import select
print("Connecting...")
name = "fatie"
print 'Please enter the name you wish to use for your pirate?'
name = raw_input()
host = 'localhost'
port = 8303
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()
#When the connection is established the game loads.
#So if the code "Connected" comes up, the connection has been established.
print("Connected")
print("Loading Game")
#Game Loads Info connection to files then half way down the code
def updatecoords(task):
s.send(name)
print 'Name sent...'
def updatepos(task):
y = format(Cat.getPos())
s.send(y)
def updaterender(task):
x = Cat.reparentTo(render)
s.send(x)
return Task.cont
print 'Position sent'
def readServer(task):
try:
data = s.recv(4096)
print data
return Task.cont
except:
print 'no data received'
#Then further down
base.taskMgr.add(handleMovement, 'controlManager')
base.taskMgr.add(updatecoords, 'network coords')
base.taskMgr.add(updaterender, 'network coords')
base.taskMgr.add(updatepos, 'network coords')
base.taskMgr.add(readServer, 'read in')
Server Code:
import socket
import time
import pickle
import select
def broadcast(sock, message):
for socket in CONNECTION:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
CONNECTION.remove(socket)
HOST = ""
PORT = 8303
CONNECTION = []
RECV_BUFFER = 4096
maxclients = 5
print "Online Server started on port " + str(PORT)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('',PORT))
server_socket.listen(maxclients)
CONNECTION.append(server_socket)
while 1:
read_socks,wri_socks,err_socks = select.select(CONNECTION,[],[])
for sock in read_socks:
#New connection
if sock == server_socket:
socknew, addr = server_socket.accept()
CONNECTION.append(socknew)
print "Client (%s, %s) connected" % addr
broadcast(socknew, "[%s:%s] entered game\n" % addr)
else:
try:
data = socknew.recv(RECV_BUFFER)
if data:
print data
# broadcast_data(sock,data)
# print 'data was broadcast to'
# print CONNECTION_LIST.len()
except:
broadcast(sock, "Client (%s, %s) is offline" % addr)
sock.close()
CONNECTION.remove(sock)
continue
server_socket.close()