Tutorial Python untuk Symbian S60

Ringkasan dan Diskripsi tentang Tutorial Python untuk Symbian S60

Tutorial Python untuk Symbian S60

☞ Pendahuluan :

  • Langkah dasar : telepon, unduhan, pemasangan, SDK
  • Modul telepon PyS60
  • Ekstensi, Platform keamanan
  • PythonForS60 untuk pengembangan middleware

 perangkat yang mendukung Pyhton untuk S60 :

1. S60v3

  • 3250
  • 5500 Sport
  • E50
  • E60
  • E61
  • E62
  • E65
  • E70
  • N71
  • N73
  • N75
  • N77
  • N80
  • N91
  • N91 8GB
  • N92
  • N93

2. S60v3 FP1

  • 5700 XpressMusic
  • 6110 Navigator
  • 6120 Classic
  • 6121 Classic
  • 6124 Classic
  • 6290
  • E51
  • E66
  • E71
  • E90 Communicator
  • N76
  • N81
  • N81 8GB
  • N82
  • N95
  • N95 8GB

3. S60v3 FP2

  • 5320 XpressMusic
  • 6210 Navigator
  • 6220 Classic
  • 6650
  • N78
  • N79
  • N85
  • N96

4. S60v2 FP1

  • 6600
  • 3230
  • 6260
  • 6620
  • 6670
  • 7610

5. S60v2 FP2

  • 6630
  • 6680
  • 6681
  • 6682

6. S60v2 FP3

  • N70
  • N72
  • N90

  Dalam hal ini Python S60 merupakan

  • Sumber Terbuka
  •  Didasarkan pada juru bahasa Python 2.2.2
  •  Versi terbaru PythonS60: 1.4.4 (Juni 2008)
  •  Rilis 2-3 kali setahun atau lebih

☞ Penginstalan Pyhton ke perangkat ponsel

  • Install Python S60 interpreter.sis
  • Install PythonForS60_1_4_4_3rdEd.sis
  • Install the Python Shell.sis
  • Install PythonScriptShell_1_4_4_3rdEd.SIS

☞ Perlengkapan Software untuk dijalankan melalui komputer

  • Unduh S60 Platform SDKs untuk Symbian
  • Unduh SDK Python Untuk S60
  • Anda dapat menjalankan skrip Python di emulator

☞ Firefox emulator + lighttpd (experimental)

  • Tingkatkan siklus pengembangan dengan dapat menjalankan kode PyS60 di destop
  • Mirip dengan kompatibilitas PDIS Perpustakaan
  • Bekerja dengan server SCGI dan Lighttpd
  • PyS60 berjalan di browser

☞ ... PyS60 modules...☜ 

  • Lokasi 

import location

cell_info = location.gsm_location ()

if 4==len(cell_info):

mcc,mnc,lac,cid = cell_info

import location, e32

cell_info = location.gsm_location ()

while 1:

if 4==len(cell_info):

mcc,mnc,lac,cid = cell_info

e32.sleep(60*2)

➜ Maksud inti : fungsi tulis untuk mendapatkan lokasi, menampilkan negara (dari daftar PKS), dan dalam menu : item mulai / berhenti

  • penentuan posisi

import positioning

requestor = {'type':'service', 'format':'application',

'data':'myappname'}

positioning.set_requestors ([requestor])

pos = positioning.position (course=1, satellites=1)

if pos and pos.has_key('position'):

lat = pos['position']['latitude']

lon = pos['position']['longitude']

print "GPS:", lat, lon

➜ Maksud inti : penentuan posisi polling setiap x detik, tulis ke dalam file

  • Kotak Masuk (untuk membaca SMS)

import inbox

received_box = inbox.Inbox (inbox.EInbox)

sent_box

msg_ids

= inbox.Inbox (inbox.ESent)

= received_box.sms_messages ()

msg_ids.sort() # ascending order

id = msg_ids[0] # get the first one (the oldest SMS)

sms = {'content' : received_box.content (id),

'date' : received_box.time (id),

'address' : received_box.address (id),

'status' : received_box.unread(id),

'id' : id, }

print "The oldest SMS I received: ", sms

