How to find bluetooth devices not set to visible in python? - python

Im trying to make a algorithm in python to detect if my phone is in the area. Im using this to find my device:
bluetooth.discover_devices()
But it only detects my phone if I set my Bluetooth on my phone to "visible".
Is there a function or command to detect my phone when it's set to hidden?
Im fairly new to python so any form of help is very welcome!
Thanks in advance!

You could attempt to connect to your phone. If it's nearby, the connection will succeed. Devices can be connectable when they are not discoverable. You would have to already know the device address of your phone (via discovery when your phone was visible) in order to initiate the connection.

Not sure if a solution is still needed (I think this is right, just haven't been succesful with it). A book entitled "Violent Python" gives a solution for this in chapter 5, but I haven't been successful in implementing it. Supposedly you just need to increment the MAC address of the devices wifi adapter by one to calculate the Bluetooth MAC.
def retBtAddr(addr):
btAddr=str(hex(int(addr.replace(':', ''), 16) + 1))[2:]
btAddr=btAddr[0:2]+":"+btAddr[2:4]+":"+btAddr[4:6]+":"+\
btAddr[6:8]+":"+btAddr[8:10]+":"+btAddr[10:12]
return btAddr
and then something like the following (where OUI is the first 24 bytes of BT MAC)
def checkBluetooth(btAddr):
btName = lookup_name(btAddr)
if btName:
print '[+] Detected Bluetooth Device: ' + btName
else:
print '[-] Failed to Detect Bluetooth Device.'
def wifiPrint(pkt):
iPhone_OUI = 'd0:23:db'
if pkt.haslayer(Dot11):
wifiMAC = pkt.getlayer(Dot11).addr2
if wifiMAC != None and iPhone_OUI == wifiMAC[:8]:
print '[*] Detected iPhone MAC: ' + wifiMAC
btAddr = retBtAddr(wifiMAC)
print '[+] Testing Bluetooth MAC: ' + btAddr
checkBluetooth(btAddr)

Related

Python nmap not showing same results as terminal

Unsure how to phrase this, as I am new to Python.
Basically, I have this method in Python (below) that is scanning for devices available on my network. The Python code returns only 6 devices, and not the one I am searching for (Roku)
def scanner(self):
"""
Method that scans the network for available IP addresses.
"""
if len(self.ip) == 0:
network = '192.168.1.0/24'
else:
network = self.ip + '/24'
print("Scanning please wait...")
nm = nmap.PortScanner()
nm.scan(hosts=network, arguments='-sn')
host_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
for item in nm.all_hosts():
print(item)
for host, status in host_list:
self.ip_addresses.append(host)
self.choose_address()
When I use sudo nmap -sn 192.168.1.0/24 in my terminal, I get back 9 devices, including the Roku. Does anyone have any insight into why this doesn't want to work for me?

Im trying to scan my wifi network to find out when my phone connects, where am i going wrong?

I am running python 3.7 on macOS
I am trying to have my code scan my wifi network to see when my phone joins the specified wifi network, i provide the routers ip address ("ip") and the phones assigned ip address when it connects to that specified wifi ("device")
When i run my code i get no errors but i also get no output
I have tried using "subprocess.Popen(["say, 'Iphone just connected to the network'"]) to speak but that did not work so i tried echo and say, which also did not work.
At this point i'm not sure what part of my code is the part that is not working, this is my first try at automation so any help would be greatly appreciated.
Thank you
import sys
import subprocess
import os
from decouple import config
ip = "192.168.*.***"
device = "192.168.*.***"
proc = subprocess.Popen(["ping", ip],stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if not line:
break
connected_ip = line.decode('utf-8').split()[3]
if connected_ip == device:
os.system("echo 'Iphone just connected to the network'")
os.system("say 'Iphone just connected to the network'")
'''subprocess.Popen(["say, 'Iphone just connected to the network'"])'''

Display FULL return in python after sending a command to external device

Environment: Python v2.x in Windows OS.
Question: I am using COM4 to communicate with a robot. I notice that I cannot get complete return in my Python code when I send "getver(ion)" cmd to robot.
To be specific, my current code is:
########## open COM4
ser = serial.Serial(3)
########## send cmd 'getver'
ser.write ("testmode on \n")
ser.write ("getver \n")
print ser.read()
########### return
Component,Major,Minor,Build,Aux
APPassword,956FC721
BaseID,1.2,1.0,18000,2000,
BatteryType,4,LIION_4CELL_SMART,
Beehive URL, beehive.cloud.com
BlowerType,1,BLOWER_ORIG,
Bootloader Version,27828,,
BrushMotorType,1,BRUSH_MOTOR_ORIG,
BrushSpeed,1400,,
BrushSpeedEco,800,,
ChassisRev,1,,
Cloud Selector, 2
However, the right return is this:
Component,Major,Minor,Build,Aux
APPassword,956FC721
BaseID,1.2,1.0,18000,2000,
BatteryType,4,LIION_4CELL_SMART,
Beehive URL, beehive.cloud.com
BlowerType,1,BLOWER_ORIG,
Bootloader Version,27828,,
BrushMotorType,1,BRUSH_MOTOR_ORIG,
BrushSpeed,1400,,
BrushSpeedEco,800,,
ChassisRev,1,,
Cloud Selector, 2
DropSensorType,1,DROP_SENSOR_ORIG,
LCD Panel,137,240,124,
LDS CPU,F2802x/c001,,
LDS Serial,KSH13315AA-0000153,,
LDS Software,V2.6.15295,0000000001,
LDSMotorType,2,LDS_MOTOR_MABUCHI,
Locale,1,LOCALE_USA,
MagSensorType,1,MAG_SENSOR_ORIG,
MainBoard Serial Number,OPS13115,544a1696de32,
MainBoard Version,1,,
Model,BotVacConnected,905-0143,
QAState,QA_STATE_APPROVED
Serial Number,KSH13715,544a1696de32,P
SideBrushPower,1500,,
SideBrushType,2,SIDE_BRUSH_VORWERK_REV1,
SmartBatt Data Version,2048
SmartBatt Device Chemistry,LION
SmartBatt Device Name,F164A1028
SmartBatt Manufacturer Name,Panasonic
SmartBatt Mfg Year/Month/Day,2095,10,6
SmartBatt Serial Number,14592
SmartBatt Software Version,1280
Software,2,0,0,46,28146
UI Board Hardware,0,0,
UI Board Software,1,3,
UI Name,Davinci
UI Version,1.0.0
VacuumPwr,80,,
VacuumPwrEco,65,,
WallSensorType,1,WALL_SENSOR_ORIG,
WheelPodType,1,WHEEL_POD_ORIG,
As you can see, the return from python is not complete, um...then how to display the full info? Thanks in advance.
I know some electronics and robotics, but I cannot predict what exact could happen, so I have some ideas to check only ;)
1) I wonder to know what did you get when call recieve again. I think it could help.
2) set exact bytes to recieve in read() method.
it is described here,
TL;DR below:
While True:
bytesToRead = ser.inWaiting()
ser.read(bytesToRead)
3) Try to initialize Serial object with timeout = None - maybe it just waits, or default is too small ;)
I will edit that when you check that sth not working, and if I will have new idea.
Regards and sorry for my English.

