Showing posts with label PyS60. Show all posts
Showing posts with label PyS60. Show all posts

Downloading and playing of a video

import appuifw, e32 
# import urllib import urllib  print "press options"  
# function that handles the fetching and the playing of the video def fetching():     
# define the url where the video file is located on the server     
url = "http://www.leninsgodson.com/courses/pys60/resources/vid001.3gp"     
# define the loction on the phone where the fetched video file shall be stored     
tempfile = "e:\\video01.3gp"     
try:         
print "Retrieving information..."         
# fetch down the video and store it to you hard drive         
urllib.urlretrieve(url, tempfile)         
# create an active object before playin the video         
lock=e32.Ao_lock()         
# a content handler handles the playing of the video         
# load the content handler and tell to release the active object after the video has finnished playing (lock.signal)         content_handler = appuifw.Content_handler(lock.signal)         
# open the video via the content handler. It will start playing automatically         
content_handler.open(tempfile)         
# Wait for the user to exit the image viewer.         
lock.wait()         
print "Video viewing finished."     
except:         
print "Problems."   
def quit():     
app_lock.signal()  
# define the application menu with one choice "get video" and call the fetching video 
appuifw.app.menu = [(u"get video", fetching)]  
appuifw.app.title = u"Get video"  
appuifw.app.exit_key_handler = quit 
app_lock = e32.Ao_lock() 
app_lock.wait() 

Bluetooth: Background scanning

# install first the following files to your phone # (they will install automatically the needed libraries for the script below): # aosocket-series60_v20.sis, pdis.sis # found at: http://pdis.hiit.fi/pdis/download/pdis/  # this script was found from forum.nokia.com  import e32 import appuifw import aosocketnativenew from pdis.lib.logging import * import httplib, urllib  init_logging(FileLogger("c:\\bt_probing.txt"))  def tell(string):     logwrite(string)     if e32.is_ui_thread():         print string         e32.ao_yield()  # ---------------------------------- from aosocket.symbian.bt_device_discoverer import * from socket import * # for obex file send  def discovered(error, devices, cb_param):     if error == 0:        #tell("devices: " + str(devices))         tell(" ")         for address, name in devices:                   tell("Found: " + address + " | " + name)                for address, name in devices:                 tell(" ")                 try:                     address2, services = bt_discover(address)	#find services and port number                                         tell("Probing: " + address + " | " + name)                     tell("RFCOMM Services: ")                     tell(services)                     tell(services.values()[0]) # port number of first RFCOMM service found                     tell(" ")                 except:                     pass                     #tell("ooooops with " + name)                     #log_exception()                              for address, name in devices:                 try:                     address3, services2 = bt_obex_discover(address)	#find obex service port number                                   tell("Probing: " + address + " | " + name)                     tell("OBEX SERVICES: ")                     tell(services2)                     tell(services2.values()[0]) # port number of first OBEX service found                     tell(" ")                 except:                     pass                          else:         tell("device discovery failure: error %d" % error)     _discoverer.close()       # -----------------------------------------------------------------------------   while(1):     try:         _discoverer = BtDeviceLister()         _discoverer.discover_all(discovered, None)         tell("discovering")         e32.ao_sleep(30)         print "scanning again"     except:         tell("init failure")         appuifw.note(u"Fatal error.", "error")

Bluetooth: OBEX (Client)


# this file lets 2 phones exchange a file via OBEX
# this file is the client side
# the corresponding server side file is called obex_server.py

from socket import *
import appuifw
import e32

# JL: you don't need a socket for this!
## create socket
#s=socket(AF_BT,SOCK_STREAM)

# scan for other phones offering OBEX service
addr,services=bt_obex_discover()
print "Discovered: %s, %s"%(addr,services)
if len(services)>0:
choices=services.keys()
choices.sort()
choice=appuifw.popup_menu([unicode(services[x])+": "+x
for x in choices],u'Choose port:')
port=services[choices[choice]]
else:
port=services[services.keys()[0]]
address=(addr,port)

# create file to be sent
send_path = u"c:\\test.txt"
f=open(send_path, 'w')
f.write("hello")
f.close() # NOTE: parens were missing here before!

# send file via OBEX
print "Sending file %s to host %s port %s"%(send_path, address[0], address[1])
bt_obex_send_file(address[0], address[1], send_path)
print "File sent."

Bluetooth: OBEX (Server)

