Send AT-command through bluetooth from python application - python

hai guyz,
how can i send AT-command through bluetooth from a python application?
OS:fedora 8
Any one please healp me with the code?
which package i need to import?
from where can i download it?

To get a connection over bluetooth to your IP modem, you want to use the bluetooth
rfcomm driver:
michael#challenger:~> cat /etc/bluetooth/rfcomm.conf
rfcomm0 {
# Automatically bind the device at startup
bind yes;
# Bluetooth address of the device
device 00:1C:CC:XX:XX:XX;
# RFCOMM channel for the connection
channel 1;
# Description of the connection
comment "Blackberry";
}
This is the setup I use for mine - YMMV.
michael#challenger:~> cu -l /dev/rfcomm0
Connected.
ATI
Research in Motion BlackBerry IP Modem
OK
Once you have the rfcomm0 port, you treat the port as a standard serial port and you're good to go.

I think this is better.......
import bluetooth
sockfd = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sockfd.connect(('00:24:7E:9E:55:0D', 1)) # BT Address
sockfd.send('ATZ\r')
time.sleep(1)
sockfd.send(chr(26))
sockfd.close()

Related

Unable to view Serial Ports (ComPorts) on android

I installed Octo4A on my android phone.
It installed Alpine linux and python3.
When I run a python script to view the serial ports.
It says no ports are found, but it does find the ports on my windows computer using the same script:
import serial.tools.list_ports as ports
def getAvailablePorts():
availablePorts = list(ports.comports())
return availablePorts
availablePorts = getAvailablePorts()
for port in availablePorts:
print("Available port: " + port.device)
The output on windows:
Available port: COM3
Here are the serials listed in Octo4a:
How can I get a list of the available ports and connect to it on android using python3?
If you look at the code, the way pyserial looks for ports in Linux is by trying to find the following strings:
/dev/ttyS* # built-in serial ports
/dev/ttyUSB* # usb-serial with own driver
/dev/ttyXRUSB* # xr-usb-serial port exar (DELL Edge 3001)
/dev/ttyACM* # usb-serial with CDC-ACM profile
/dev/ttyAMA* # ARM internal port (raspi)
/dev/rfcomm* # BT serial devices
/dev/ttyAP* # Advantech multi-port serial controllers
/dev/ttyGS* # https://www.kernel.org/doc/Documentation/usb/gadget_serial.txt
In Octo4A, serial ports are apparently called /dev/ttyOcto4a so they will not be found by list_ports().
Of course, that does not mean pyserial won't work, you can try to instantiate and open your serial port directly with:
import serial
ser = serial.Serial(port='/dev/ttyOcto4a')
ser.isOpen()
I have not tried this myself, so I can not guarantee it will work.

Python sending package through wrong interface

I have a raspberry pi that is both connected to the internet via Wlan and a local device via Ethernet. So it has two IPs; one for each endpoint.
This is how it looks like simplified when running ifconfig; with different IPs for privacy
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 189.168.200.110 netmask 0.0.0.0 broadcast 255.255.255.255
wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 189.168.201.79 netmask 255.255.255.0 broadcast 192.168.1.255
This is the code that python is using to send a message to the device through the Ethernet with that gateway's ip
TCP_PORT = 3001
SERVER_IP_AD = "189.168.200.110"
CLIENT_IP_AD = "189.168.200.155"
BROADCAST_IP = "255.255.255.255"
def sendMessage(self, file_path, client_ip=CLIENT_IP_AD):
print('message en route')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((self.SERVER_IP_AD, 0))
s.connect((client_ip, self.TCP_PORT)) #**ERROR IS HERE**
MESSAGE = self.openFile(file_path)
s.send(MESSAGE.encode())
data = s.recv(self.BUFFER_SIZE)
s.close()
return data
Using wireshark I can see that the package is being sent through the Wlan interface instead of the Ethernet interface with the correct IP source and IP destination.
How do I tell python to use the correct interface when sending out the package?
In my opinion, you can establish Tcp connection with Ethernet, cause there isn't shaking hands by Ethernet
And, you shouldn't use s.bind() and s.connect() at the same time. Because the former is for UDP client, and the later is for TCP client. Have a try with only s.bind().

Connect to local bluetooth

I am using pybluez to develop a bluetooth application on linux in python. I want to know if it is possible to connect to a "localhost" for bluetooth so I can run the client and server on the same machine (as most people do for web development).
If this is not possible, how to most people develop bluetooth applications? Do they just run the client and server on different devices or is there a more clever way to handle this?
Eventually the server will run on a raspberry pi and the client will be any bluetooth enabled device (cell phone, laptop, etc.) but during development it would be great if I could run both on the same machine.
Here is my server:
import bluetooth as bt
socket = bt.BluetoothSocket(bt.RFCOMM)
host = ""
socket.bind((host, bt.PORT_ANY))
port = socket.getsockname()[1]
print("port: " + str(port))
socket.listen(1)
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
# bt.advertise_service(socket, "BTServer", uuid)
print("Listening on " + host + ":" + str(port))
client_sock, addr = socket.accept()
print("Connection accepted from " + addr)
data = client_sock.recv(1024)
print(data)
client_sock.close()
socket.close()
And when I call services = bt.find_service(name=None, uuid=None, address="localhost") on the client it cannot find any services.
Through further research I have found that it is not possible to run a bluetooth client and server on the same device with the same bluetooth adapter. For local testing you can either use two bluetooth enabled computers or get a bluetooth dongle.
It is not possible to run a Bluetooth client and server on the same device.
I used the pybluez python module.
When I run bluetooth.discover_devices(lookup_names=True) in the client code on my machine, it returns all other Bluetooth devices around it except my machine.
As we can not discover the machine, we can not connect to it over Bluetooth and can not use it as a Bluetooth Server.

