meta data for this page
Shared Python Code
This is our own shared code page. Here you can/should add ready-made, good and working code snippets for other to use. It is highly recommended to share stuff, AS IT MAKES EVERYONE'S LIFE EASIER. No need to invent the wheel twice.
So, add the codes underneath. You can copy the template underneath and just add to the line:
Tutorial for PyGtk
http://www.pygtk.org/pygtk2tutorial/
though not every function in pygtk library does work in maemo as developer were too lazy and didn't import them. like no scrollbar or slidebar exist in maemo.
some examples
- examples.py
def main(self): # place where fin info about pygtk http://www.pygtk.org/pygtk2tutorial/ win = hildon.StackableWindow() # Create and pack labels vbox = gtk.VBox(False, 10) hbox = gtk.HBox(False, 10) #interface.. buttons, labels ,... etc labelHeader = gtk.Label("MeHear") labelSubHeader = gtk.Label("voice amplifier") # buttonGTK1 = gtk.Button("Record") # buttonGTK1.connect("clicked", self.record_button_clicked, labelSubHeader) buttonGTK = gtk.ToggleButton("AMPlify") buttonGTK.connect("clicked", self.amplify_button_clicked, labelSubHeader) #a= gtk.CheckButton("check button 1") #hbox.pack_start(a, True, True, 0) #b= gtk.ToggleButton("check button 1") #hbox.pack_start(b, True, True, 0) #c = gtk.RadioButton(None, "radio button1") #hbox.pack_start(c, True, True, 0) #adjus = gtk.Adjustment(value=60, lower=0, upper=100, step_incr=1, page_incr=0, page_size=0) #d = gtk.SpinButton(adjustment= adjus, climb_rate=0.1, digits=5) #hbox.pack_start(d, True, True, 0) #hscrollbar = gtk.HSscrollbar(adjustment) #http://www.pygtk.org/pygtk2tutorial/sec-ComboWidget.html combo = gtk.Combo() combo.entry.set_text("text") slist = [ "String 1", "String 2", "String 3", "String 4" ] combo.set_popdown_strings(slist) hbox.pack_start(combo, True, True, 0) hbox.pack_start(buttonGTK, True, True, 0) vbox.pack_start(labelHeader, True, True, 0) vbox.pack_start(labelSubHeader, True, True, 0) vbox.pack_start(hbox, True, True, 0) # Add label's box to window win.add(vbox) win.connect("delete_event", gtk.main_quit) win.show_all() gtk.main()
Software playtrought
- Group: Esa-Petri and Hilmi
- Description: program to play voice from mic
- MeHear.py
from optparse import OptionParser from time import sleep import sys, os import pygtk, gtk, gobject import dbus import gst import pygst import sys import time import gtk import hildon class Record(): mic = None def __init__(self, sink): """ @summary: The Constructor class, that searches for the microphone on initialization """ bus = dbus.SystemBus() hal_manager = bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/Manager") hal_manager = dbus.Interface(hal_manager, "org.freedesktop.Hal.Manager") print hal_manager devices = hal_manager.FindDeviceStringMatch("alsa.type", "capture") identifiers = [] for dev in devices: device = bus.get_object("org.freedesktop.Hal", dev) card = device.GetAllProperties(dbus_interface="org.freedesktop.Hal.Device") if card["alsa.card"] not in identifiers: print "%d. %s" % (card["alsa.card"], card["alsa.card_id"]) identifiers.append(card["alsa.card"]) self.mic = identifiers[0] """ @attention: this is important it initializes softfare playtrought (audioconvert is not nesesity) @summary: takes stream from mic to autosink """ self.pipeline = gst.parse_launch("""alsasrc device=hw:%d ! audioconvert ! autoaudiosink location=%s""" % (self.mic, sink)) def rec(self): """ @summary: sets recording on """ self.pipeline.set_state(gst.STATE_PLAYING) print "" print "recording started" def stoprec(self): """ @summary: sets recording off """ self.pipeline.set_state(gst.STATE_NULL) print "" print "recording, stoped" class Prosesor(): """ @summary: Takes care of prossesing the sound """ def __init__(self): volume=0 gain =0 CutThereshold=0 def proses(self,volume, gain, comp): a=1 class player(): def __init__(self): """ @summary: player part """ self.player = gst.element_factory_make("playbin2", "player") fakesink = gst.element_factory_make("fakesink", "fakesink") self.player.set_property("video-sink", fakesink) audiosink = gst.element_factory_make("autoaudiosink", "audio-output") self.recorder=Record(audiosink) """ @attention: next links raw data from mic to player mekanism of gstreamer """ self.player.set_property("audio-sink",audiosink) self.playmode = True bus = self.player.get_bus() bus.add_signal_watch() bus.connect("message", self.on_message) def on_message(self, bus, message): t = message.type if t == gst.MESSAGE_EOS: self.player.set_state(gst.STATE_NULL) self.playmode = False elif t == gst.MESSAGE_ERROR: self.player.set_state(gst.STATE_NULL) err, debug = message.parse_error() print "Error: %s" % err, debug self.playmode = False def play(self): self.recorder.rec() self.player.set_state(gst.STATE_PLAYING) print "playing" def stop(self): #self.playmode = False self.player.set_state(gst.STATE_NULL) self.recorder.stoprec() print "stoped" class MeHear(hildon.Program): def __init__(self): self.pl= player() def amplify_button_clicked(self,button, label): buttontext = button.get_label() text = buttontext if text == "AMPlify" : label.set_text("") button.set_label("Stop") self.pl.play() print "play button pressed" if text == "Stop" : label.set_text("Stopped") button.set_label("AMPlify") self.pl.stop() print "stop button pressed" def main(self): win = hildon.StackableWindow() # Create and pack labels vbox = gtk.VBox(False, 10) hbox = gtk.HBox(False, 10) #interface.. buttons, labels ,... etc labelHeader = gtk.Label("Application header") labelSubHeader = gtk.Label("-") # buttonGTK1 = gtk.Button("Record") # buttonGTK1.connect("clicked", self.record_button_clicked, labelSubHeader) buttonGTK = gtk.Button("AMPlify") buttonGTK.connect("clicked", self.amplify_button_clicked, labelSubHeader) # hbox.pack_start(buttonGTK1, True, True, 0) hbox.pack_start(buttonGTK, True, True, 0) vbox.pack_start(labelHeader, True, True, 0) vbox.pack_start(labelSubHeader, True, True, 0) vbox.pack_start(hbox, True, True, 0) # Add label's box to window win.add(vbox) win.connect("delete_event", gtk.main_quit) win.show_all() gtk.main() if __name__ == "__main__": app = MeHear() app.main()
Sending SMS
- Group: Japskua
- Description: Sends a text message to a given number
- sms.py
import dbus ############################################################################################ """ HERE IS THE VERY EVIL PART OF THE CODE! DON'T TOUCH! WILL PROBABLY MESS THE PHONE!!!!""" def octify(str): ''' Returns a list of octet bytes representing each char of the input str. ''' bytes = map(ord, str) bitsconsumed = 0 referencebit = 7 octets = [] while len(bytes): byte = bytes.pop(0) byte = byte >> bitsconsumed try: nextbyte = bytes[0] bitstocopy = (nextbyte & (0xff >> referencebit)) << referencebit octet = (byte | bitstocopy) except: octet = (byte | 0x00) if bitsconsumed != 7: octets.append(byte | bitstocopy) bitsconsumed += 1 referencebit -= 1 else: bitsconsumed = 0 referencebit = 7 return octets def semi_octify(str): ''' Expects a string containing two digits. Returns an octet - first nibble in the octect is the first digit and the second nibble represents the second digit. ''' try: digit_1 = int(str[0]) digit_2 = int(str[1]) octet = (digit_2 << 4) | digit_1 except: octet = (1 << 4) | digit_1 return octet def deoctify(arr): referencebit = 1 doctect = [] bnext = 0x00 for i in arr: bcurr = ((i & (0xff >> referencebit)) << referencebit) >> 1 bcurr = bcurr | bnext if referencebit != 7: doctect.append( bcurr ) bnext = (i & (0xff << (8 - referencebit)) ) >> 8 - referencebit referencebit += 1 else: doctect.append( bcurr ) bnext = (i & (0xff << (8 - referencebit)) ) >> 8 - referencebit doctect.append( bnext ) bnext = 0x00 referencebit = 1 return ''.join([chr(i) for i in doctect]) def createPDUmessage(number, msg): ''' Returns a list of bytes to represent a valid PDU message ''' numlength = len(number) if (numlength % 2) == 0: rangelength = numlength else: number = number + 'F' rangelength = len(number) octifiednumber = [ semi_octify(number[i:i+2]) for i in range(0,rangelength,2) ] octifiedmsg = octify(msg) HEADER = 1 FIRSTOCTETOFSMSDELIVERMSG = 10 ADDR_TYPE = 129 #unknown format number_length = len(number) msg_length = len(msg) pdu_message = [HEADER, FIRSTOCTETOFSMSDELIVERMSG, number_length, ADDR_TYPE] pdu_message.extend(octifiednumber) pdu_message.append(0) pdu_message.append(0) pdu_message.append(msg_length) pdu_message.extend(octifiedmsg) return pdu_message ################################################### """ VERY EVIL PART OVER, NOW TO THE NORMAL PART """ class Messager(object): """ @summary: This is the Messager class, that handles sending SMS messages """ def __init__(self): """ @summary: The Constructor, initializes the dbus """ self.bus = dbus.SystemBus() self.smsobject = self.bus.get_object('com.nokia.phone.SMS', '/com/nokia/phone/SMS/ba212ae1') self.smsiface = dbus.Interface(self.smsobject, 'com.nokia.csd.SMS.Outgoing') def Send(self, message, number): """ @summary: The Send function, that actually sends the given message @param message: The message to be sent @type message: String @param number: The number to send the message to (can be with country code also) @type number: String """ arr = dbus.Array(createPDUmessage(number.replace('+', '00'), message)) msg = dbus.Array([arr]) self.smsiface.Send(msg, '') if __name__ == "__main__": messager = Messager() messager.Send("Hello man, testing", "0400558160")
Making Phone Calls
- Group: Japskua
- Description: Makes a phone call to given number
- call.py
''' Created on Aug 18, 2011 @author: Japskua ''' import dbus class Caller(object): """ @summary: This is the Caller class that makes the phone calls """ def __init__(self): """ @summary: The Constructor """ # Do nothing self.bus = dbus.SystemBus() self.csd_call = dbus.Interface(self.bus.get_object("com.nokia.csd", "/com/nokia/csd/call"), "com.nokia.csd.Call") def Call(self, number): """ @summary: The function to Call to a given number @param number: The number to call to @type number: String """ self.csd_call.CreateWith(str(number), dbus.UInt32(0)) if __name__ == '__main__': caller = Caller() caller.Call("0400558160")
Creating Buttons with Images
- Group: Japskua
- Description: How to create buttons with functions, data and images
- * Creating multiple buttons
- * Adding functions to buttons
- * Adding images to buttons
- window_with_buttons.py
# First import all the neccesary libraries import gtk import hildon # This is an example callback function that can be put to a button and used to receive stuff # All buttons print hello world, but if it has data included, will print that aswell def hello(widget, data): print "Hello World!" if data != None: print "Data: ", data def main(): # Get an instance of HildonProgram. It is an object used to represent an # application running in the Hildon framework. program = hildon.Program.get_instance() # create a new hildon window window = hildon.Window() # Registers a window as belonging to the program program.add_window(window) # When the window is given the "delete_event" signal (this is given by the # window manager, usually by the "close" option, or on the titlebar), we # ask it to call the delete_event () function as defined above. The data # passed to the callback function is None and is ignored in the callback # function. window.connect("delete_event", gtk.main_quit, None) # Create three different buttons: 1st with no data, 2nd with data and 3rd as an Image button1 = hildon.Button(gtk.HILDON_SIZE_AUTO, hildon.BUTTON_ARRANGEMENT_VERTICAL, "First Button, no data") button2 = hildon.Button(gtk.HILDON_SIZE_AUTO, hildon.BUTTON_ARRANGEMENT_VERTICAL, "Second Button, with data") button3 = hildon.Button(gtk.HILDON_SIZE_AUTO, hildon.BUTTON_ARRANGEMENT_VERTICAL, "") # When the button is given the "clicked" signal, we ask it to call the # hello () function as defined above. If the data passed to the callback # function is None and is ignored in the callback function. button1.connect("clicked", hello, None) button2.connect("clicked", hello, "a lot of numbers here") button3.connect("clicked", hello, None) # Set the button to have an image # First we need to load the image from file image = gtk.image_new_from_file("preview.jpg") # and then to set it to the button button3.set_image(image) # Now we create a button box, which is an container that can have multiple buttons in it # The one used here is Vertical box, that places the buttons on top of each other, but # you could create HButtonBox() that is a horizontal box, that puts buttons next to # each other buttonBox = gtk.VButtonBox() # Here the layour is defined to spread the buttons evenly, options to use here are # gtk.BUTTONBOX_SPREAD, gtk.BUTTONBOX_EDGE, gtk.BUTTONBOX_START and gtk.BUTTONBOX_END buttonBox.set_layout(gtk.BUTTONBOX_SPREAD) # And then finally add all the buttons to the buttonBox buttonBox.add(button1) buttonBox.add(button2) buttonBox.add(button3) # And then the buttonBox to the window window.add(buttonBox) # The final step is to display this newly created widget and all widgets it # contains. window.show_all() # All GTK+ applications must have a gtk_main(). Control ends here and waits # for an event to occur (like a key press or mouse event). gtk.main() if __name__ == "__main__": main()
Creating buttons
- Group: Group 2
- Description: It creates 2 buttons and 2 labels, pressing the buttons change the text of one of the labels.
- buttons.py
''' Created on Aug 18, 2011 @author: Group 2 @summary: Button example ''' import sys import gtk import hildon def menu_button_clicked(button, label): buttontext = button.get_label() text = "Last option selected:\n%s" % buttontext label.set_text(text) def main(): win = hildon.StackableWindow() # Create and pack labels vbox = gtk.VBox(False, 10) hbox = gtk.HBox(False, 10) #interface.. buttons, labels ,... etc labelHeader = gtk.Label("Application header") labelSubHeader = gtk.Label("-") buttonGTK1 = gtk.Button("None") buttonGTK1.connect("clicked", menu_button_clicked, labelSubHeader) buttonGTK2 = gtk.Button("Hello") buttonGTK2.connect("clicked", menu_button_clicked, labelSubHeader) hbox.pack_start(buttonGTK1, True, True, 0) hbox.pack_start(buttonGTK2, True, True, 0) vbox.pack_start(labelHeader, True, True, 0) vbox.pack_start(labelSubHeader, True, True, 0) vbox.pack_start(hbox, True, True, 0) # Add label's box to window win.add(vbox) win.connect("delete_event", gtk.main_quit) win.show_all() gtk.main() if __name__ == "__main__": main()