# This script lets 2 phones exchange a file via OBEX. # This is the server, the corresponding client is obex_client.py from socket import * import appuifw  # Create a bluetooth socket in waiting state to be connected to s = socket(AF_BT, SOCK_STREAM) port = bt_rfcomm_get_available_server_channel(s) print "Binding service to port %s"%port s.bind(("", port)) print "Service bound."  # Advertise the OBEX service, so it can be seen by other phones service_name=u"Test OBEX service"  print "Advertising service as %s"%repr(service_name) bt_advertise_service(service_name, s, True, OBEX)  try:      print "Setting security to AUTH."     set_security(s, AUTH)      receive_path = u"c:\\obex.txt"     print "Receiving file."     bt_obex_receive(s, receive_path)     print "File received."      import e32     e32.ao_sleep(1) finally:     print "Stopping service advertising."     bt_advertise_service(service_name, s, False, OBEX)  print "Closing socket." s.close() print "Socket closed." print "Finished."

Bluetooth: RFCOMM (Client)

# this file lets 2 phones exchange data via RFCOMM # this file is the client side # the corresponding server side file is called rfcomm_server.py  import socket import appuifw import e32  class BTReader:     def connect(self):         self.sock=socket.socket(socket.AF_BT,socket.SOCK_STREAM)         addr,services=socket.bt_discover()         print "Discovered: %s, %s"%(addr,services)         if len(services)>0:             import appuifw             choices=services.keys()             choices.sort()             choice=appuifw.popup_menu([unicode(services[x])+": "+x                                        for x in choices],u'Choose port:')             port=services[choices[choice]]         else:             port=services[services.keys()[0]]         address=(addr,port)         print "Connecting to "+str(address)+"...",         self.sock.connect(address)         print "OK."      def readline(self):         line=[]         while 1:             ch=self.sock.recv(1)             if(ch=='\n'):                 break             line.append(ch)         return ''.join(line)     def close(self):         self.sock.close()  bt=BTReader() bt.connect() print "Received: "+bt.readline() bt.close() 

Bluetooth: RFCOMM (Server)

# this file lets 2 phones exchange data via RFCOMM # this file is the server side # the corresponding client side file is called rfcomm_client.py  from socket import * import appuifw  server_socket = socket(AF_BT, SOCK_STREAM) p = bt_rfcomm_get_available_server_channel(server_socket) server_socket.bind(("", p)) print "bind done" server_socket.listen(1) bt_advertise_service( u"jurgen", server_socket, True, RFCOMM) set_security(server_socket, AUTH) print "I am listening"  # Note: Don't call .send or .recv on the server_socket! # Use the sock object returned by server_socket.accept(). (sock,peer_addr) = server_socket.accept() print "Connection from %s"%peer_addr test = appuifw.query(u"Type words", "text", u"") sock.send(test+'\n') print "sending done" import e32 # Allow time for data to be sent to work around a bug in the socket # module. e32.ao_sleep(1) sock.close()
 
 

Mobile to PC Bluetooth Connection

# script that connects to the serial port of the PC # and lets you send characters to the PC  import appuifw # import the module socket import socket import e32  # function that handles the bluetooth connection: def bt_connect():     global sock     # create a bluetooth socket     sock=socket.socket(socket.AF_BT,socket.SOCK_STREAM)     target=''# here you can give the bt address of the other mobile if you know it     if not target:         # scan for bluetooth devices         address,services=socket.bt_discover()         print "Discovered: %s, %s"%(address,services)         if len(services)>1:             choices=services.keys()             choices.sort()             # bring up a popup menu and show the available bt devices for selection             choice=appuifw.popup_menu([unicode(services[x])+": "+x                                         for x in choices],u'Choose port:')             target=(address,services[choices[choice]])         else:             target=(address,services.values()[0])     print "Connecting to "+str(target)     # connect to the serial port of the PC     sock.connect(target)     print "OK."      # call the text input field function        bt_typetext()          # define the textinput function def bt_typetext():     global sock     # create the text input field     test = appuifw.query(u"Type words", "text", u"")     # if cancel has been pressed, then quit the application otherwise send the character over bluetooth     if test == None:         exit_key_handler()     else:         # send the typed in characters over bluetooth to the PC         sock.send(test)         # call again the textinput field function to show the text input again         bt_typetext()  def exit_key_handler():     script_lock.signal()     appuifw.app.set_exit()  appuifw.app.title = u"bt mob to PC"  script_lock = e32.Ao_lock()  appuifw.app.exit_key_handler = exit_key_handler()  # call the function that handles the bluetooth connection bt_connect()  script_lock.wait()