Can't connect to local Machine IP through TCP From Arduino Uno using SIM900 Shield

So you have a basic understanding of the parts im using, I have:
Arduino Uno
Seeed Studio GPRS Shield v2.0 (http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0)
Ultimate GPS for Adafruit V3.3 (https://www.adafruit.com/products/746?gclid=Cj0KEQjw3-W5BRCymr_7r7SFt8cBEiQAsLtM8qn4SCfVWIvAwW-x9Mu-FLeB6hLmVd0PAPVU8IAXXPgaAtaC8P8HAQ)
Here is my problem:
I have tested the Arduino stacked with the GPRS shield, and it works fine with regards to accessing the internet through TCP, sending SMS, etc.. However, my application requires me to send GPS data from the adafruit GPS to a web server that I have already coded with Django and postgresql. The backend is set up.
I need to send the data from the Uno (client) to my laptop (server), which I coded in python (This is just to check whether it is creating a connection):
#!/usr/bin/env python
import socket
# import postgres database functions
TCP_IP = '192.168.1.112'
TCP_PORT = 10000
BUFFER_SIZE = 40
server_address = (TCP_IP,TCP_PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created.'
# Bind socket to TCP server and port
try:
s.bind(server_address)
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(1) # Puts socket into server mode
print 'Listening on port: ', TCP_PORT
# Now Keep Talking with the client
while (1):
# Wait to accept a connection
conn, addr = s.accept() # Wait for incoming connection with accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if not data: break
print "recieved data: data", data
conn.send(data) #echo
conn.close()
I dont think there is a problem with this. From this I will post data to my postgreSQL database. However, When I try to use AT commands on the SIM900 module to connect to the server using port 10000, I cannot connect:
AT+CIPSHUT
SHUT OK
AT+CGATT?
+CGATT: 1
OK
AT+CIPMUX=0
OK
AT+CSTT="fast.t-mobile.com","",""
OK
AT+CIICR
OK
AT+CIFSR
6.60.94.49
AT+CIPSTART="TCP","192.168.1.112,"10000"
OK
STATE: TCP CLOSED
CONNECT FAIL
I have tried connecting through TCP and replaced the AT+CIPSTART line with the below statement and it worked, so I know TCP works:
AT+CIPSTART="TCP","www.vishnusharma.com", "80"
Is the IP i'm using wrong? I'm new to this, but if it makes a difference, im using Ubuntu 16.04 partitioned on my Mac OSX. I have also checked the APN for T-mobile and it seems fine.
Any help would be greatly appreciated. Thank You!
The IP you're using is inside a NAT since it starts with 192.168. Unless you have a private apn with the mobile operator you're using, you won't be able to reach your Ubuntu from a public IP. Your ISP gives you a public IP address which ir administrated by your router, so if you want this to work, you'll have to do a port forwarding from your router to your Ubuntu.
To do the port forwarding you have to get in the router's configuration page (Typically 192.168.1.1 but depends on the model) an there you'll have to redirect the port XXX to 192.168.1.112:10000. After that you have to obtain your public IP (curl ifconfig.co) and use it to access from the SIM900.
First of all as a suggestion, you can combine the two shields by using SIM908 (unless you are getting more precision on your GPS shield). Since your TCP connection is working, I bet that the port 10000 on your ubuntu is blocked by the firewall. You can first try to turn off your firewall and see if it works. If it did not worked its something else. If it worked, turn on your firewall and then unblock the tcp port using the following command:
sudo ufw allow 10000/tcp

Pairing bluetooth devices with Passkey/Password in python - RFCOMM (Linux)

I am working on a Python script to search for bluetooth devices and connect them using RFCOMM. This devices has Passkey/Password. I am using PyBlueZ and, as far as I know, this library cannot handle Passkey/Password connections (Python PyBluez connecting to passkey protected device).
I am able to discover the devices and retrieve their names and addresses:
nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True,
flush_cache=True, lookup_class=False)
But if tried to connect to a specific device using:
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect((addr,port))
I get an error 'Device or resource busy (16)'.
I tried some bash commands using the hcitool and bluetooth-agent, but I need to do the connection programmatically. I was able to connect to my device using the steps described here: How to pair a bluetooth device from command line on Linux.
I want to ask if someone has connected to a bluetooth device with Passkey/Password using Python. I am thinking about to use the bash commands in Python using subprocess.call(), but I am not sure if it is a good idea.
Thanks for any help.
Finally I am able to connect to a device using PyBlueZ. I hope this answer will help others in the future. I tried the following:
First, import the modules and discover the devices.
import bluetooth, subprocess
nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True,
flush_cache=True, lookup_class=False)
When you discover the device you want to connect, you need to know port, the address and passkey. With that information do the next:
name = name # Device name
addr = addr # Device Address
port = 1 # RFCOMM port
passkey = "1111" # passkey of the device you want to connect
# kill any "bluetooth-agent" process that is already running
subprocess.call("kill -9 `pidof bluetooth-agent`",shell=True)
# Start a new "bluetooth-agent" process where XXXX is the passkey
status = subprocess.call("bluetooth-agent " + passkey + " &",shell=True)
# Now, connect in the same way as always with PyBlueZ
try:
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect((addr,port))
except bluetooth.btcommon.BluetoothError as err:
# Error handler
pass
Now, you are connected!! You can use your socket for the task you need:
s.recv(1024) # Buffer size
s.send("Hello World!")
Official PyBlueZ documentation is available here
Is there a way to connect two phones via Bluetooth , the script should be running on a Linux host. Any suggestions of using pybluez or any other APIs?
I have seen some examples where a Linux host is used as Client and is connect a phone (which is a server), but here I'm want to use Linux host as just a device to run the script and make two phones connect via Bluetooth.

Categories