➜ Maksud inti : Pesan cadangan dalam file ; sepenggal kata (per orang, total); menampilkan semua pesan oleh satu orang; cari di pesan

  • Pesan SMS baru (Panggilan Balik SMS baru)

import inbox

received_box = inbox.Inbox (inbox.EInbox)

def callback(new_id):

sms = {'content' : received_box.content (new_id),

'date' : received_box.time (new_id),

'address' : received_box.address (new_id),

'status' : received_box.unread(new_id),

'id' : new_id, }

print "You got a message!"

received_box.bind(callback)

➜ Maksud inti : menjawab SMS secara otomatis jika berasal dari kontak tertentu dan berisi kata-kata tertentu

  • Pesan (untuk mengirim SMS)

import messaging

contact_number = "+16501112222"

contact_name = "John"

gps = (50.87780, 4.70382)

message = u("Hey, I'm in Belgium. Exactely here:

%s"%gps)

messaging.sms_send(contact_number, message, name=contact_name)

print "Message was sent"

➜ Maksud inti : kirim SMS dengan panggilan balik, kirim MMS dengan gambar terlampir

  • Kontak (buku telepon)

import contacts

# Backup all contacts as vcards, in a text file

cdb = contacts.open()

ids = cdb.keys()

f = open('./contacts_backup.txt', 'w+')

for id in ids:

vcard = cdb.export_vcards( [id,])

info = { 'vcard'

: vcard,

 'date.modif'

: cdb[id].last_modified,

 'id' : id, }

f.write(repr(info))

f.write("\n")

f.close()

➜ Maksud inti : membaca file cadangan, membaca vcard dengan paket vobject bersihkan kontak

  • Kalender

import calendar, time

cdb = calendar.CalendarDb()

print "There are %s calendar entries "%len(cdb)

# Get all entries until now + one month

one_week_in_seconds = 60*60*24*7

entries = cdb.find_instances(time.time()-one_week_in_seconds,

time.time()+one_week_in_seconds)

one_id = entries[0]

one = cdb[one_id['id']]

print "one_id, one

for el in ['type' ,'alarm', 'id', 'content', 'end_time', 'last_modified',

'location', 'originating', 'priority', 'replication', 'start_time',]:

print "%s: "%el, one.__getattribute__(el)

vcal = cdb.export_vcalendars((one_id['id'], ))

➜ Maksud inti : membaca vcal dengan paket vobject

  • appuifw (hal popup)

import appuifw

for typ in ['text', 'code', 'number', 'float', 'date', 'time', 'query',]:

res = appuifw.query(u"Give me a %s"%typ, typ)

print res

options = map ( lambda x : u'Option %s'%x, range(0,5))

res = appuifw.popup_menu(options, u"Which option do you want?")

appuifw.note(u"You have selected %s (%s) "%(options[res], res), 'info')

res = appuifw.selection_list(options, search_field=0)

print res

res = appuifw.multi_query(u"This", u"That")

options = map ( lambda x : u'Option %s'%x, range(0,100))

res = appuifw.multi_selection_list(options, style='checkbox', search_field=1)

print res

appuifw.note(u"Uh uh this does not work: %s (%s) "%(options[res[0]], res[0]), 'error')

➜ Maksud inti : tanyakan secara acak apa yang dilakukan pengguna dan log

  • appuifw (aplikasi)

import appuifw

t = appuifw.Text()

t.add(u"You can display things here, or let the user write: \n")

appuifw.app.body = t

full_s = t.get()

t.clear()

print t.font

print appuifw.available_fonts()

appuifw.app.title = u"Py app"

appuifw.app.screen = 'full'

# 'normal' , 'large', 'full'

def do_something(s='?'): t.add(u" %s \n\n"%s)

appuifw.app.menu=[ (u"Print 1" , lambda: do_something(1) ),

 (u"Print ?" , do_something ),

 (u"Do nothing", lambda: None ), ] 

➜ Maksud inti : aplikasi yang menampilkan pilihan gambar acak, SMS

  • appuifw (template)

import appuifw, e32

class MyApp:

def __init__(self):

self.lock = e32.Ao_lock()

appuifw.app.title = u"My App"

# create UI elements

self.lb = appuifw.Listbox( [u"Item 1", u"Item 2"], self.lb_callback)

self.activate()

def activate(self):

appuifw.app.menu=[ (u"Help", lambda: None), (u"Exit", self.key_exit), ]

appuifw.app.exit_key_handler = self.key_exit

appuifw.app.body = self.lb

def key_exit(self):

self.lock.signal()

def lb_callback(self):

i = self.lb.current()

appuifw.note(u"List callback selection: %s"%i, 'info')

def run(self):

self.lock.wait()

if __name__=="__main__":

global myapp

e32.ao_yield()

myapp = MyApp()

myapp.run()

  • appuifw (Kotak daftar)

import appuifw

# List with a single line

def callback():

current_i = lb.current()

appuifw.note(u"'%s' (%s) was selected"%(l[current_i], current_i), 'info')

l = [ u"Thing %s"%i for i in range(0, 10) ]

lb = appuifw.Listbox(l, callback)

appuifw.app.body = lb

# List with double line

l = [ (u"Thing %s"%i, u"with more info about thing %s"%i) for i in range(0, 10) ]

lb = appuifw.Listbox(l, callback)

appuifw.app.body = lb

  • key_codes (mengikat peristiwa kunci)

import key_codes, appuifw

# You can delete things off the list

def delete_callback():

current_i = lb.current()

l.pop(current_i)

if len(l)==0:

l.append(u"Nothing") # you cannot have an empty list

if len(l)>current_i-1 and current_i-1>=0:

lb.set_list(l, current_i-1)

else:

lb.set_list(l)

l = [ u"Thing %s"%i for i in range(0, 10) ]

lb = appuifw.Listbox(l, callback)

lb.bind(key_codes.EStdKeyHome, delete_callback) # it's the 'C - delete' key

appuifw.app.body = lb

  • Penangkapan kunci (menangkap peristiwa penting global)

import keycapture, appuifw, e32, key_codes

# create a dict of the integer code values, and the name of the key code

values_keynames = dict( [ [val, key] for key, val in key_codes.__dict__.items() if

key[0]=='E'])

t = appuifw.Text(u"Press a key\n")

appuifw.app.body = t

def callback(key):

t.clear()

t.add(u"\nKey pressed: keycodes.%s (%s)"%(values_keynames[key], key))

capturer = keycapture.KeyCapturer(callback)

capturer.keys = keycapture.all_keys

capturer.forwarding = 0

capturer.start()

e32.ao_sleep(20)

capturer.stop()

  • Kanvas

import appuifw

# draw once

c = appuifw.Canvas()

appuifw.app.body = c

c.line([0,0, 200, 250], outline=0x00ff00)

# redrawn after the application screen was hidden by something

def redraw(area_coords):

c.rectangle([0,0, c.size[0], c.size[1]], fill=0x88eeee)

c.line([0,0, 200, 250], outline=0x00ff00, width=3)

c = appuifw.Canvas(redraw)

appuifw.app.body = c

➜ Maksud inti : gunakan fungsi lain - elips, busur, poligon, titik, teks, jelas

  • Kanvas dan grafis

import appuifw, graphics

c = appuifw.Canvas()

appuifw.app.body = c

# draw on a buffer

buf = graphics.Image.new(c.size)

im = graphics.Image.open("C:\\Data\\myapp\\miata.png")

buf.clear()

buf.blit(im)

buf.line([0,0, im.size[0],im.size[1]], outline=0xff0000, width=10)

buf.line([0,im.size[1],im.size[0], 0], outline=0xff0000, width=10)

buf.text([100, 220], u"SOLD", font=(appuifw.available_fonts()[0],

20,graphics.FONT_BOLD))

c.blit(buf)

➜ Maksud inti : menambahkan panggilan balik menggambar ulang;  ambil tangkapan layar

  • Penangan_konten / Content_handler

import appuifw

# Create a simple html file

open("C:/Data/myapp/waffles.html", "w+").write(

"""

Best Waffles are in Belgium

src='http://static.flickr.com/97/265787242_a8d2018f53.jpg' />

""")

ch = appuifw.Content_handler()

# This opens the default web browser because it's a .html file

ch.open(u"C:\\Data\\myapp\\waffles.html")

➜ Maksud inti : meneruskan panggilan balik ke Content_handler;  menggunakan fungsi open_standalone;  unduh URL favorit untuk menjelajah Offline

  • kamera (gambar)

import camera, appuifw

# Take a photo and display it

appuifw.app.body = appuifw.Canvas()

image = camera.take_photo()

appuifw.app.body.blit(image)

# Use the viewfinder

def callback(image):

appuifw.app.body.blit(image)

camera.start_finder(callback)

camera.release()

camera.stop_finder()

➜ Maksud inti : ikat acara kunci ke fungsi yang mengambil foto dan menyimpannya dalam file

  • kamera (video)

import camera, appuifw, e32

appuifw.app.body = appuifw.Canvas()

def callback(image):

appuifw.app.body.blit(image)

camera.start_finder(callback)

def video_cb(code, status):

print code, status

fn = "C:\\Data\\myapp\\video01.mp4"

camera.start_record(fn,video_cb)

e32.ao_sleep(10) # make a 10 seconds video

camera.stop_record()

camera.release()

camera.stop_finder()

➜ Maksud inti : unggah video

  • Telepon

import telephone, e32

telephone.dial(u"+16505758524")

e32.ao_sleep(20) # gives some time to the other person

to answer

telephone.hang_up()

➜ Maksud inti ➝ Menerapkan panggilan telepon SOS - 2 fitur :

  1. Aplikasi mendengarkan SMS yang masuk, jika ada SMS baru
  2. 'SOS call me', panggilan dilakukan ke nomor yang sesuai
  3. Klik 'kirim SOS', SMS dikirim ke kontak darurat Anda dengan 'SOS hubungi saya'
  • Audio

import audio, e32, os, random, time

random.seed(time.time())

dir = u"C:\\Data\\myapp\\wavs\\"

list_wavs=[f for f in os.listdir(dir) if f[-4:]==".wav"]

sounds = [audio.Sound.open(dir+fn) for fn in list_wavs]

for i in range(0, 30):

r_i = int(random.random() * len(sounds))

if sounds[r_i].state() != audio.EOpen:

continue

sounds[r_i].play(1)

e32.ao_sleep(random.random()*2)

for s in sounds: s.close()

➜ Maksud inti : merekam musik pada waktu yang sama;  menggunakan akselerometer sebagai masukan

  • serialisasi sederhana (conf, file data)

import os, os.path

FILE_PATH = "C:/Data/myapp"

user_conf = {} # empty or with default values

def open_config_file():

conf_f = os.path.join(FILE_PATH, "user.conf")

if os.path.exists(conf_f):

s = open(conf_f, 'r').read()

if len(s)>0:

user_conf.update(eval(s))

def write_config_file():

conf_f = os.path.join(FILE_PATH, "user.conf")

open(conf_f, 'w+').write(repr(user_conf))

if __name__=="__main__":

open_config_file()

user_conf['login'] = 'email@gmail.com'

write_config_file()

  • sensor (data sensor log)

import sensor, appuifw, e32

FILENAME = "C:/Data/myapp/sensor_data.txt"

global data, gesture, sensor

def callback_acc(val):

data.append( [val['data_1'], val['data_2'], val['data_3'] ])

def stop_acc():

sensor.disconnect()

f = open(FILENAME, "ab+")

f.write(repr( {'gesture' : gesture, 'data': data } ))

f.write("\n") ; f.close()

def get_gesture_data():

global data, gesture

data = []

gesture = appuifw.query(u"Information about the recorded data", 'text')

sensor.connect(callback_acc)

e32.ao_sleep(2) # get data for 2s

stop_acc()

acc_info = sensor.sensors()['AccSensor']

sensor = sensor.Sensor(acc_info['id'], acc_info['category'])

get_gesture_data()

➜ Maksud inti : memproses data untuk menghubungkan gerakan dan akselerometer

  • Logs

import logs

# easy access to the phone logs

for typ in ['call', 'sms', 'data', 'fax', 'email', 'scheduler']:

data = logs.log_data(typ)

print "\n%s logs: "%typ

if len(data)>0:

print len(data), data[0]

else:

print 0

  • urlib modul Python standar ←

import urllib, appuifw

f = urllib.urlopen("http://www.google.com")

html = f.read()

# post GET data to an online image collection

keyword = appuifw.query(u"Keyword for the image search:", 'text')

keyword = keyword and keyword or 'ship'

params = urllib.urlencode({'f' : 'search', 'txt' : '%s'%keyword, 'w':'1', 'x' :

'0', 'y' : '0'})

f = urllib.urlopen("http://www.sxc.hu/browse.phtml?"+params)

html = f.read()

print "Length of the HTML file ", len(html)

➜ Maksud inti : Simpan html secara lokal, buka di browser (menggunakan Content_handler) ;  Mengurai html

  • ftplib (mengunggah video)modul Python standar ←

import ftplib

fn = "C:\\Data\\myapp\\video01.mp4"

f = open(fn, 'rb')

host = "ftp.blip.tv"

user = "pymobmid"

pwd = "pymid"

ftp = ftplib.FTP(host)

ftp.login(user, pwd)

ftp.storbinary("STOR video01.mp4", f, 1024)

ftp.quit()

f.close()

Catatan : ftplib tidak diinstal oleh bawaan.  Salin ftplib.py ke telepon.

➜ Maksud inti : Mengunggah file Video

  • soket (Bluetooth)

import socket, appuifw

# Send a file to a Bluetooth device

selected_bt = socket.bt_obex_discover()

fn = u"C:\\Data\\contacts_backup.txt"

socket.bt_obex_send_file(selected_bt[0], selected_bt[1].values()[0], fn)

# List of Bluetooth devices

list_bt = socket.bt_discover()

➜ Maksud inti : Buat server Bluetooth

  • soket (inet) →modul Python standar ←

# localserver.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind( ("127.0.0.1", 18000) )

s.listen(1)

conn, addr = s.accept()

while 1:

data = conn.read(1024)

if not data: break

question = eval(data)

conn.send( repr({'result': eval(question['exp'])}))

conn.close()

# Start server with: e32.start_server(u"C:\\Data\\myapp\\localserver.py")

# localclient.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(("127.0.0.1", 18000))

s.send( repr({'exp': '10*80'}))

data = s.read(1024)

print "Result", eval(data)

s.close()

➜ Maksud inti : buat server lebih kuat, tangani lebih banyak perintah

  • sysinfo (phone params)

import sysinfo
info = {'imei' 
: sysinfo.imei(),
'battery.level'
: sysinfo.battery(),
'active.profile'
: sysinfo.active_profile(),
'ring.type'
: sysinfo.ring_type(),
'signal'
: sysinfo.signal_dbm(),
'signal.bars'
: sysinfo.signal_bars(),
'ram.total'
: sysinfo.total_ram(),
'ram.free'
: sysinfo.free_ram(),
# 'ram.max'
: sysinfo.max_ramdrive_size(),
'rom'
: sysinfo.total_rom(),
'space.free'
: sysinfo.free_drivespace(),
'display.pixels'
: sysinfo.display_pixels(),
'display.twips'
: sysinfo.display_twips(),
'sw.version'
: sysinfo.sw_version(),

➜ Maksud inti : Tingkat baterai dan aktivitas baterai

  • _ _builtins_ _ →modul Python standar ←

# get the list of the methods (for objects), or functions available in modules
print dir(__builtins__)
print dir(''), dir([]), dir({})
# call a script:
import os
random_script = os.listdir('C:/Python')[2]
print "We are calling ", random_script
execfile(u'C:/Python/'+random_script)
# local variables are stored in a dict returned by locals()
print locals()
city 
= 'Leuven'
country = 'belgium'
print "I am in %(city)s, in %(country)s"%({'city' : city, 'country': country})
# or simpler:
print "I am in %(city)s, in %(country)s"%locals()

➜ Maksud inti : map, filter, lambda, globals, unicode, hex, chr, int, ...

  • Modul diletakkan disini / skema

e32
# symbian OS functions/class
sysinfo
# system info
appuifw
# GUI framework
graphics
# images, drawing
camera
# to take photos or videos
sensor
# access to the phone sensors
audio
# play mp3, wav, record audio
telephone
# dial, hang up
messaging
# send, receive SMS
inbox
# access to the messaging inbox, sent boxes
location
# cellid location
positioning
# GPS location
contacts
# access to the phone book
logs
# access to the phone's logs
keycapture
# capture global key events
calendar
# access to the calendar

Apa Reaksi Anda?

like

dislike

love

funny

angry

sad

wow