Playing Midi

# playing Midi    import appuifw import e32 import audio   def playsound1():     S = audio.Sound.open("E:\\sound1.mid")     S.play()     menu()      def playsound2():     S = audio.Sound.open("E:\\sound2.mid")     S.play()     menu()   def exit_key_handler():     appuifw.app.set_exit()      def quit():     appuifw.app.set_exit()  L = [u"sound 1", u"sound 2", u"exit"]  def menu():     index = appuifw.popup_menu(L,u'select')     if index == 0:         playsound1()     if index == 1:         playsound2()     if index == 2:         quit()          appuifw.app.title = u"Midi player"  appuifw.app.exit_key_handler = exit_key_handler menu()

Recording & Playing wave

# Sound recording / playing script   import appuifw, e32 # import the audio module import audio   # define a name of the file to be the sound file, incl. its full path filename = 'e:\\boo.wav'  # define the recording part: def recording():     global S     # open the sound file to be ready for recording and set an instance (S) of it     S=audio.Sound.open(filename)     # do the recording (has to be stopped by closing() function below)     S.record()     print "Recording on! To end it, select stop from menu!"  # define the playing part: def playing():     global S     try:         # open the sound file to be ready for playing by setting an instance (S) of it         S=audio.Sound.open(filename)         # play the sound file         S.play()         print "Playing"     except:         print "Record first a sound!"  # stopping of recording / playing and closing of the sound file def closing():     global S     S.stop()     S.close()     print "Stopped"  def quit():     script_lock.signal()     appuifw.app.set_exit()  # define the application menu appuifw.app.menu = [(u"play", playing),                     (u"record", recording),                     (u"stop", closing)]  appuifw.app.title = u"Sound recorder"  appuifw.app.exit_key_handler = quit script_lock = e32.Ao_lock() script_lock.wait()  

S60 Application tabs

# This script creates tabs that let you switch between different applications # listbox app, listbox app and canvas app   import appuifw import e32 from graphics import *   # define application 1: listobx app  # create your icons for the listbox content   icon1 = appuifw.Icon(u"z:\\system\\data\\avkon.mbm", 28, 29) icon2 = appuifw.Icon(u"z:\\system\\data\\avkon.mbm", 40, 41) icon3 = appuifw.Icon(u"z:\\system\\data\\avkon.mbm", 30, 31) icon4 = appuifw.Icon(u"z:\\system\\data\\avkon.mbm", 32, 33) icon5 = appuifw.Icon(u"z:\\system\\data\\avkon.mbm", 34, 35) icon6 = appuifw.Icon(u"z:\\system\\data\\avkon.mbm", 36, 37) icon7 = appuifw.Icon(u"z:\\system\\data\\avkon.mbm", 38, 39)  # create your content list of your listbox including the icons to be used for each entry entries = [(u"Signal", icon1),            (u"Battery", icon2),            (u"Sirene", icon3),            (u"Waste", icon4),            (u"Helicopter", icon5),            (u"Train", icon6),            (u"Auto", icon7)]  # create the listbox callback handler def handler():     print "done"      # create an instance of appuifw.Listbox(), include the content list "entries" and the callback function "handler" app1 = appuifw.Listbox(entries,handler)    # define application 2: listbox app  # define the list of items as pop-up menu content L2 = [u"Stefan", u"Holger", u"Emil", u"Ludger"]  # create the listbox callback handler def handler_L2():     print "ola"  # create the pop-up menu  app2 = appuifw.Listbox(L2, handler_L2)     # define application 3: canvas application  def app_3():     global canvas     img=Image.new((176,208))     img.line((20,20,20,120),0xff00ee)     img.rectangle((40,60,50,80),0xff0000)     img.point((50.,150.),0xff0000,width=40)     img.ellipse((100,150,150,180),0x0000ff)     img.text((100,80), u'hello')          # define your redraw function (still belonging to app 3)      def handle_redraw(rect):     #global canvas         canvas.blit(img)     # define the canvas, include the redraw callback function     canvas =appuifw.Canvas(event_callback=None, redraw_callback=handle_redraw)     appuifw.app.body = canvas        def exit_key_handler():     app_lock.signal()  # create a tab handler that switches the application based on what tab is selected def handle_tab(index):     global lb     if index == 0:         appuifw.app.body = app1 # switch to application 1     if index == 1:         appuifw.app.body = app2 # switch to application 2     if index == 2:         app_3() # switch to application 3       # create an Active Object app_lock = e32.Ao_lock()  # create the tabs with its names in unicode as a list, include the tab handler appuifw.app.set_tabs([u"One", u"Two", u"Three"],handle_tab)  # set the title of the script appuifw.app.title = u'Tabs advanced'  # set app.body to app1 (for start of script) appuifw.app.body = app1   appuifw.app.exit_key_handler = exit_key_handler app_lock.wait()

