class DataGenerator(QtCore.QObject): newData = QtCore.pyqtSignal(object) def __init__(self, parent=None, sizey=100, rangey=[0, 100], delay=1000): QtCore.QObject.__init__(self) self.parent = parent self.sizey = sizey self.rangey = rangey self.delay = delay self.mutex = QMutex() self.y = [0 for i in range(sizey)] self.run = True def generateData(self): while self.run: try: self.mutex.lock() for i in range(self.sizey): self.y[i] = randint(*self.rangey) self.mutex.unlock() self.newData.emit(self.y) QtCore.QThread.msleep(self.delay) except: pass
class Write(QObject): signal_begin = pyqtSignal(str) def __init__(self, rest): # QObject().__init__(self) self.mutex = QMutex() def WriteCMD(self, command): self.mutex.lock() SensorSerial.write(str.encode(str(command))) readline = SensorSerial.readline().decode('utf-8').strip() self.mutex.unlock() return readline
class Write(QObject): signal_begin = pyqtSignal(str) def __init__(self, rest): QObject().__init__(self) self.mutex = QMutex() def WriteCMD(self, command): self.mutex.lock() print("Command: " + command) BridgeSerial.write(str.encode(command)) readline = BridgeSerial.readline() if command.startswith('RDGRNG '): time.sleep(3) if command.startswith('SCAN '): time.sleep(4) time.sleep(0.1) self.mutex.unlock() return readline
class InfoSocketNotification(QThread): def __init__(self, tray_icon): QThread.__init__(self) self.tray_icon = tray_icon self.mutex = QMutex() def __del__(self): self.wait() def run(self): wss = websocket.create_connection('wss://listen.moe/api/v2/socket') while True: self.mutex.lock() if not self.tray_icon.isPlaying: self.tray_icon.notificationWaitCondition.wait(self.mutex) data = wss.recv() if data != '': info = json.loads(data) self.tray_icon.new_song_notification_sent.emit(info) self.mutex.unlock()
class Scheduler(QObject): INTERVAL = 1 # minutes delete_old_news = pyqtSignal(object) start_recipe_fetch = pyqtSignal(object) def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.no_internet_msg = _('Cannot download news as no internet connection ' 'is active') self.no_internet_dialog = d = error_dialog(self._parent, self.no_internet_msg, _('No internet connection'), show_copy_button=False) d.setModal(False) self.recipe_model = RecipeModel() self.db = db self.lock = QMutex(QMutex.Recursive) self.download_queue = set([]) self.news_menu = QMenu() self.news_icon = QIcon(I('news.png')) self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self) self.news_menu.addAction(self.scheduler_action) self.scheduler_action.triggered[bool].connect(self.show_dialog) self.cac = QAction(QIcon(I('user_profile.png')), _('Add a custom news source'), self) self.cac.triggered[bool].connect(self.customize_feeds) self.news_menu.addAction(self.cac) self.news_menu.addSeparator() self.all_action = self.news_menu.addAction( _('Download all scheduled news sources'), self.download_all_scheduled) self.timer = QTimer(self) self.timer.start(int(self.INTERVAL * 60 * 1000)) self.timer.timeout.connect(self.check) self.oldest = gconf['oldest_news'] QTimer.singleShot(5 * 1000, self.oldest_check) def database_changed(self, db): self.db = db def oldest_check(self): if self.oldest > 0: delta = timedelta(days=self.oldest) try: ids = list(self.db.tags_older_than(_('News'), delta, must_have_authors=['calibre'])) except: # Happens if library is being switched ids = [] if ids: if ids: self.delete_old_news.emit(ids) QTimer.singleShot(60 * 60 * 1000, self.oldest_check) def show_dialog(self, *args): self.lock.lock() try: d = SchedulerDialog(self.recipe_model) d.download.connect(self.download_clicked) d.exec_() gconf['oldest_news'] = self.oldest = d.old_news.value() d.break_cycles() finally: self.lock.unlock() def customize_feeds(self, *args): from calibre.gui2.dialogs.user_profiles import UserProfiles d = UserProfiles(self._parent, self.recipe_model) try: d.exec_() d.break_cycles() finally: d.deleteLater() def do_download(self, urn): self.lock.lock() try: account_info = self.recipe_model.get_account_info(urn) customize_info = self.recipe_model.get_customize_info(urn) recipe = self.recipe_model.recipe_from_urn(urn) un = pw = None if account_info is not None: un, pw = account_info add_title_tag, custom_tags, keep_issues = customize_info script = self.recipe_model.get_recipe(urn) pt = PersistentTemporaryFile('_builtin.recipe') pt.write(script) pt.close() arg = { 'username': un, 'password': pw, 'add_title_tag':add_title_tag, 'custom_tags':custom_tags, 'recipe':pt.name, 'title':recipe.get('title',''), 'urn':urn, 'keep_issues':keep_issues } self.download_queue.add(urn) self.start_recipe_fetch.emit(arg) finally: self.lock.unlock() def recipe_downloaded(self, arg): self.lock.lock() try: self.recipe_model.update_last_downloaded(arg['urn']) self.download_queue.remove(arg['urn']) finally: self.lock.unlock() def recipe_download_failed(self, arg): self.lock.lock() try: self.recipe_model.update_last_downloaded(arg['urn']) self.download_queue.remove(arg['urn']) finally: self.lock.unlock() def download_clicked(self, urn): if urn is not None: return self.download(urn) for urn in self.recipe_model.scheduled_urns(): if not self.download(urn): break def download_all_scheduled(self): self.download_clicked(None) def has_internet_connection(self): if not internet_connected(): if not self.internet_connection_failed: self.internet_connection_failed = True if self._parent.is_minimized_to_tray: self._parent.status_bar.show_message(self.no_internet_msg, 5000) elif not self.no_internet_dialog.isVisible(): self.no_internet_dialog.show() return False self.internet_connection_failed = False if self.no_internet_dialog.isVisible(): self.no_internet_dialog.hide() return True def download(self, urn): self.lock.lock() if not self.has_internet_connection(): return False doit = urn not in self.download_queue self.lock.unlock() if doit: self.do_download(urn) return True def check(self): recipes = self.recipe_model.get_to_be_downloaded_recipes() for urn in recipes: if not self.download(urn): # No internet connection, we will try again in a minute break
class Scheduler(QObject): INTERVAL = 1 # minutes delete_old_news = pyqtSignal(object) start_recipe_fetch = pyqtSignal(object) def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.no_internet_msg = _('Cannot download news as no internet connection ' 'is active') self.no_internet_dialog = d = error_dialog(self._parent, self.no_internet_msg, _('No internet connection'), show_copy_button=False) d.setModal(False) self.recipe_model = RecipeModel() self.db = db self.lock = QMutex(QMutex.Recursive) self.download_queue = set() self.news_menu = QMenu() self.news_icon = QIcon(I('news.png')) self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self) self.news_menu.addAction(self.scheduler_action) self.scheduler_action.triggered[bool].connect(self.show_dialog) self.cac = QAction(QIcon(I('user_profile.png')), _('Add or edit a custom news source'), self) self.cac.triggered[bool].connect(self.customize_feeds) self.news_menu.addAction(self.cac) self.news_menu.addSeparator() self.all_action = self.news_menu.addAction( _('Download all scheduled news sources'), self.download_all_scheduled) self.timer = QTimer(self) self.timer.start(int(self.INTERVAL * 60 * 1000)) self.timer.timeout.connect(self.check) self.oldest = gconf['oldest_news'] QTimer.singleShot(5 * 1000, self.oldest_check) def database_changed(self, db): self.db = db def oldest_check(self): if self.oldest > 0: delta = timedelta(days=self.oldest) try: ids = list(self.db.tags_older_than(_('News'), delta, must_have_authors=['calibre'])) except: # Happens if library is being switched ids = [] if ids: if ids: self.delete_old_news.emit(ids) QTimer.singleShot(60 * 60 * 1000, self.oldest_check) def show_dialog(self, *args): self.lock.lock() try: d = SchedulerDialog(self.recipe_model) d.download.connect(self.download_clicked) d.exec_() gconf['oldest_news'] = self.oldest = d.old_news.value() d.break_cycles() finally: self.lock.unlock() def customize_feeds(self, *args): from calibre.gui2.dialogs.custom_recipes import CustomRecipes d = CustomRecipes(self.recipe_model, self._parent) try: d.exec_() finally: d.deleteLater() def do_download(self, urn): self.lock.lock() try: account_info = self.recipe_model.get_account_info(urn) customize_info = self.recipe_model.get_customize_info(urn) recipe = self.recipe_model.recipe_from_urn(urn) un = pw = None if account_info is not None: un, pw = account_info add_title_tag, custom_tags, keep_issues = customize_info arg = { 'username': un, 'password': pw, 'add_title_tag':add_title_tag, 'custom_tags':custom_tags, 'title':recipe.get('title',''), 'urn':urn, 'keep_issues':keep_issues } self.download_queue.add(urn) self.start_recipe_fetch.emit(arg) finally: self.lock.unlock() def recipe_downloaded(self, arg): self.lock.lock() try: self.recipe_model.update_last_downloaded(arg['urn']) self.download_queue.remove(arg['urn']) finally: self.lock.unlock() def recipe_download_failed(self, arg): self.lock.lock() try: self.recipe_model.update_last_downloaded(arg['urn']) self.download_queue.remove(arg['urn']) finally: self.lock.unlock() def download_clicked(self, urn): if urn is not None: return self.download(urn) for urn in self.recipe_model.scheduled_urns(): if not self.download(urn): break def download_all_scheduled(self): self.download_clicked(None) def has_internet_connection(self): if not internet_connected(): if not self.internet_connection_failed: self.internet_connection_failed = True if self._parent.is_minimized_to_tray: self._parent.status_bar.show_message(self.no_internet_msg, 5000) elif not self.no_internet_dialog.isVisible(): self.no_internet_dialog.show() return False self.internet_connection_failed = False if self.no_internet_dialog.isVisible(): self.no_internet_dialog.hide() return True def download(self, urn): self.lock.lock() if not self.has_internet_connection(): return False doit = urn not in self.download_queue self.lock.unlock() if doit: self.do_download(urn) return True def check(self): recipes = self.recipe_model.get_to_be_downloaded_recipes() for urn in recipes: if not self.download(urn): # No internet connection, we will try again in a minute break
class OpenGLView(ZOpenGLView): CIRCLE_ANGLE = 360 INCREMENT = 2 def __init__(self, parent=None): super(ZOpenGLView, self).__init__(parent) self.parent = parent self.angle = 0 self.timerThread = None self.renderingInterval = 40 self.mutex = QMutex() def initializeGL(self): self.quadric = ZOpenGLQuadric() self.quadric.drawStyle(GLU_FILL) self.quadric.normals(GLU_SMOOTH) self.sphere = ZOpenGLSphere(self.quadric, None, 0.5, 40, 40) self.circle = ZOpenGLCircle(0.0, 0.0, 0.0, 1.3) self.timerThread = ZOpenGLTimerThread(self, self.renderingInterval) self.timerThread.start() def paintGL(self): self.mutex.lock() if (self.angle < (self.CIRCLE_ANGLE - self.INCREMENT)): self.angle += self.INCREMENT else: self.angle = self.INCREMENT if (self.sphere != None): pos = self.circle.getOrbitPosition(self.angle) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() gluLookAt(-5.0, 10.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glTranslate(0.0, 0.0, 0.0) glColor(1.0, 1.0, 1.0) #green self.circle.draw() glTranslate(pos[0], pos[1], pos[2]) light = ZOpenGLLight(GL_LIGHT0) lightPosition = [-2.0, 0.0, -1.0, 1.0] light.positionv(lightPosition) white = [1.0, 1.0, 1.0, 1.0] blue = [0.0, 0.0, 1.0, 1.0] green = [0.0, 1.0, 0.0, 1.0] shininess = 100.0 material = ZOpenGLMaterial(GL_FRONT) material.diffusev(green) material.specularv(white) material.shininess(shininess) self.sphere.draw() self.mutex.unlock() def resizeGL(self, width, height): if width == 0 or height == 0: return glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(16.0, width / height, 0.5, 40.0) glMatrixMode(GL_MODELVIEW)
class Lslrecorder: def __init__(self): self.mutex = QMutex() self.timeStamps = None self.stream = None self.inlet = None self.info = None self.channelCount = None self.doRec = False self.srate = None self.data = None self.bufferUpdateThread = None def findStream(self, hostname=None, timeout=1): # Gather lsl stream and create respective inlet and buffer, returns channelcount of that stream print("Searching for streams with a timeout of " + str(timeout) + " seconds") streams = resolve_stream(timeout) if len(streams) < 1: print("No stream found - exiting") return -1 else: print("Found " + str(len(streams)) + " streams") if hostname is None: print( "No stream hostname has been specified - selecting first stream" ) self.stream = streams[0] else: for stream in streams: if stream.hostname() == hostname: self.stream = stream print("Selected stream with hostname " + str(hostname)) break if self.stream is None: print("No stream with hostname " + str(hostname) + " has been found - exiting") self.inlet = StreamInlet(self.stream) self.info = self.inlet.info() self.channelCount = self.info.channel_count() self.srate = self.info.nominal_srate() self.data = np.empty((0, self.channelCount)) try: self.offset = self.inlet.time_correction(timeout=3) print("Offset: " + str(self.offset)) except TimeoutError: self.offset = 0 print("Offset Retrieval Timed Out") #print("Stream Meta Info:") #print(self.info.as_xml()) return self.channelCount def startRec(self): # Create and Start buffer update thread as daemon so that it gets terminated automatically when program exits self.doRec = True self.bufferUpdateThread = Thread(target=self.grabData, args=()) self.bufferUpdateThread.daemon = True self.bufferUpdateThread.start() def stopRec(self): self.doRec = False self.bufferUpdateThread.join() print("Stopped recording") def grabData(self): print("Starting recording") while self.doRec: c, t = self.inlet.pull_chunk(timeout=0.0) if c: # add offset to timestamps and transform timestamps to ms and round to int tmp_t = np.array([int((ts + self.offset) * 1000) for ts in t]) self.mutex.lock() self.data = np.concatenate((self.data, c), axis=0) if self.timeStamps is None: self.timeStamps = np.array(tmp_t) else: self.timeStamps = np.concatenate((self.timeStamps, tmp_t)) self.mutex.unlock()
class OpenGLView(ZOpenGLView): def __init__(self, parent=None): super(ZOpenGLView, self).__init__(parent) self.parent = parent self.timerThread = None self.renderingInterval = 30 self.mutex = QMutex() def initializeGL(self): self.angles = [0.0] * NUMBER_OF_PLANETS for i in range(NUMBER_OF_PLANETS): self.angles[i] = 30.0 * i self.sun = None self.planets = [None] * NUMBER_OF_PLANETS self.orbits = [None] * NUMBER_OF_PLANETS black = [0.0, 0.0, 0.0, 1.0] ambient = [0.5, 0.5, 0.5, 1.0] diffuse = [0.2, 0.4, 0.8, 1.0] greendiffuse = [0.0, 1.0, 0.0, 1.0] reddiffuse = [1.0, 0.0, 0.0, 1.0] bluediffuse = [0.0, 0.0, 1.0, 1.0] silverdiffuse = [0.8, 0.8, 0.8, 1.0] specular = [1.0, 1.0, 1.0, 1.0] emission = [0.8, 0.2, 0.0, 0.0] lowShining = [10.0] highShining = [100.0] sunMateria = ZOpenGLMateria(GL_FRONT, black, diffuse, black, emission, highShining) self.sun = ZOpenGLSolidSphere(sunMateria, 0.5, 40, 40) self.orbits[0] = ZOpenGLCircle(0.0, 0.0, 0.0, 1.0) self.orbits[1] = ZOpenGLCircle(0.0, 0.0, 0.0, 1.6) self.orbits[2] = ZOpenGLCircle(0.0, 0.0, 0.0, 2.4) self.orbits[3] = ZOpenGLCircle(0.0, 0.0, 0.0, 2.9) materia = [None] * NUMBER_OF_PLANETS materia[0] = ZOpenGLMateria(GL_FRONT, ambient, bluediffuse, specular, black, lowShining) materia[1] = ZOpenGLMateria(GL_FRONT, ambient, silverdiffuse, specular, black, lowShining) materia[2] = ZOpenGLMateria(GL_FRONT, ambient, greendiffuse, specular, black, lowShining) materia[3] = ZOpenGLMateria(GL_FRONT, ambient, reddiffuse, specular, black, lowShining) self.planets[0] = ZOpenGLSolidSphere(materia[0], 0.10, 20, 20) self.planets[1] = ZOpenGLSolidSphere(materia[1], 0.18, 20, 20) self.planets[2] = ZOpenGLSolidSphere(materia[2], 0.18, 20, 20) self.planets[3] = ZOpenGLSolidSphere(materia[3], 0.12, 20, 20) self.timerThread = ZOpenGLTimerThread(self, self.renderingInterval) self.timerThread.start() def paintGL(self): self.mutex.lock() for i in range(NUMBER_OF_PLANETS): if (self.angles[i] < CIRCLE_ANGLE - INCREMENT[i]): self.angles[i] += INCREMENT[i] else: self.angles[i] = INCREMENT[i] glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() gluLookAt(-1.0, 8.0, 17.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glColor(1.0, 1.0, 1.0) glTranslate(0, 0, 0) self.sun.draw() # 0.0, 0.0, 0.0) light = ZOpenGLLight(GL_LIGHT0) lightPosition = [-2.0, 0.0, -1.0, 1.0] light.positionv(lightPosition) for i in range(NUMBER_OF_PLANETS): pos = self.orbits[i].getOrbitPosition(int(self.angles[i])) glPushMatrix() glTranslate(pos[0], pos[1], pos[2]) self.planets[i].draw() glPopMatrix() self.mutex.unlock() def resizeGL(self, w, h): if (w == 0 or h == 0): return glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(16.0, w / h, 0.5, 40.0) glMatrixMode(GL_MODELVIEW)