Create DBus signal dynamically in python - python

I've read some topics related to dynamically create python methods, and I followed their instructions, but it does not work. I do not know if it is because I use decorator # or something else.
The code is here, very simple.
When running this code, no error occurred, but when I use D-feet(A tool to check dbus informations), I could not find new signals I created.
#!/usr/bin/python
import dbus
import dbus.service
import dbus.glib
import gobject
from dbus.mainloop.glib import DBusGMainLoop
import psutil
class EventServer(dbus.service.Object):
i = 0
#dbus.service.signal('com.github.bxshi.event')
def singal_example(self,msg):
""" example of singals
"""
print msg
def __init__(self):
bus_name = dbus.service.BusName('com.github.bxshi.event', bus=dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/com/github/bxshi/event')
def create(self):
self.i +=1
setattr(self.__class__, 'signal_'+str(self.i), self.singal_example)
if __name__ == "__main__":
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
eventserver = EventServer()
gobject.timeout_add(1000,eventserver.create)
loop = gobject.MainLoop()
loop.run()

you have a typo: singal_example instead of signal_example
in your create-method you call setattr on the class. I don't know what you're trying to do, but you should simply emit the signal
This is the fixed example:
#!/usr/bin/python
import dbus
import dbus.service
import dbus.glib
import gobject
from dbus.mainloop.glib import DBusGMainLoop
#import psutil
class EventServer(dbus.service.Object):
i = 0
#dbus.service.signal('com.github.bxshi.event')
def signal_example(self,msg):
""" example of singals
"""
print msg
def __init__(self):
bus_name = dbus.service.BusName('com.github.bxshi.event', bus=dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/com/github/bxshi/event')
def create(self):
self.i +=1
#setattr(self.__class__, 'signal_'+str(self.i), self.singal_example)
self.signal_example('msg: %d' % self.i)
if __name__ == "__main__":
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
eventserver = EventServer()
gobject.timeout_add(1000,eventserver.create)
loop = gobject.MainLoop()
loop.run()
After that you can connect to the signal:
# ...
bus = dbus.Bus()
service=bus.get_object('com.github.bxshi.event', '/com/github/bxshi/event')
service.connect_to_signal("signal_example", listener)
# ...

Related

Threading python not working

These are my first steps with python and desktop programming. I worked with web all my life and now I need to do threading.
I tried work with tkinter, pyqt and now gtk(father of tkinter) with glade xml.
I tried different modules because I was failing every time on the same problem. The interface has an infinite loop so I read a little bit about it on Google and its my first time working with python, desktop and threading
so here's my code could someone say what is wrong and why?
# -*- coding: utf-8 -*-
#Parallelism modulos
import threading
import Queue
#GUI modulos
import gtk, sys
#webservice modulos
import urllib2, json, urllib
#rfid modulos
import MFRC522
import signal
#GPIO modulos
import RPi.GPIO as GPIO
#sleep modulos
from time import sleep
#database modulos
import psycopg2
class Janela(threading.Thread):
def on_window_destroy(self, data=None):
gtk.main_quit()
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
builder = gtk.Builder()
builder.add_from_file("interface.glade")
self.window = builder.get_object("window1")
'''aluno informação'''
self.alunoimage = builder.get_object("alunoimage")
self.label = builder.get_object("nomecrianca")
'''Responsavel informação'''
builder.connect_signals(self)
imagefile = "anderson_caricatura.png"
self.alunoimage.set_from_file(imagefile)
self.label.set_text("Anderson Santana")
self.window.show()
gtk.main()
class RfID():
def __init__(self):
a = "343511711127"
self.read()
def beep(self):
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, False)
sleep(0.05)
GPIO.output(11, True)
sleep(0.05)
GPIO.output(11, False)
sleep(0.05)
GPIO.output(11, True)
def regulariza_cartao(self,cartao):
string = ''.join(str(e) for e in cartao);
return string
def consulta_web_service(self,cartao):
req = urllib2.Request("http://192.168.1.161/ieduca/TheClientRfid.php?cartao="+cartao)
response = urllib2.urlopen(req)
the_page = response.read()
return the_page
def end_read(signal, frame):
MIFAREReader = MFRC522.MFRC522()
global continue_reading
continue_reading = False
print "Ctrl+C captured, ending read."
MIFAREReader.GPIO_CLEEN()
def read(self):
continue_reading = True
MIFAREReader = MFRC522.MFRC522()
while continue_reading:
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
(status,backData) = MIFAREReader.MFRC522_Anticoll()
if status == MIFAREReader.MI_OK:
self.beep()
string = self.regulariza_cartao(backData)
consome = self.consulta_web_service(string)
jsonreaded = json.loads(consome)
print "Tem responsavel? ",jsonreaded['have_responsavel']
print "nome do estudante: ",jsonreaded['estudante_nome']
print "estudante imagem: ",jsonreaded['estudante_imagem']
print "imagem caminho: ",jsonreaded['estudante_caminho']
urllib.urlretrieve("http://192.168.1.161/ieduca/"+jsonreaded['estudante_caminho']+jsonreaded['estudante_imagem'], jsonreaded['estudante_imagem'])
print "baixou a imagem"
queue = Queue.Queue()
print "abriu comunicador"
worker = Janela(queue)
print "instanciou a janela"
worker.start()
print "iniciou a janela"
queue.put('quit')
print "pede pra sair 02"
print "rala!"
def run():
GUI = RfID()
run()
this code seems with what is happening to my code
import threading
from time import sleep
#lets pretend this class is the rfid class and will be the first to run
class RFid(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
i=0
d=True
while d:
print "oi"
i = i+1
print i
if i==10:
t2 = Gtk()#after some conditions in it while other class will run this class is the gtk (window, label, images)obs:no buttons
t2.start()
t2.join()
sleep(5)
del t2
#self.run() (or something or something meaning it)
#for example
##if ctrl+c:
##d = False
class Gtk(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while True:#here on the gtk theres a infinity while never ends but it should close the window after some secs and than back to while of first class
print "ola"
#to resume the rfid will open a window with information of the owner of the rfidcard on scream
#but when the information are opened gtk enter on a infinity loop wainting for a event it will never happen
#when it should close after 5 secs and when other card's owner pass show other window and this forever...
def main():
t1 = RFid()
t1.start()
if __name__ == '__main__':
main()
i hope you understand now

python multiprocessing process count

#coding:utf-8
import sys
import time
import os
import multiprocessing
class Worker(object):
def __init__(self):
self.progress = 0
self.task_info = None
def init(self):
pass
def status(self):
pass
def set_task_info(self, task_info):
self.task_info = task_info
def run(self, worker_status_meta_dict):
print multiprocessing.current_process()
print "process is %d" % self.progress
while self.progress < 5:
self.progress = self.progress +1
worker_status_meta_dict['state'] = 0
worker_status_meta_dict['status'] = "running"
time.sleep(2)
worker_status_meta_dict['state'] = 1
worker_status_meta_dict['status'] = "succeeded"
print "bavscan worker finished..."
if __name__ == "__main__":
worker = Worker()
worker_process_dict = multiprocessing.Manager().dict()
process = multiprocessing.Process(target=Worker.run, args=(worker, worker_process_dict))
process.start()
time.sleep(60)
This is a simple demo for python multiprocess.
The main process invoke the Worker.run method in a subprocess with multiprocessing.Process.
When run it in wondows 7, the main process will lauch two subprocess.
I find the problem in the "Python27\Lib\multiprocessing__init__.py"
def Manager():
'''
Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects.
'''
from multiprocessing.managers import SyncManager
m = SyncManager()
m.start()
return m
m.start() will lauch a subprocess to start the manager.

Python cannot work as dbus server and client in the multi-thread enviroment

I created the dbus server as the following code, named it as server1.py
#!/usr/bin/python2.7
import dbus.service
import dbus.glib
import glib
import gobject
from dbus.mainloop.glib import DBusGMainLoop
class APP_Server(dbus.service.Object):
def __init__(self):
bus = dbus.SessionBus(private = True, mainloop = DBusGMainLoop())
bus_name = dbus.service.BusName('de.test.app1', bus)
dbus.service.Object.__init__(self, bus_name, '/de/test/app1_obj_path')
#dbus.service.method("test.app1.interface",)
def is_ready(self):
return True
def publish_dbus():
loop = glib.MainLoop()
APP_Server()
loop.run()
if __name__ == '__main__':
gobject.threads_init()
dbus.glib.init_threads()
publish_dbus()
And then I want to access dbus service in the server1.py by the following code, named it as server2.py which also will work as a dbus server.
#!/usr/bin/python2.7
import dbus.service
import dbus.glib
import glib
import dbus.mainloop
import gobject
from dbus.mainloop.glib import DBusGMainLoop
from threading import Thread
from time import sleep
class APP_Server(dbus.service.Object):
def __init__(self):
bus = dbus.SessionBus(private = True, mainloop = DBusGMainLoop())
bus_name = dbus.service.BusName('de.test.app3', bus)
dbus.service.Object.__init__(self, bus_name, '/de/test/app3_obj_path')
#dbus.service.method("test.app3.interface",)
def is_ready(self):
return True
def call_dbus():
bus_name = 'de.test.app1'
obj_path = '/de/test/app1_obj_path'
interface_name = 'test.app1.interface'
count = 1
while count < 1000:
proxy_bus = dbus.SessionBus(private = True)
obj = None
try:
obj = proxy_bus.get_object(bus_name, obj_path)
except:
sleep(1)
obj = proxy_bus.get_object(bus_name, obj_path)
ready = obj.get_dbus_method('is_ready', interface_name)
ready(pid_, bin_path)
count += 1
print count
def publish_dbus():
loop = glib.MainLoop()
APP_Server()
loop.run()
if __name__ == '__main__':
gobject.threads_init()
dbus.glib.init_threads()
th1 = Thread(target = publish_dbus)
th1.start()
th2 = Thread(target = call_dbus)
th2.start()
sleep(10000000)
Then after run the server2.py, the application will terminated without finished all the dbus call in the thread "call_dbus".
And if I tried with the follwoing code, only changed the code in server2.py as the following:
FROM:
proxy_bus = dbus.SessionBus(private = True)
TO:
proxy_bus = dbus.SessionBus(private = True, mainloop = dbus.mainloop.NULL_MAIN_LOOP)
Now, there will have many connnections after the thread "callbus" finished by using the tools "d-feet" which can be used as a d-bus debugger to check if the dbus server is ready or if the dbus connection has been established.
If someone can make some suggeston to make it work normally??
What i've noticed is this:
Your bus/object names don't match.
You create a new dbus connection each time in your while loop. Very bad idea, specially seen that you don't close them.
Either move the call out of the loop, or use a shared connection (private=False)
You don't really need an own thread to publish the dbus object, that's what the mainloop is for anyway.
If you run a mainloop in a different thread, make sure you have a way to stop, otherwise kill will be the only way of terminating your program. Or put int in your main thread, then it should at least react to Ctrl-C
The sleep at the end of your program is unnecessary. As long as there are running non-daemon threads around the program won't exit anyway.
Putting all this together, this should work:
#!/usr/bin/python2.7
import dbus.service
import dbus.glib
import glib
import dbus.mainloop
import gobject
from dbus.mainloop.glib import DBusGMainLoop
from threading import Thread
from time import sleep
class APP_Server(dbus.service.Object):
def __init__(self):
bus = dbus.SessionBus(private = True, mainloop = DBusGMainLoop())
bus_name = dbus.service.BusName('de.test.app3', bus)
dbus.service.Object.__init__(self, bus_name, '/de/test/app3_obj_path')
#dbus.service.method("test.app3.interface",)
def is_ready(self):
return True
def call_dbus():
bus_name = 'de.test.app3'
obj_path = '/de/test/app3_obj_path'
interface_name = 'test.app3.interface'
proxy_bus = dbus.SessionBus(private = True)
count = 1
while count < 1000:
obj = None
try:
obj = proxy_bus.get_object(bus_name, obj_path)
except:
sleep(1)
obj = proxy_bus.get_object(bus_name, obj_path)
ready = obj.get_dbus_method('is_ready', interface_name)
#ready(pid_, bin_path)
count += 1
print count
if __name__ == '__main__':
gobject.threads_init()
dbus.glib.init_threads()
loop = glib.MainLoop()
server = APP_Server()
#th1 = Thread(target = publish_dbus)
#th1.start()
th2 = Thread(target = call_dbus)
th2.start()
loop.run()

Thread not working in Storm Cluster

I'm trying to do the following, Start stream listener in a separate thread that will create a queues, Than those queue will be processed later on... however Storm doesn't do anything after thread. It stuck over there.
And my code looks like this:
import os, sys, traceback, random, StringIO, time
import random
from uuid import uuid4
from select import select
from subprocess import Popen,PIPE
import pyinotify
import simplejson, pycurl
import sys, signal
import twitter
import tweepy
import Queue
import threading
try:
import simplejson as json
except ImportError:
import json
import storm
queue = Queue.Queue()
class MyModelParser(tweepy.parsers.ModelParser):
def parse(self, method, payload):
result = super(MyModelParser, self).parse(method, payload)
result._payload = json.loads(payload)
return result
class CustomStreamListener(tweepy.StreamListener):
''' Handles data received from the stream. '''
def __init__(self, api, q):
self.api = api
self.queue = q
self.queue.put('lalala')
def on_status(self, status):
self.queue.put('%s' % status.author.screen_name)
self.queue.task_done()
def on_error(self, status_code):
return True # To continue listening
def on_timeout(self):
return True # To continue listening
class Starter():
def __init__(self,q):
self.queue = q
hashtag = ['justinbieber','snooki','daddy_yankee','MikeTyson','iamdiddy','lala']
auth = self.t_auth()
api = tweepy.API(auth, parser=MyModelParser())
stream = tweepy.streaming.Stream(auth,CustomStreamListener(api,queue))
stream.filter(follow=None, track=hashtag)
def t_auth(self):
consumer_key=""
consumer_secret=""
access_key = ""
access_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
return auth
class TwitterSpout(storm.Spout):
SPOUT_NAME = "TwitterSpout"
queue = queue
def initialize(self, conf, context):
self.pid = os.getpid()
try:
t = threading.Thread(target=Starter(self.queue) )
t.daemon=True
t.start()
except KeyboardInterrupt, e:
self.log('\n\nStopping')
raise
Use pyleus(https://github.com/Yelp/pyleus) and your spout implementation should have next_tuple(self): which should emit the output fields as in the example below;
from pyleus.storm import Spout
class DummySpout(Spout):
OUTPUT_FIELDS = ['sentence', 'name']
def initialize(self):
pass
def next_tuple(self):
self.emit(("This is a sentence.", "spout",))
if __name__ == '__main__':
DummySpout().run()
then write your bolt;
from pyleus.storm import SimpleBolt
class DummyBolt(SimpleBolt):
OUTPUT_FIELDS = ['sentence']
def process_tuple(self, tup):
sentence, name = tup.values
new_sentence = "{0} says, \"{1}\"".format(name, sentence)
self.emit((new_sentence,), anchors=[tup])
if __name__ == '__main__':
DummyBolt().run()
you can also have a look at how i am using it;
https://github.com/Yelp/pyleus/issues/140

Twisted task.loop and pb auth

Learn Twisted. I decided to write a server and client that once a second to share data.
Wrote one implementation, but it seems to me that it is not correct.
# -*- coding: utf-8 -*-
from twisted.spread import pb
from twisted.internet import reactor, task
from twisted.cred import credentials
from win32com.server import factory
class login_send:
def __init__(self):
self.count=0
self.timeout = 1.0
self.factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8800, self.factory)
def testTimeout(self):
self.count+=1
print self.count
def1 = self.factory.login(credentials.UsernamePassword("test1","bb1b"))
def1.addCallbacks(self.good_connected, self.bad_connected)
def1.addCallback(self.send_data)
def1.addErrback(self.disconnect)
if self.count>10:def1.addBoth(self.disconnect)
def start(self):
l = task.LoopingCall(self.testTimeout)
l.start(self.timeout)
reactor.run()
def good_connected(self, perspective):
print 'good login and password', perspective
return perspective
def bad_connected(self, perspective):
print 'bad login or password', perspective
return perspective
def send_data(self, perspective):
print 'send'
return perspective.callRemote("foo", self.count)
def disconnect(self, perspective):
print 'disconnect'
reactor.stop()
if __name__ == "__main__":
st=login_send()
st.start()
Code: if login and password True -> send self.count, if login or password False -> disconnect, if self.count>10 -> disconnect
The first mistake, in my opinion is that I have to login every time.
def1 = self.factory.login(credentials.UsernamePassword("test1", "bb1b"))
How to make one authorization, and continue to send data every second?
simple test server code:
from zope.interface import implements
from twisted.spread import pb
from twisted.cred import checkers, portal
from twisted.internet import reactor
class MyPerspective(pb.Avatar):
def __init__(self, name):
self.name = name
def perspective_foo(self, arg):
print "I am", self.name, "perspective_foo(",arg,") called on", self
return arg
class MyRealm:
implements(portal.IRealm)
def requestAvatar(self, avatarId, mind, *interfaces):
if pb.IPerspective not in interfaces:
print 'qqqq'
raise NotImplementedError
return pb.IPerspective, MyPerspective(avatarId), lambda:None
p = portal.Portal(MyRealm())
c = checkers.InMemoryUsernamePasswordDatabaseDontUse(test1="bbb",
user2="pass2")
p.registerChecker(c)
reactor.listenTCP(8800, pb.PBServerFactory(p))
reactor.run()
I believe this should do the trick.
# Upper case first letter of class name is good policy.
class Login_send:
def __init__(self):
# initialize the state variable to False.
self.connection = False
self.count=0
self.timeout = 1.0
self.factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8800, self.factory)
def testTimeout(self):
self.count+=1
print self.count
# no connection -- create one.
if not self.connection:
self.assign_connection()
# cached connection exists, call send_data manually.
elif self.count > 10:
self.disconnect(self.connection)
else:
#you probably want to send data only if it it should be valid.
self.send_data(self.connection)
def assign_connection(self):
''' Creates and stores a Deffered which represents the connection to
the server. '''
# cache the connection.
self.connection = self.factory.login(
credentials.UsernamePassword("test1","bb1b"))
# add connection callbacks as normal.
self.connection.addCallbacks(
self.good_connected, self.bad_connected)
self.connection.addCallback(self.send_data)
self.connection.addErrback(self.disconnect)
def disconnect(self, perspective):
# be sure to cleanup after yourself!
self.connection = False
print 'disconnect'
reactor.stop()
# the rest of your class goes here.

Categories

Resources