Get USB device address through python

For test purposes, I want to connect a USB device and want to check what is the speed (HS/FS/LS).
I am able to access to Device Descriptor, Endpoint descriptor, interface descriptor but I would like to know the device address which has been allocated by the OS (windows 7)
My code so far :
import usb
busses = usb.busses()
for bus in busses:
for dev in bus.devices:
if dev.idVendor == vendor_id and dev.idProduct == product_id:
print ("Test vehicle %s device FOUND!" %protocol)
print ("iManufacturer : %s" %usb.util.get_string(dev.dev, 256, 1))
print ("iProduct : %s" %usb.util.get_string(dev.dev, 256, 2))
print ("iSerialNumber : %s" %usb.util.get_string(dev.dev, 256, 3))
return dev
print ("Test vehicle %s device NOT FOUND!" %protocol)
Returns :
C:\Python27\Lib\site-packages>python example.py
Test vehicle HS device FOUND!
iManufacturer : Kingston
iProduct : DataTraveler 2.0
iSerialNumber : 5B720A82364A
In the very useful USBview software, there is a section :
ConnectionStatus: DeviceConnected
Current Config Value: 0x01
Device Bus Speed: High
Device Address: 0x09
Open Pipes: 2
How do I get these informations ? is it a query to the USB device using pyUSB ? or is it a query to sys ?
Thanks for any help.
There are several more fields available in the device objects (in your code these are named dev).
A quick and dirty way to look at them
def print_internals(dev):
for attrib in dir(dev):
if not attrib.startswith('_') and not attrib == 'configurations':
x=getattr(dev, attrib)
print " ", attrib, x
for config in dev.configurations:
for attrib in dir(config):
if not attrib.startswith('_'):
x=getattr(config, attrib)
print " ", attrib, x
And call it within your "for dev in bus.devices" loop. It looks like the filename might correspond to 'device address', though bus speed is a bit deeper in (dev.configurations[i].interfaces[j][k].interfaceProtocol), and this only has an integer. usb.util might be able to provide you more information based on those integers, but I don't have that module available to me.
Documentation for pyUSB doesn't seem to be very extensive, but this SO question points at the libusb docs which it wraps up.
You can get usb device speed information by pyUSB with this patch https://github.com/DeliangFan/pyusb/commit/a882829859cd6ef3c91ca11870937dfff93fea9d.
Because libusb1.0 has already support to get usb speed information.
These attributes are (nowadays) easily accessible. At least it works for me. https://github.com/pyusb/pyusb/blob/master/usb/core.py
import usb.core
devices = usb.core.find(find_all=True)
dev = next(devices)
print("device bus:", dev.bus)
print("device address:", dev.address)
print("device port:", dev.port_number)
print("device speed:", dev.speed)

