Wednesday, November 30, 2011

Python String replace

I came across a point where the incoming user string had to be replaced with something i desire . Considering the simplicity of the activity i expected python to have some user defined function . might be a simple thing , but really useful...

replace( old , new, [max count]).
if you have the below
Code :
sample = "this is a test string"
print sample.replace("test" , "long test")
the result will look like this
"this is a long test string"
you dont have to import any library in specific.
the "max" from the syntax constitutes to the number of times the string has to be replaced.

Tuesday, November 29, 2011

Scan for bluetooth devices using python

scan for bluetooth devices using a python script. the below script can be used for performing the same. remember , you will have to install pybluez module (it is available for both windows and linux). now for the script , here you go!

import bluetooth

print "performing inquiry..."

nearby_devices = bluetooth.discover_devices(lookup_names = True)

print "found %d devices" % len(nearby_devices)

for addr, name in nearby_devices:
print " %s - %s" % (addr, name)


this will print the number of devices , address and name . this can be used as test script for a variety for reasons .

Tuesday, November 8, 2011

Open EXE with Python

I guess we all reach a point in our scripting space when we end up with opening an exe file from the script. Well , here the code for it . just replace the contents with the values you desire

import subprocess
import os
from win32api import ShellExecute
ShellExecute(0, "open","C:\\XXXX\\XXXX.exe","" , "C:\\XXX", 1)

There might be other ways of doing it , but i believe this one is simple enough for you to try.


Monday, November 7, 2011

AT Commands Python

You can send AT commands to phone when connected to pc via the below progaram . i was able send the commands successfully. Remember most of the phones will have the DUN port open , if you don't connect the machine to a Linux box and run hciconfig command to see the configurations. if you dont have a linux box , just use a virtual box application and download ubuntu which is free of cost

in the case of a android phone , i made use of an application called padNEt 3.02 which helps you turn on the DUN port.

you can use the below mentioned code to send AT commands over bluetooth too. identify the appropriate profile and sent id accordingly.

#!/usr/bin/env python

# ATsend.py
#
# Turn the phone bluetooth off and on each time you
# send the At commands to free up the DUN port
#
# Requires Pybluez from Google
# http://pybluez.googlecode.com
# PyBluez works on GNU/Linux and Windows XP (Microsoft and Widcomm Bluetooth stacks)
#
# Send At commands to mobile device via DUN
#
# Some code to show how to dial a number with
# AT commands also shown below
#

import sys
import bluetooth
from bluetooth import * #Pybluez http://pybluez.googlecode.com

deviceName = []
deviceAddress = None
foundDevices = bluetooth.discover_devices()
if len(foundDevices) == 0:
print "No Bluetooth device found"
exit(0)
count = 0
while count == 0:
for bdaddr in foundDevices:
deviceName.append(bluetooth.lookup_name( bdaddr ))
deviceAddress = bdaddr
print "%2d %-16s Address: %s" % (count +1, deviceName[count], deviceAddress)
count += 1
choice = raw_input("Choose Device or 0 to repeat scan")

# Repeat scan to get more device names
if (choice.isdigit() and int(choice) <= len(foundDevices)):
count = int(choice)
else:
print "Invalid Choice - Please rerun the program"
exit(0)
# choice = raw_input("Choose Device or 0 to repeat scan")
# if (choice.isdigit() and int(choice) <= len(foundDevices)):
# count = int(choice)
#if choice == 0:
# while count == 0:
# for bdaddr in foundDevices:
# deviceName.append(bluetooth.lookup_name( bdaddr ))
# deviceAddress = bdaddr
# print "%2d %-16s Address: %s" % (count +1, deviceName[count], deviceAddress)
# count += 1
# choice = raw_input("Choose Device or 0 to repeat scan")

selected = deviceName[count -1]
deviceAddress = foundDevices[count -1]

if deviceAddress is not None:
print "Identifying the services for the selected devices ....."
else:
print "Could not find a Bluetooth device"
exit(0)

services = bluetooth.find_service(address=deviceAddress)
devicename = bluetooth.lookup_name(deviceAddress, timeout=10)
showProfiles = None

if len(services) > 0:
print "Found %d services on %s\n" % (len(services), deviceAddress)
#
else:
print "No device found at address: %s" % deviceAddress
print
print "Did you turn on bluetooth?"
print "Did you accept/authorize the connection?"
print
sys.exit(3)

