class ProducerConsumer(unittest.TestCase): '''Basic test case for producer-consumer QThread''' def setUp(self): #Create fixtures self.app = QCoreApplication([]) def tearDown(self): #Destroy fixtures del self.app def finishCb(self): #Quits the application self.app.exit(0) def testProdCon(self): #QThread producer-consumer example bucket = Bucket() prod = Producer(bucket) cons = Consumer(bucket) prod.start() cons.start() QObject.connect(prod, SIGNAL('finished()'), self.finishCb) QObject.connect(cons, SIGNAL('finished()'), self.finishCb) self.app.exec_() prod.wait() cons.wait() self.assertEqual(prod.production_list, cons.consumption_list)
def testEmitOutsideThread(self): global thread_run app = QCoreApplication([]) source = Source() thread = ThreadJustConnects(source) QObject.connect(thread, SIGNAL('finished()'), lambda: app.exit(0)) thread.start() while not thread_run: pass source.emit_sig() app.exec_() thread.wait() self.assert_(thread.target.called)
class StatusNetHandler(dbus.service.Object): def __init__(self): dbus_main_loop = dbus.glib.DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus(dbus_main_loop) bus_name = dbus.service.BusName("com.mikeasoft.statusnet", bus=session_bus) dbus.service.Object.__init__(self, object_path="/synchronize", bus_name=bus_name) self.app = QCoreApplication(sys.argv) signal.signal(signal.SIGINT, signal.SIG_DFL) self.client = gconf.client_get_default() self.api_path = self.client.get_string( '/apps/ControlPanel/Statusnet/api_path') self.latest = self.client.get_int( '/apps/ControlPanel/Statusnet/latest') self.eventService = EventFeedService('statusnet', 'StatusNet') self.eventService.local_name = "com.mikeasoft.statusnet.eventcallback" self.eventService.DEFAULT_INTF = "com.mikeasoft.statusnet.eventcallback" if not self.api_path: return self.cacheDir = QDesktopServices.storageLocation( QDesktopServices.CacheLocation) if not os.path.exists(self.cacheDir): os.mkdir(self.cacheDir) sys.exit(self.app.exec_()) def login(self): if self.api_path in oauth_consumer_keys: key = oauth_consumer_keys[self.api_path] secret = oauth_consumer_secrets[self.api_path] oauth_token = self.client.get_string( "/apps/ControlPanel/Statusnet/oauth_token") oauth_token_secret = self.client.get_string( "/apps/ControlPanel/Statusnet/oauth_token_secret") self.statusNet = StatusNet(self.api_path, auth_type="oauth", consumer_key=key, consumer_secret=secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) else: username = self.client.get_string( '/apps/ControlPanel/Statusnet/username') password = self.client.get_string( '/apps/ControlPanel/Statusnet/password') self.statusNet = StatusNet(self.api_path, username, password) @dbus.service.method("com.mikeasoft.statusnet") def refresh(self): thread = threading.Thread(target=self.updateTimeline) thread.start() def updateTimeline(self): self.login() statuses = self.statusNet.statuses_home_timeline(self.latest) if len(statuses) > 0: self.client.set_int('/apps/ControlPanel/Statusnet/latest', statuses[0]['id']) for status in statuses: self.showStatus(status) self.app.exit() def showStatus(self, status): if status['text'] == None: # HTML only message return icon = statusnetutils.getAvatar(status['user']['profile_image_url'], self.cacheDir) title = "%s on StatusNet" % status['user']['name'] creationtime = statusnetutils.getTime(status['created_at']) item = EventFeedItem(icon, title, creationtime) item.set_body(status['text']) item.set_action_data(status['id'], status['statusnet_conversation_id']) self.eventService.add_item(item)
class QtMobility(PositionSource): def __init__(self, location): PositionSource.__init__(self, location) self.qtApplication = None # used for headless location support # connect to QT Mobility position source self.source = None # self.satelliteSource = QGeoSatelliteInfoSource.createDefaultSource(None) self.satsInViewCount = None self.satsInUseCount = None # if self.satelliteSource is not None: ## self.satelliteSource.satellitesInViewUpdated.connect(self._satsInViewUpdateCB) ## self.satelliteSource.satellitesInViewUpdated.connect(self._satsInUseUpdateCB) # log.info("location Qt Mobility: satellite info source created") # else: # log.error("location Qt Mobility: satellite info source creation failed") def start(self, startMainLoop=False): if startMainLoop: from PySide.QtCore import QCoreApplication self.qtApplication = QCoreApplication(sys.argv) # we import QGeoPositionInfoSource after the Qt Application is # created to get rid of the: # " # QDBusConnection: system D-Bus connection created before QCoreApplication. Application may misbehave. # QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave. # " # warnings from QtMobility.Location import QGeoPositionInfoSource self.source = QGeoPositionInfoSource.createDefaultSource(None) if self.source is not None: self.source.positionUpdated.connect(self._positionUpdateCB) log.info("position source created") # TODO: custom interval setting self.source.setUpdateInterval(1000) self.source.startUpdates() log.info("started") # only start the mainloop if the source was created successfully, # otherwise it would never end as the signal provided by the source, # that stops the main loop, would never be triggered if startMainLoop: log.info("starting headless mainloop") self.qtApplication.exec_() else: log.error("source creation failed") # if self.satelliteSource: # log.info(self.satelliteSource.availableSources()) # self.satelliteSource.startUpdates() # log.info("sat source started") def stop(self): log.info("location qt mobility: stopping") if self.source: self.source.stopUpdates() log.info("stopped") if self.qtApplication: log.info("stopping headless mainloop") self.qtApplication.exit() # if self.satelliteSource: # self.satelliteSource.stopUpdates() # log.info("sat source stopped") def canSetUpdateInterval(self): return True def setUpdateInterval(self, interval): if self.source: self.source.setUpdateInterval(interval) def getFix(self): return self.fix # def _satsInViewUpdateCB(self, satellites=None): # """update the count of visible GPS satellites""" # if satellites is not None: # self.satsInViewCount = len(satellites) # # def _satsInUseUpdateCB(self, satellites=None): # """update the count of GPS satellites in use to # determine the current position""" # if satellites is not None: # self.satsInUseCount = len(satellites) def _positionUpdateCB(self, update): direction = update.attribute(update.Direction) speed = update.attribute(update.GroundSpeed) mode = 3 # 3d fix if update.coordinate().isValid(): if update.coordinate().CoordinateType == update.coordinate( ).Coordinate2D: mode = 2 # 2D fix else: mode = 0 # no fix if direction == -1.0: direction = 0 if speed == -1.0: speed = 0 fix = Fix( (update.coordinate().latitude(), update.coordinate().longitude()), update.coordinate().altitude(), direction, speed, mode=mode, magnetic_variation=update.attribute(update.MagneticVariation), sats=self.satsInViewCount, sats_in_use=self.satsInUseCount, horizontal_accuracy=update.attribute(update.HorizontalAccuracy), vertical_accuracy=update.attribute(update.VerticalAccuracy)) # print debug message if enabled # self.debug = True if self.debug: log.debug("Qt-Mobility POS DEBUG") log.debug("%s, %s", update.coordinate().latitude(), update.coordinate().longitude()) log.debug(update) # trigger update in the location module self.location.updatePosition(fix) self.fix = fix
class StatusNetHandler(dbus.service.Object): def __init__(self): dbus_main_loop = dbus.glib.DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus(dbus_main_loop) bus_name = dbus.service.BusName("com.mikeasoft.statusnet", bus=session_bus) dbus.service.Object.__init__(self, object_path="/synchronize", bus_name=bus_name) self.app = QCoreApplication(sys.argv) signal.signal(signal.SIGINT, signal.SIG_DFL) self.client = gconf.client_get_default() self.api_path = self.client.get_string('/apps/ControlPanel/Statusnet/api_path') self.latest = self.client.get_int('/apps/ControlPanel/Statusnet/latest') self.eventService = EventFeedService('statusnet', 'StatusNet') self.eventService.local_name = "com.mikeasoft.statusnet.eventcallback" self.eventService.DEFAULT_INTF = "com.mikeasoft.statusnet.eventcallback" if not self.api_path: return self.cacheDir = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) if not os.path.exists(self.cacheDir): os.mkdir(self.cacheDir) sys.exit(self.app.exec_()) def login(self): if self.api_path in oauth_consumer_keys: key = oauth_consumer_keys[self.api_path] secret = oauth_consumer_secrets[self.api_path] oauth_token = self.client.get_string("/apps/ControlPanel/Statusnet/oauth_token") oauth_token_secret = self.client.get_string("/apps/ControlPanel/Statusnet/oauth_token_secret") self.statusNet = StatusNet(self.api_path, auth_type="oauth", consumer_key=key, consumer_secret=secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) else: username = self.client.get_string('/apps/ControlPanel/Statusnet/username') password = self.client.get_string('/apps/ControlPanel/Statusnet/password') self.statusNet = StatusNet(self.api_path, username, password) @dbus.service.method("com.mikeasoft.statusnet") def refresh(self): thread = threading.Thread(target=self.updateTimeline) thread.start() def updateTimeline(self): self.login() statuses = self.statusNet.statuses_home_timeline(self.latest) if len(statuses) > 0: self.client.set_int('/apps/ControlPanel/Statusnet/latest', statuses[0]['id']) for status in statuses: self.showStatus(status) self.app.exit() def showStatus(self, status): if status['text'] == None: # HTML only message return icon = statusnetutils.getAvatar(status['user']['profile_image_url'], self.cacheDir) title = "%s on StatusNet" % status['user']['name'] creationtime = statusnetutils.getTime(status['created_at']) item = EventFeedItem(icon, title, creationtime) item.set_body(status['text']) item.set_action_data(status['id'], status['statusnet_conversation_id']) self.eventService.add_item(item)
class QtMobility(PositionSource): def __init__(self, location): PositionSource.__init__(self, location) self.qtApplication = None # used for headless location support # connect to QT Mobility position source self.source = None # self.satelliteSource = QGeoSatelliteInfoSource.createDefaultSource(None) self.satsInViewCount = None self.satsInUseCount = None # if self.satelliteSource is not None: ## self.satelliteSource.satellitesInViewUpdated.connect(self._satsInViewUpdateCB) ## self.satelliteSource.satellitesInViewUpdated.connect(self._satsInUseUpdateCB) # print("location Qt Mobility: satellite info source created") # else: # print("location Qt Mobility: satellite info source creation failed") def start(self, startMainLoop=False): if startMainLoop: from PySide.QtCore import QCoreApplication self.qtApplication = QCoreApplication(sys.argv) # we import QGeoPositionInfoSource after the Qt Application is # created to get rid of the: # " # QDBusConnection: system D-Bus connection created before QCoreApplication. Application may misbehave. # QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave. # " # warnings from QtMobility.Location import QGeoPositionInfoSource self.source = QGeoPositionInfoSource.createDefaultSource(None) if self.source is not None: self.source.positionUpdated.connect(self._positionUpdateCB) print("location Qt Mobility: position source created") # TODO: custom interval setting self.source.setUpdateInterval(1000) self.source.startUpdates() print("location qt mobility: started") # only start the mainloop if the source was created successfully, # otherwise it would never end as the signal provided by the source, # that stops the main lopp, would never be triggered if startMainLoop: print("location qt mobility: starting headless mainloop") self.qtApplication.exec_() else: print("location Qt Mobility: source creation failed") # if self.satelliteSource: # print(self.satelliteSource.availableSources()) # self.satelliteSource.startUpdates() # print("location qt mobility: sat source started") def stop(self): print("location qt mobility: stopping") if self.source: self.source.stopUpdates() print("location qt mobility: stopped") if self.qtApplication: print("location qt mobility: stopping headless mainloop") self.qtApplication.exit() # if self.satelliteSource: # self.satelliteSource.stopUpdates() # print("location qt mobility: sat source stopped") def canSetUpdateInterval(self): return True def setUpdateInterval(self, interval): if self.source: self.source.setUpdateInterval(interval) def getFix(self): return self.fix # def _satsInViewUpdateCB(self, satellites=None): # """update the count of visible GPS satellites""" # if satellites is not None: # self.satsInViewCount = len(satellites) # # def _satsInUseUpdateCB(self, satellites=None): # """update the count of GPS satellites in use to # determine the current position""" # if satellites is not None: # self.satsInUseCount = len(satellites) def _positionUpdateCB(self, update): direction = update.attribute(update.Direction) speed = update.attribute(update.GroundSpeed) mode = 3 # 3d fix if update.coordinate().isValid(): if update.coordinate().CoordinateType == update.coordinate().Coordinate2D: mode = 2 # 2D fix else: mode = 0 # no fix if direction == -1.0: direction = 0 if speed == -1.0: speed = 0 fix = Fix((update.coordinate().latitude(), update.coordinate().longitude()), update.coordinate().altitude(), direction, speed, mode=mode, magnetic_variation=update.attribute(update.MagneticVariation), sats=self.satsInViewCount, sats_in_use=self.satsInUseCount, horizontal_accuracy=update.attribute(update.HorizontalAccuracy), vertical_accuracy=update.attribute(update.VerticalAccuracy) ) # print debug message if enabled # self.debug = True if self.debug: print("Qt-Mobility POS DEBUG") print("%s, %s" % (update.coordinate().latitude(), update.coordinate().longitude())) print(update) # trigger update in the location module self.location.updatePosition(fix) self.fix = fix