I am not able to connect to socket on Raspberry Pi 3 B+. This is what I did
Installed dnsmasq and hostapd and configured
created an access point and assigned static ip to wlano as 192.168.4.1 without bridging to lan
started a python script to listen on port 8888 (is successfully waiting for connections)
created an Android app to connect to the access point and send message over socket to 192.168.4.1 on port 8888
When I tried to connect to the socket using the wlan0 static ip,192.168.4.1 I am getting unknown host exception. and the python script prints the socket ip as 127.0.1.1 how can I run the Python script to listen on wlan0 IP instead of 127.0.1.1 this is my Python script which I got from internet
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
I haven't done any Python programming earlier. So I have to rely on the script and it is working fine.
Set
HOST = "192.168.4.1"
In the code and it should work.
Related
I would like to receive the messages from my phone to raspberry over bluetooth
I have written the following code ,
import bluetooth
hostMACAddress = '18:9E:FC:A1:81:93' # The MAC address of my iphone
port = 3
backlog = 1
size = 1024
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
try:
client, clientInfo = s.accept()
while 1:
data = client.recv(size)
if data:
print(data)
client.send(data) # Echo back to client
except:
print("Closing socket")
client.close()
s.close()
How can i receive the messages to my Raspberry when i run this code, i see no messages being received, my raspberry detects the MAC address of my iPhone but i would like to send some message and see if the bluetooth of raspberry can receive it
Kindly let me know what modifications i have to do in this code in order to achieve bluetooth connection
I haven't completed building an app using Flutter but I have the server/client code ready using python.
Server.py
import socket
import os
import multiprocessing
from multiprocessing import pool
os.system('sudo python3 relay.py C') #runs relay program and setups up GPIO pins
hostMACAddress = 'B8:27:EB:A3:B6:EB' # The MAC address of a Bluetooth adapter on the server.
backlog = 4
port=3
size = 1024
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.bind((hostMACAddress,port))
s.listen(backlog)
def new_client(client):
while 1:
data = client.recv(size)
if data:
n=data.decode("utf-8")
if n == 'ON':
os.system('sudo python3 relay.py ON')
if n == 'OFF':
os.system('sudo python3 relay.py OFF')
if n == 'CLOSE':
break
client.send(data)
if __name__ == '__main__':
client, address = s.accept()
pool = multiprocessing.Pool(4)
pool.map(new_client, (client, ))
pool.close()
pool.join
print("Closing socket")
client.close()
s.close()
This is my server program running on raspberry pi.
I implemented multithreading to allow 4 active connections(sockets) at all time, since bluetooth is a little different than web socket programming I had to get creative to keep the application running after any client closes connection.
Basically if I get the message ON/OFF, it in turn runs another python program that turn the relay on or off, if I get CLOSE message, I terminate the thread.
Client.py
import bluetooth
bd_addr = 'B8:27:EB:A3:B6:EB'
port = 3
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr,port))
print("Connected")
while True:
try:
data = input()
sock.send(data.encode())
if data == 'CLOSE':
break
except KeyboardInterrupt:
sock.close()
This is my client program running on my computer.
Notice the address in both codes in the same(MAC Address of my raspberry pi), because raspberry pi need the address of the bluetooth adapter to use(in case some machines have multiple interfaces) and client needs server bluetooth MAC Address in order to initiate socket connection. You also need to port that you configured in raspbery pi to receive connection in my case 3.
Let me know if you need any additional information.
Have fun making an app that implements socket programming!
I have a somewhat unusual problem. I want to run some code on my android smartphone via the ADB (which along with SL4A is already set up) and then I want it to act as a server and respond with the program's results while my host machine acts as a client and receives this data. However, I am not an expert in socket operations and I'm getting results I don't understand. My code is as follows:
from device import android
import socket
droid = android.Android()
# Open socket
s = socket.socket()
HOST = socket.gethostname()
PORT = 8000
s.bind((HOST, PORT))
s.listen(5)
print "HOST = ", HOST, ", PORT = ", PORT
# Accept instructions
c, addr = s.accept()
print "Got connection from", addr
data = ""
while True:
chunk = c.recv(1024)
if (not chunk):
break
else:
data.extend(chunk)
s.close()
# DO STUFF WITH RECEIVED INPUT
# Send result
c, addr = s.accept()
print "Got connection from", addr
while True:
if (c.send(str(result)):
break
s.close()
The code I'm running on the client, my host machine, is as follows:
s = socket.socket()
HOST = "localhost"
PORT = 8000
s.connect((HOST, PORT))
s.send(data)
s.close()
# IN A DIFFERENT FUNCTION
s = socket.socket()
HOST = "localhost"
PORT = 8000
try:
s.connect((HOST, PORT))
results = s.recv(1024)
s.close()
return results
except Exception:
return False
The environment has been set up this way:
set AP_PORT=54023
adb forward tcp:%AP_PORT% tcp:%AP_PORT%
So, how this is supposed to work is this: the server is set up to run on my Android smartphone and accept input to run the program on my Android smartphone from another program running on my PC. After the Android program has finished running, it should send the result back to my PC.
However, I'm having several problems. I can't seem to get the first connection open. I either get 10061's or 10049's and I'm not sure why that is. I've looked at the existing documentation available and I'm still not getting results. I'm also not sure if this code is actually running on the Android device and this is very important to my application so I really need some sort of confirmation on this.
Any enlightenment would be greatly appreciated.
The server program never ends until it reaches an exception, because you set up an inf loop: while True.
c.close() close the current connection, then the loop starts again and the program waits for another connection to accept.
The host program instead should end after the message is sent or when it reaches an exception.
What do you mean with: " I'm getting results I don't understand... This code runs without error... The problem I'm having is that I'm not getting any results back"?
What results do you get? Have you checked the data var?
I am trying to make a bluetooth connection with my Android client and a Python server. However, I am unable to do so since my Android client always fails to connect. Now I am wondering whether it is possible at all to use an Android Bluetooth socket and a python socket together. Is that possible?
And if so, do you have suggestions what else I might try? In a nutshell, this is what I do:
My Android client:
I get a Bluetooth device like this:
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice(deviceAddress);
Where deviceAddress is equal to the bluetooth MAC address of my laptops bluetooth adapter. Which is E0:F8:47:3F:80:49
Then I use that device to create a Socket:
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
Where MY_UUID is this string: 00001101-0000-1000-8000-00805F9B34FB
After that I just call connect:
socket.connect();
And that is where it fails to connect. Maybe it is because of server wihich looks like this:
My Python server:
import bluetooth
hostMACAddress = 'E0:F8:47:3F:80:49' # The MAC address of a Bluetooth adapter
port = 3
backlog = 1
size = 1024
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
try:
client, clientInfo = s.accept()
while 1:
data = client.recv(size)
if data:
print(data)
client.send(data) # Echo back to client
except:
print("Closing socket")
client.close()
s.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print "entered loop"
c, addr = s.accept() # Establish connection with client.
I was using this piece of code to simply create a socket and accept a connection on it from an Android. Simple enough.
But since the past few hours (with no changes to the code), python is for some reason unable to create the socket. I don't get any errors, but it's forever stuck at the s.accept() line.
I tried using Fing, a network diagnostics app on my Android to see the open ports, and indeed, Python is unable to create/open the socket. Earlier, as soon as I ran the code and rescanned on Fing, I was able to see the port open and test a TCP connection on it.
Sometimes, randomly in between, it works for one or two attempts.
What could be going wrong? I've tried to change port. I don't know what to debug since there isn't any error!
Same Error occur to me . it was due to not closing the Socket . Try Closing the Sockets.
Else it will work for once when ever you will run and then after that it will start causing problems.
I have these snippet in python with pybluez framework:
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 = [ RFCOMM_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"
and also I have this other snippet in Android to connect the pybluez rfcomm server socket:
private static final UUID MY_UUID = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");
....
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(myServerMacAddress);
....
BluetoothSocket tmp= device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
My problem is that Android device could not connect to the pybluez socket.
I think that the way I use to connect is wrong, and I don't know how to connect correctly or advertise my server socket
I offered a bounty, but found the solution myself. :) Posted on another answer but this may also apply to your problem. On certain versions of Debian (Raspbian etc) and maybe some others distros. The server_sock.accept() will by default just hang and never accept a connection - even from a paired device! I'm in some cases even convinced the socket isn't open at all. However, a solution to this is really simple.
Update your /etc/bluetooth/main.conf file, add a line or change the existing so it looks like this:
DisablePlugins = pnat
Then restart the Bluetooth service:
sudo invoke –rc.d bluetooth restart
It now MAY have been fixed.
Good luck!
Reference: RFCOMM without pairing using PyBluez on Debian?