S60 Application Menu

# this script lets you create a simple application menu  # NOTE: # press the options key in order to open the applicaion menu # when running the script!  # imort appuifw and the e32 modules import appuifw, e32  # create the "callback functions" for the application menu def item1():     appuifw.note(u"Foo", "info")  def item2():     appuifw.note(u"Outch", "info")      # define an exit handler function def quit():     app_lock.signal()  # create the application menu include the selectable options (one, two) # and the related callback functions (item1, item2)  appuifw.app.menu = [(u"one", item1),                     (u"two", item2)]  appuifw.app.exit_key_handler = quit  # create an active object app_lock = e32.Ao_lock()  # start a scheduler app_lock.wait()

S60 Application Skeleton (with MainLoop)

# Application skeleton with main loop (while loop)   import appuifw import e32   appuifw.app.screen='large'   # create your application logic ...   running=1  def quit():     global running     running=0      app.exit_key_handler=quit  appuifw.app.title = u"drawing"  appuifw.app.body= ...   while running:     # handle_redraw(())     e32.ao_sleep(0.5)      """ description:  # 1. import all modules needed import appuifw import e32  # 2. set the screen size to large appuifw.app.screen='large'    # 3. create your application logic ... # e.g. create all your definitions (functions) or classes and build instances of them or call them etc. # ...... application logic ....  running=1    # 4. no application menu here neccessary  # 5. create and set an exit key handler: when exit ley is pressed, the main loop stops going (because the variable running will be put to 0= def quit():     global running     running=0      app.exit_key_handler=quit  # 6. set the application title appuifw.app.title = u"drawing"  # 7. no active objects needed  # 8. set the application body  appuifw.app.body= ...  # 9. create a main loop (e.g. redraw the the screen again and again) while running:     # #put here things that need to be run through again and again     # #e.g. redraw the screen:     # handle_redraw(())     # yield needs to be here e.g. in order that key pressings can be noticed     e32.ao_yield()   """ 

S60 Application Skeleton

# Application skeleton (no main loop)  import appuifw import e32  appuifw.app.screen='large'    # create your application logic ...   def item1():     print "hello"  def subitem1():     print "aha"  def subitem2():     print "good"  appuifw.app.menu = [(u"item 1", item1),                     (u"Submenu 1", ((u"sub item 1", subitem1),                                     (u"sub item 2", subitem2)))]      def exit_key_handler():     app_lock.signal()  appuifw.app.title = u"drawing"       app_lock = e32.Ao_lock()  appuifw.app.body = ...   appuifw.app.exit_key_handler = exit_key_handler app_lock.wait()     """ description:   # 1. import all modules needed import appuifw import e32  # 2. set the screen size to large appuifw.app.screen='large'     # 3. create your application logic ... # e.g. create all your definitions (functions) or classes and build instances of them or call them etc. # ...... application logic ....     # 4. create the application menu including submenus # create the callback functions for the application menu and its submenus def item1():     print ""     round.set(u'item one was selected')  def item1():     print "hello"  def subitem1():     print "aha"  def subitem2():     print "good"  appuifw.app.menu = [(u"item 1", item1),                     (u"Submenu 1", ((u"sub item 1", subitem1),                                     (u"sub item 2", subitem2)))]        # 5. create and set an exit key handler def exit_key_handler():     app_lock.signal()  # 6. set the application title appuifw.app.title = u"drawing"      # 7. crate an active objects  app_lock = e32.Ao_lock()  # 8. set the application body  appuifw.app.body = ...   # no main loop  appuifw.app.exit_key_handler = exit_key_handler app_lock.wait()  """

Application Canvas Drawing