pyBluez python server - phone don't see my server

first i'm sorry if my english is not very good because i'm french.
I'm a beginner on bluetooth development with pyBluez (i already know TCP and UDP sockets) and i have a little problem with the server.
when i run the following code, my computer seems to be in a listening state but when my phone(nokia xpress music 5800) try to detect it, it doesn't see anything!
and there is two surprising things for me:
1)there is no fonction in my code configuring a name like "my computer". maybe my phone find my address but,because it can't resolve the name by lookup_name()-like function, it considers my computers isn't on?
2)when i replace serversock.bind(("",PORT_ANY)) by serversock.bind(("00:12:34:56:78:9A",PORT_ANY)) where 00:12:34:56:78:9A is the address given by hciconfig tool for my bluetooth device, i'm getting :
_bluetooth.error: (98, 'Address already in use'
just a stupid question because i think the answer is yes bacause of channels:
is it possible to have multiple program listening on the SAME bluetooth interfaces.
i run the program on root
from bluetooth import *
serversock=BluetoothSocket(RFCOMM)
serversock.bind(("",PORT_ANY))
serversock.listen(1)
advertise_service(serversock,"SampleServer",service_classes = [ SERIAL_PORT_CLASS ],profiles = [ SERIAL_PORT_PROFILE ] )
clientsock,clientinfo = serversock.accept()
print "Accepted connection from " , clientinfo
clientsock.send("PyBluez server says Hello!! ")
data = clientsock.recv(1024)
print "received: " , data
clientsock.close()
serversock.close()
thank you
Check the server's visibility with hciconfig:
# hciconfig
hci0: Type: USB
BD Address: 00:11:22:12:34:56 ACL MTU: 192:8 SCO MTU: 64:8
UP RUNNING PSCAN ISCAN
RX bytes:296 acl:0 sco:0 events:26 errors:0
TX bytes:536 acl:0 sco:0 commands:22 errors:0
In case your local device is invisible, set visibility on with:
hciconfig hci0 piscan
Turn off visibility if needed with:
hciconfig hci0 noscan

Categories

Resources