Archived:How to connect Mobile to PC using PySymbian
All PySymbian articles have been archived. PySymbian is no longer maintained by Nokia and is not guaranteed to work on more recent Symbian devices. It is not possible to submit apps to Nokia Store.
Article Metadata
The following article shows how to connect mobile phone to PC using Python
Contents |
Introduction
There are many platforms and operating systems on which you can connect your mobile phone to PC: Mac OS X, Linux, Windows, etc. In this tutorial, you will see how to connect your mobile device to your PC through a bluetooth connection using Python.
Mobile Code
I have created a generic library rc_phone.py, so you can use it to connect your mobile phone to any device with bluetooth. It provides functions to discover and connect to new devices and also connect to the last successfully connection. In order to use it, put the code in the lib folder inside the phone's Python directory . The code runs in PySymbian version >= 1.4.5. I have tested this code on 5800 Xpress Music (PySymbian 1.9.7) and on N95 (PySymbian 1.4.5).
""""
=======================
rc_phone (Generic library for connect and save connections with Bluetooth)
=======================
(c) 2009 Marcel Caraciolo and Dimas Gabriel
e-mail: caraciol@gmail.com, dimas@dimasgabriel.net
Released under the GNU General Public License
"""
import os,struct
from e32 import pys60_version
if pys60_version.split()[0] >= '1.9.1':
import btsocket as socket
else:
import socket
def connect_phone2Device(config_file_path):
import appuifw
"""
Connect the phone to the device (It can be the last sucessfuly connection or a new connection)
config_file_path: Stores the services names, adresses and ports of previous connections
"""
try:
config = eval(open(config_file_path,'r').read())
except:
config = {'default_services': []}
default_services = config.get('default_services',[])
if len(default_services) > 0:
selected = appuifw.popup_menu([u"Connect to the last saved", u"New device"])
if selected == 0:
#LastDevice
service = default_services[0]
sock = connect2service(service)
if sock:
return sock
elif selected == None:
print 'No device choosen.'
return None
try:
#New Device
service = discover_address()
except Exception:
print "No device chosen."
return None
if service:
config['default_services'].append(service)
#Make sure the configuration file exists
if not os.path.isdir(os.path.dirname(config_file_path)):
os.makedirs(os.path.dirname(config_file_path))
#store the configuration file
open(config_file_path,"w").write(repr(config))
return connect2service(service)
else:
print 'No service choosen.'
return None
def connect2service(service):
"""
Connect to the chosen service.
service: (name,addr,port)
"""
print 'Connecting to %s on %s port %d ...' %service
try:
sock = socket.socket(socket.AF_BT, socket.SOCK_STREAM)
sock.connect(service[-2:])
return sock
except Exception, e:
print 'Failed to connect: %s' %e
return None
def discover_address():
"""
the user is prompted to select device and service.
"""
import appuifw
print "Discovering..."
address, services = socket.bt_discover()
print "Discovered: %s, %s" %(address, services)
if len(services) > 1: #if this host offers more than one service, let the user choose the right one
service_names = services.keys()
service_names.sort()
service_list =[unicode(name) for name in service_names]
choice = appuifw.popup_menu(service_list, u"Choose service:")
if choice == None:
return None
service_name = service_names[choice]
port = services[service_name]
else:
service_name,port = services.popitem()
return (service_name,address, port)
Demo
This is a simple script to show how the library works. It connects to the PC-Server, sends a "Hello World" using a socket connection and after that it closes the connection with a command message "bye". Put this code into the Python directory of your phone.
""""
=======================
remoteTest
=======================
(c) 2009 Marcel Caraciolo and Dimas Gabriel
e-mail: caraciol@gmail.com, dimas@dimasgabriel.net
Released under the GNU General Public License
"""
import os
import rc_phone
import time
from e32 import pys60_version
if pys60_version.split()[0] >= '1.9.1':
CONFIG_FILE = os.path.join(['c:','Personal files','python','rc_com.cfg'])
else:
CONFIG_FILE = os.path.join(['e:','python','rc_com.cfg'])
def main():
print "remoteTest.py start..."
server_sock = rc_phone.connect_phone2Device(CONFIG_FILE)
if server_sock:
print 'Connected...'
try:
time.sleep(1)
print "Sending Hello PC"
server_sock.send('Hello PC')
time.sleep(2)
print "Saying good-bye"
server_sock.send('bye')
except Exception,e:
print 'A problem has occurred when sending data...'
import traceback
traceback.print_exc()
server_sock.close()
else:
print 'remoteTest.py: could not connect.'
print 'remoteTest.py done.'
if __name__ == '__main__':
main()
Server
Now code the server, which will run on the PC. Depending on the OS, there are many third-party libraries. The sections below you will see how to code the server with Python.
Mac OS X
For connect to Mac OS X (>= 10.5), I have used the open-source library [lightblue] http://lightblue.sourceforge.net/. There are versions for linux and Mac OS. To install it, download the LightBlue source files and extract them to some directory. Open a Terminal window, change to that directory, and run the command
''python setup.py install''
To use the lightblue API, use import lightblue. In the official website there are many examples. I've coded one so you can use it to receive the connection of the script above.
""""
=======================
macMote - Server
=======================
(c) 2009 Marcel Caraciolo and Dimas Gabriel
e-mail: caraciol@gmail.com, dimas@dimasgabriel.net
Released under the GNU General Public License
"""
import lightblue
s = lightblue.socket()
s.bind(("",0))
s.listen(1)
lightblue.advertise("MacMote Server", s, lightblue.RFCOMM)
print "Server started..."
conn,addr = s.accept()
print "Connected by", addr
while True:
packet = conn.recv(1024)
if packet == "bye":
break
elif packet != None:
print packet
conn.close()
s.close()
You can see some screenshots of the server running as follow:
Windows
Not coded yet.
Linux
Not coded yet.
Generic
Original article at Mobile Programming PitStop
import bluetooth
import pyosd
from time import sleep
p = pyosd.osd()
p.set_pos(pyosd.POS_MID)
p.set_align(pyosd.ALIGN_CENTER)
p.set_colour("green")
p.display( "Scanning for bluetooth device")
nearby_devices = bluetooth.discover_devices(duration=20, lookup_names = True)
str= "found %d devices" % len(nearby_devices)
print str
p.display(str)
sleep(2)
for name, addr in nearby_devices:
p.display( " %s - %s" % (addr, name))
print (" %s - %s" % (addr,name))
sleep(2)
- Note: sleep and pyosd are external pys60 extensions (may be made by the contributor)
Bold text



This is one of the article which shows the use of Bluetooth module.This article showa the code for connecting a Mobile device to a PC using Bluetooth.
Connect This both device is Not easier task.But using python you can do this.But for this you required Bluetooth port in PC.
Link given in this program get some error.But it sows only This code.
--nayan_trivedi
nokia 5230
Thank you,
I try the code on nokia 5230 and it worked. I only modified the name of the config file in an unicode string.
Cristian Spiridon