# This script draws different shapes and text to the canvas   import appuifw from appuifw import * import e32 # import graphics from graphics import *    # create an exit handler def quit():     global running     running=0     appuifw.app.set_exit()  # set the screen size to large appuifw.app.screen='large'  # define an initial image (white) img=Image.new((176,208))  # add different shapes and text to the image # coord. sequence x1,x2,y1,y2 img.line((20,20,20,120),0xff00ee) img.rectangle((40,60,50,80),0xff0000) img.point((50.,150.),0xff0000,width=40) img.ellipse((100,150,150,180),0x0000ff) img.text((100,80), u'hello')   # define your redraw function (that redraws the picture on and on) # in this case we redraw the image named img using the blit function def handle_redraw(rect):     canvas.blit(img)  running=1  # define the canvas, include the redraw callback function canvas=appuifw.Canvas(event_callback=None, redraw_callback=handle_redraw)  # set the app.body to canvas appuifw.app.body=canvas  app.exit_key_handler=quit   # create a loop to redraw the the screen again and again until the exit button is pressed while running:     # redraw the screen     handle_redraw(())     # yield needs to be here in order that key pressings can be noticed     e32.ao_yield()  

Application body Text

import appuifw import e32  def exit_key_handler():     app_lock.signal()  # create an instance of appuifw.Text() round = appuifw.Text() # change the style of the text round.style = appuifw.STYLE_UNDERLINE # set the text to 'hello' round.set(u'hello')  # put the screen size to full screen appuifw.app.screen='full'   # create an Active Object app_lock = e32.Ao_lock()  # set the application body to Text # by handing over "round" which is an instance of appuifw.Text() as definded above appuifw.app.body = round  appuifw.app.exit_key_handler = exit_key_handler app_lock.wait()

Application body Listbox

import appuifw import e32  def exit_key_handler():     app_lock.signal()  # define a callback function def shout():     index = lb.current()     print index     print entries[index]  # create your content list of your listbox including the icons to be used for each entry entries = [u"Signal",u"Battery"] lb = appuifw.Listbox(entries,shout)  # create an Active Object app_lock = e32.Ao_lock()  # create an instance of appuifw.Listbox(), include the content list "entries" and the callback function "shout" # and set the instance of Listbox now as the application body appuifw.app.body = lb   appuifw.app.exit_key_handler = exit_key_handler app_lock.wait()

Application Menu

import appuifw import e32  def exit_key_handler():     app_lock.signal()    # create the callback functions for the application menu and its submenus def item1():     print ""     round.set(u'item one was selected')  def subitem1():     print ""     round.set(u'subitem one was selected')  def subitem2():     round.set(u'subitem two was selected')   app_lock = e32.Ao_lock() round = appuifw.Text() round.set(u'press options') appuifw.app.screen='large' appuifw.app.body = round  # create the application menu including submenus appuifw.app.menu = [(u"item 1", item1),                     (u"Submenu 1", ((u"sub item 1", subitem1),                                     (u"sub item 2", subitem2)))]   appuifw.app.exit_key_handler = exit_key_handler app_lock.wait()

Application Screen

import appuifw import e32  def exit_key_handler():     app_lock.signal()   round = appuifw.Text() round.set(u'hello')  # put the application screen size to full screen appuifw.app.screen='full' #(a full screen)  # other options: #appuifw.app.screen='normal' #(a normal screen with title pane and softkeys) #appuifw.app.screen='large' #(only softkeys visible)    app_lock = e32.Ao_lock()  appuifw.app.body = round  appuifw.app.exit_key_handler = exit_key_handler app_lock.wait()

Defining a function

# defining a simple function   import appuifw  # a function is definded with: def nameoffunction(): # be aware of the indentation! (4 x spacebar)  def afunction():     data = appuifw.query(u"Type a word:", "text")     appuifw.note(u"The typed word was: " +data, "info")   # a function is called with its name and brackets behind it afunction()           

SMS to speech

# This script waits for an incoming sms, reads its 
# content and shows it inside a pop-up note 
# NOTE: PyS60 version 1.3.14 or higher is needed to run this script.  
import inbox 
import e32 
import audio  
#create a function that does the reading of the content of the sms  
def read_sms(id):     
e32.ao_sleep(0.1)     
# read the content out of the message that has just arrived     
sms_text = i.content(id)     
# the phone speaks out the text that just arrived by sms (you can hear it through the loudspeakers of your phone)     
audio.say(sms_text)  
# create an instance of the inbox() class      
i=inbox.Inbox() 
print "send now sms to this phone" 
# put the phone into waiting stage to wait for an incoming message 
i.bind(read_sms)