dunPort = 0 # Not found yet
# Get Service Details
# global showProfiles
showProfiles = raw_input("Show Bluetooth Profiles supported? y|n")
for svc in services:
# Look for DUN port
if svc["name"] == "Dial-up networking (DUN)":
dunPort = svc["port"]
if showProfiles == "y":
print "BT Profile: %s" % svc["name"]
print " Host: %s" % svc["host"]
print " Description: %s" % svc["description"]
print " Provided By: %s" % svc["provider"]
print " Protocol: %s" % svc["protocol"]
print " channel/PSM: %s" % svc["port"]
print " svc classes: %s "% svc["service-classes"]
print " profiles: %s "% svc["profiles"]
print " service id: %s "% svc["service-id"]
print

if dunPort != 0:
print "Found Dial-Up Networking port = %d\n" % (dunPort)

#s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
#conn = s.connect((deviceAddress, dunPort))
sock=BluetoothSocket( RFCOMM )
sock.connect(("78:47:1D:B6:01:B2", dunPort))
print "socket connected"
# A semicolon ";" at the of the number dialed
# is necessary to make a voice call
# with out the ";" this command will try to
# make a data call

# Example to Dial a number using AT command

#s.send('AT#QAS\r'),
#print s.recv(1024),


# This next section has to expect the correct number of returns
# The first command "ATE1" gets a single "OK" response with a carrage return
# The next commands expects 2 lines returned.
# Each line return ends with \r
# The correct send/expect sequence must be followedd or you will get
# a hang or no response.

#s.send("ATE1\r")
#print s.recv(1024),
s.send("AT\r")
print s.recv(1024)

#s.send("AT+CMGF=1\r")
#print s.recv(1024)
#print s.recv(1024)

#s.send('AT+CMGS="0784XXXXXXX"\r')
#print s.recv(1024)
#s.send("This is freds test!"+chr(26))
#print s.recv(1024)
#print s.recv(1024)

#s.send("AT+GMI\r")
#print s.recv(1024),
#print s.recv(1024),

#s.send("AT+CGMI\r")
#print s.recv(1024),
#print s.recv(1024),

#s.send("AT+GMM\r")
#print s.recv(1024),
#print s.recv(1024),

#s.send("AT+CGMM\r")
#print s.recv(1024),
#print s.recv(1024),

s.close
sys.exit(0)

else :
print "Could not find Dial Up Networking port."
print "Or DUN port is busy."
print "Switch the target's Bluetooth off then on and retry"
sys.exit(4)

Friday, November 4, 2011

pylbuez SDP

We have seen that Bluetooth devices can locate other nearby devices, those that are in discovery mode. Rather than connecting by the address and port of a device and application, devices can discover the address and port by the service names.

The following version performs the same function but using SDP. On the server-side, the primary use of SDP to advertise the helloService as a serial port or RFCOMM protocols.

The client first finds a list of devices that provide the helloService (in reality, more than just helloService is returned). The list is then searched for the helloService, when found, the associated host address and port are used to connect to the service.

Client Code:


from bluetooth import *

services=find_service(name="helloService",
uuid=SERIAL_PORT_CLASS)

for i in range(len(services)):
match=services[i]
if(match["name"]=="helloService"):
port=match["port"]
name=match["name"]
host=match["host"]

print name, port, host

client_socket=BluetoothSocket( RFCOMM )

client_socket.connect((host, port))

client_socket.send("Hello world")

client_socket.close()

break


Server Code:

import bluetooth

server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

server_sock.bind(("",bluetooth.PORT_ANY))
server_sock.listen(1)

bluetooth.advertise_service(server_sock, "helloService",
service_classes=[bluetooth.SERIAL_PORT_CLASS],
profiles=[bluetooth.SERIAL_PORT_PROFILE])

client_sock, address = server_sock.accept()
print "Accepted connection from ",address

data = client_sock.recv(1024)
print "received [%s]" % data

client_sock.close()
server_sock.close()

Thursday, November 3, 2011

pybluez bluetooth inquiry

In my yesterday's blog i was talking about pyserial module . today's post i wanted to share a test code for pybluez module which is a python wrapper around the Bluetooth stack. in this sample code below , we will perform a inquiry of all the Bluetooth devices nearby and list them.

from bluetooth import *
print "performing inquiry..."
nearby_devices = discover_devices(lookup_names = True)
print "found %d devices" % len(nearby_devices)
for name, addr in nearby_devices:
print " %s - %s" % (addr, name)


don't forget to download the pybluez module before you try this. this will be an important step.
you will end up getting errors that the bluetooth module is not available if you try to run the program as is.

happy testing!

Wednesday, November 2, 2011

pyserial

pyserial module is really useful . i have been using it for perfroming uart related communication.
there a lot of sites which provides this pyserial downloads.
import serial
ser = serial.Serial(0) # open serial port
print ser.portstr # prints the used port
ser.write("hello") # write a string
ser.close()
you can use the above code as a test program for performing a pyserial communication from windows.