Fast Bluetooth Name Lookup - python

I'm experiencing problems in fast detecting nearby bluetooth devices' names (human names, not BTADDR)
I found a very interesting Python-based project here [http://code.google.com/p/python-bluetooth-scanner/] but the issue basically is that, while looking for BTADDR and RSSI is fast, detecting the "human" name of the device takes longer (even if they say it should work in the code)
I know I can look up for names with:
the simple "hcitool scan" console command, which is slow
the bluetooth.lookup_name(address) method of module PyBlueZ
as written in the project, reported below
-
sock = bluetooth.bluez._gethcisock(device)
timeoutms = int(timeout * 1000)
try:
name = bluetooth._bluetooth.hci_read_remote_name( sock, address, timeoutms )
except bluetooth._bt.error, e:
print e
logger.debug("Lookup Failed")
name = None
sock.close()
return name
A brief insight: the system uses 2 dongles to detect nearby BT devices, if I make them looking up for names, they spend more time hence remaining locked, when a new device is discovered, devices are still locked in looking for the previous one's name and the whole software hangs.
I'm running Ubuntu 10.10 in a VirtualBox in WindowsXP environment and a couple BT 2.1 dongles.
Apart from creating a list of "unnamed" devices to look for as soon as my dongles are done with the previous ones. Do you know any way I could do that faster?

Finding a remote device's friendly name is generally a two-step process. First, you perform an inquiry scan "discovering" nearby device that are discoverable. Second, you need to connect to
the remote device and "ask" it for its friendly name. Part of the delay comes from the fact that these two steps are often not performed in an interleaved manner (i.e., a device is discovered and then the name is queried). Oftentimes, you run an inquiry scan until completion (which takes a while) and then you ask specific devices for their friendly names. (To interleave the discovery and name lookup, you would start the discovery, wait until you "discover" a new device, cancel the discovery, query for the name, then restart the discovery. Repeat until no new devices are found. Some stacks do this for you automatically. Some don't.)
If both devices support Extended Inquiry Response (added in the Bluetooth 2.1 specification), the friendly name is returned as part of the discovery process. This speeds things up considerably, but it needs to be supported further down in the stack.

Related

CanOpen communication (Python) 1 Slave and CAN-USB adapter

I am currently trying to implement simple communication between an I/O module as a CanOpen slave and my computer(Python script). The I/O module is connected to my computer with a PEAK USB-CAN adapter.
My goal would be to read or write the inputs/outputs. Is this even possible with the hardware, since I don't have a real "master" from that point of view?
Unfortunately I don't know what else I have to do to be able to communicate correctly with my I/O module.
import canopen
import time
network = canopen.Network()
network.connect(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)
#add node and DCF File
IO_module = network.add_node(1, 'path to my DIO.DCF')
network.add_node(IO_module)
IO_module.nmt.state = 'RESET COMMUNICATION' # 000h 82 01
print(IO_module.nmt.state)
time.sleep(5)
IO_module.nmt.state = 'OPERATIONAL'
print(IO_module.nmt.state)
for node_id in network:
print(network[node_id])
IO_module.load_configuration()
i see some kind of communication in my console with timeout errors
INITIALISING
OPERATIONAL
<canopen.node.remote.RemoteNode object at 0x000002A023493A30>
Transfer aborted by client with code 0x05040000
No SDO response received
Transfer aborted by client with code 0x05040000
No SDO response received
Any advices ?
I can't get any further with the documentation alone
https://canopen.readthedocs.io/en/latest/
thank you
The good news is, you probably have all the required hardware. You are doing the "master" part from Python, that's fine. (The CAN bus isn't really master/slave, just broadcast. CANopen can be master/slave sometimes, but it's still all broadcast messages among equals on the same bus.)
You haven't provided information about your device, but I would start checking at a lower level.
Do you even have the CAN-Bus wired up correctly, and if so, what did you do to verify it? (Most common mistake: CAN-Bus not terminated with two 120ohm resistors. Though you usually can get away with just one instead of two.) And have you verified that you are using the correct baud rate?
The library docu example suggests to wait for the heartbeat with node.nmt.wait_for_heartbeat(). Why are you using a sleep instead? If there is no heartbeat, you don't need to continue. (Unless the device docu says that it doesn't implement NMT heartbeat - would be unusual.)
I certainly wouldn't try to go ahead with SDOs if you cannot confirm a NMT heartbeat. Also, some devices don't implement SDOs but only PDOs.
Try sniffing the CAN bus at a lower level (e.g. not PDOs/SDOs but just print the raw messages received - from Python, or with a separate application - e.g. candump on Linux.) Try getting statistics of the CAN "network" interface (on Linux, e.g. ifconfig). If everything is okay, the adapter should be in state "ERROR-ACTIVE", and you should see the frame counter increase for frames you've sent via Python.

Raspberry pi protection against reverse engineering the codes

Problem
I want to secure my Raspberry pi in a special way.
I would like to start up raspberry pi without entering a password as pi user.
However, I want pi user to have zero privilege. Cant read a file, cant copy a file, simply nothing. And without access to root->'sudo su'. On the other hand when raspberry pi starts itself with pi user, I want backend process to be running as root. So to put it simply, I want it like in a zoo - two worlds but neither of them can enter the other. Clients can be present, see what process are running, see files in directories, but cant read it, copy, remove and etc. In the same time I want the backend to be untouched and running and writing files.
Reason:
I have raspberri pi product - customer get it home, when plug in power supply,RPi starts up and runs backend programs with root privilege and communicates with my desktop software.
But I dont want curious customer that plugs in HDMI and see my code. I also dont want him to take the SD card and extract the code.
I heard its possible to reverse engineer the code even if compiled. So I simply want the programs(python script) to be there but cannot be accessed in any way.
Is it possible to make such protection?
Thanks in advance
You may consider to use the following approach
Use at least two levels of hashing with MAC address and ARM chip serial number (via cat /proc/cpuinfo) with additional secret keys. Run your program only if the stored license key is the same as the result of doubly-hashed functions.
Optionally, you could rewrite critical part of your code in C, compile it statically, and remove all debug symbols. Call it using Python.
Quick optimization of your code using cython. Call its generated shared objects with a python caller script. Distribute only the shared objects and the python caller script.
This will prevent most people from reverse engineering your codes.
Just to be clear, "cant read a file" means "can't run a program", which means "can't see what process are running, see files in directories".
From your question, I don't understand why you'd even leave the pi user in place...
... runs backend programs with root privilege
Never a good idea - use service accounts instead.
But I dont want curious customer that plugs in HDMI and see my code.
Then don't enable the HDMI output, don't have a graphical desktop installed and disable the login prompt. You might want to look at a "minimal" / "lite" image.
Remember that the UART can present a login prompt, so make sure that's disabled too.
And as the config.txt and kernel need to be in cleartext in the boot partition they can be easily swapped... thus these steps are not going to be terribly effective.
I also dont want him to take the SD card and extract the code.
You could look at encrypting the filesystems (e.g: LUKS), but the Raspberry Pi has no native ability to store data and identify itself... so your encryption key can only be something like the MAC address, or stored in cleartext on the SD card...
Fundamentally this is just going to be a deterrent from casual "oh what's this" investigations.
"Physical access is total access"... once you put it in the customer's hands, you're looking at deterrents more than absolutes.
I heard its possible to reverse engineer the code even if compiled. So I simply want the programs (python script) to be there but cannot be accessed in any way.
Python doesn't get compiled until runtime, so you'll need to ship the device with your source code on it...
If you really want to secure your Intellectual Property, then perhaps the Raspberry Pi isn't the best option? It's up to you to balance cost vs security.

Turn off specific USB port in windows with python

This is my first post, and I kind of have seen that the more specific the better, so I'll try to be super clear, and thanks in advance!
What I want:
I need to scan images from 2 or more scanners at the same time, these scanners are from the same brand and model, in this case Epson Perfection V600, I need different time intervals for at least 40 captures over a course of 20 hours.
My approach
I decided to use Windows, I already have a program in Python that does what I want with just one scanner, or with two from different models. But here is where you guys come in:
The problem
Windows always prints with the same scanner, Since they are from the same brand and model it always uses the same one, and I cannot use two different scanners because that will cause the images not to be comparable. Nevertheless, when I use two different scanners, I don't have such problem. I need to find a way to print with each scanner. I thought in buying a USB hub and control it with python as well, but apparently given libsub implementation in windows, I will not be able to control it. So I'm currently Looking for a way to disable an specific USB port so the program will only recognize one device, scan with it, disable that one, re-enable the other one, and so on.
What I have access to:
Right now I'm using Windows 10, 64 bits, python kernel 3 in a python 3.5 version inside a Conda environment, conda version (4.5.11).
Ubuntu 16.04, 64 bits, with pyinsane working, in a python 3.5 environment inside conda (don't have the conda version at hand).
One Epson perfection V600.
Two Canon Lide200, working only in windows, because drivers are not available in Ubuntu.
What I have also tried
Using Ubuntu,
I thought it was a good Idea, but the Epson drivers webpage fails to connect to the repository containing the rest of the Epson files, letting me only partially download the files, I already tried to contact the owner of the Docky repository, but he fails to contact me.
The error:
W: The repository 'http://ppa.launchpad.net/docky-core/ppa/ubuntu Xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://ppa.launchpad.net/docky-core/ppa/ubuntu/dists/xenial/main/binary-amd64/Packages 404 Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.
when I manually try to enter the site's repository I found that
All links to XENIAL drivers are down, actually the whole Xenial
Folder is missing.
Also then thought it was a good idea to ignore this message, but I
Need the Epwoka driver to run Epson scanners in Ubuntu, and that
a whole problem by itself. Aside from that, is not known if Epson
Perfection V600 is going to be possible to be controlled by the
PyInsane lib, since is marked as untested.
Using Windows
I thought in buying an USB hub and to controlled as shown in this thread, but apparently is not possible in windows.
I already installed libsub, usb.util, libusb1,USB (for the core functions) and usb1, but I don't know (I think is not possible) to disable and re-enable a specific USB port with them.
Can't disable the drivers since that mean all USB will be down to connect with the scanners.
Device manager is not helping, because of the inability of telling which device is which.
Cannot change the name of the scanner (yes, printers can have specific names) but scanners can't.
Can't buy another scanner, I'm stuck with Epson.
My code for Scanning
import pyinsane2
def Scan(Device, dpi):
pyinsane2.init()
try:
pyinsane2.set_scanner_opt(Device, 'resolution', [dpi])
pyinsane2.set_scanner_opt(Device, 'mode', ['Color'])
pyinsane2.maximize_scan_area(Device)
scan_session = Device.scan(multiple=False)
try:
while True:
scan_session.scan.read()
except EOFError:
pass
Image = scan_session.images[-1]
finally:
pyinsane2.exit()
return(Image)
devices = pyinsane2.get_devices()
image_a = Scan(devices[0], 75)
image_b = Scan(devices[1], 75)
a = devices[1]
b = devices[0]
a == b #Different
a.dev_type == b.dev_type
a.model == b.model
a.name == b.name #Different
a.nice_name == b.nice_name
a.options == b.options
a.reload_options == b.reload_options #Different
a.scan == b.scan #Different
a.srcs == b.srcs #Different
a.vendor == b.vendor
I put a sticki note inside each Scanner, one with an "a" the other one with a "b" and it always scans with the scanner that I plugged in first
This is what I would like to do (and doing it manually works): .
This is what I get when trying in python:
Any solution will help me, get creative! I was thinking on using a .bat file to disable an specific port and calling it with Python. But I couldn't find a way to make it.Keep in mind that doing it manually is not an option 'cause of the 20 to 40 hours of continuous image acquisition.
Thanks!
~Diego

Listening for GPIB events

I am controlling a test system using PyVisa/GPIB. The system is comprised of two separate testers (A and B) and a laptop. The the laptop passively listens for a GPIB message from tester A, when received the laptop triggers tester B.
I am using the following code to passively listen for events from tester A:
rm = visa.ResourceManager()
con = "GPIB0::3"
tester_A = rm.get_instrument(con, timeout=5000)
while True:
event = None
try:
event = tester_A.read_raw()
except VisaIOError:
logger.warning("Timeout expired.")
if event != None:
# Do something
Is there a better way to listen and respond to events from tester A? Is there a better way to control this system via GPIB?
The approach you describe will work, but as you are experiencing, is not ideal if you are not quite sure when the instrument is going to respond. The solution lies in using the GPIB's service request (SRQ) functionality.
In brief, the GPIB connection also provides various status registers that allow you to quickly check, for example, whether the instrument is on, whether an error has occurred, etc. (pretty picture). Some of the bits in this register can be set so that they turn on or off after particular events, for example when an operation is complete. This means you tell the instrument to execute a series of commands that you suspect will take a while, and to then flip a bit in the status register to indicate it is done.
From within your software you can do a number of things to make use of this:
Keep looping through a while loop until the status bit indicates that the operation is complete - this is very crude and I wouldn't recommend it.
VISA has a viWaitOnEvent function that allows you to wait until the status bit indicatesthat the operation is complete - a good solution if you need all execution to stop until the instrument has taken a measurement.
VISA also allows you to create an event that occurs when the status bit has flipped - This is a particularly nice solution as it allows you to write an event handler to handle the event.

Detecting serial port settings

From time to time I suddenly have a need to connect to a device's console via its serial port. The problem is, I never remember what port settings (baud rate, data bits, stop bits, etc...) to use with each particular device, and documentation never seems to be lying around when it's really needed.
I wrote a Python script, which uses a simple brute-force method (i.e. iterates over all possible settings, sends some test input and displays the response for a human to decide if it makes sense ), but:
it takes a long time to complete
does not always work (perhaps port reset/timeout issues)
just does not seem like a proper way to do this :)
So the question is: does anyone know of a procedure to auto-detect what port settings the remote device is using?
Although part 1 is no direct answer to your question:
There are devices, which just have a autodetection (called Auto-bauding) method included, that means: Send a character using your current settings (9k6, 115k2, ..) to the device and chances are high that the device will answer with your (!) settings. I've seen this on HP switches.
Second approach: try to re-order the connection possibilities. E.g. chances are high that the other end uses 9k6 with no hardware handshake, but less that it uses 38k4 with software Xon/Xoff.
If you break down your tries into just a few, the "brute force" method will be much more efficient.

Categories