def test(): from src import messagebus succeed = [0] def f(m, v): succeed[0] = 1 messagebus.subscribe("/system/selftest", f) messagebus.postMessage("/system/selftest", "Test") time.sleep(0.2) if not succeed[0]: time.sleep(2) if succeed[0]: raise RuntimeError( "Message not delivered within 0.2 second. This may happen occasionally if CPU load is high but otherwise should not occur." ) else: raise RuntimeError("Message not delivered within 2 seconds") f2 = weakref.ref(f) del f succeed[0] = 0 time.sleep(1) messagebus.postMessage("/system/selftest", "Test") time.sleep(3) if succeed[0]: if f2(): logging.error("selftest: f still exists " + str(f2())) raise RuntimeError("Garbage collection fails to unsubscribe")
def f(): try: if len(name) == 1: self.handleError( 'Single letter names may not work correctly. JACK in general may have subpar performace with this plugin badly configured.' ) self.synthLock = threading.Lock() self.synth = scullery.fluidsynth.FluidSynth( soundfont=data.get("device.soundfont", "").strip(), jackClientName=name, connectOutput=data.get("device.connectOutput", "").strip()) for i in range(0, 16): try: inst = "" inst = data.get("device.ch" + str(i) + "instrument", "") bank = None if ':' in inst: bank, inst = inst.split(":") bank = int(bank.strip()) inst = inst.strip() try: inst = int(inst) except: pass if inst: self.synth.setInstrument(i, inst, bank=bank) except: self.handleError("Error setting instrument:" + inst + " for channel " + str(i) + "\n" + traceback.format_exc()) connectMidi = data.get("device.connectMidi", "").strip().replace(":", '_').replace( "[", '').replace("]", '').replace(" ", '') messagebus.subscribe("/midi/" + connectMidi, self.onMidiMsg) for i in range(16): x = widgets.Button() x.attach(self.makeWidgetHandler(i)) self.widgets.append(x) except: self.handleException()
def __init__(self, file): if not os.path.exists(file): newfile = True else: newfile = False self.history = sqlite3.Connection(file) self.history.row_factory = sqlite3.Row self.filename = file if newfile: self.history.execute("PRAGMA application_id = 707898159") self.lock = threading.RLock() self.children = {} self.history.execute( "CREATE TABLE IF NOT EXISTS channel (tagName text, unit text, accumulate text, metadata text)" ) self.history.execute( "CREATE TABLE IF NOT EXISTS record (channel INTEGER, timestamp INTEGER, value REAL)" ) self.history.execute( "CREATE VIEW IF NOT EXISTS SimpleViewLocalTime AS SELECT channel.tagName as Channel, channel.accumulate as Type, datetime(record.timestamp,'unixepoch','localtime') as LocalTime, record.value as Value, channel.unit as Unit FROM record INNER JOIN channel ON channel.rowid = record.channel;" ) self.history.execute( "CREATE VIEW IF NOT EXISTS SimpleViewUTC AS SELECT channel.tagName as Channel, channel.accumulate as Type, datetime(record.timestamp,'unixepoch','utc') as UTCTime, record.value as Value, channel.unit as Unit FROM record INNER JOIN channel ON channel.rowid = record.channel;" ) self.pending = [] self.history.close() self.lastFlushed = time.monotonic() self.lastGarbageCollected = 0 self.flushInterval = 10 * 60 self.gcInterval = 3600 * 2 messagebus.subscribe("/system/save", self.forceFlush) def f(): self.flush() self.flusher_f = f self.flusher = scheduling.scheduler.everyMinute(f)
def __init__(self, name, data): devices.Device.__init__(self, name, data) self.closed = False self.service = None self.plock = threading.RLock() if '/' in name or '\\' in name: raise ValueError("Path sep in name") self.serviceDir = os.path.join(directories.vardir, "drayerdb", name) os.makedirs(self.serviceDir, exist_ok=True) try: from hardline import drayerdb if not self.data.get('device.syncKey', '').strip(): vk, sk = drayerdb.libnacl.crypto_sign_keypair() self.setDataKey('device.syncKey', base64.b64encode(vk).decode()) self.setDataKey('device.writePassword', base64.b64encode(sk).decode()) else: vk, sk = base64.b64decode(self.data.get( 'device.syncKey', '')), base64.b64decode( self.data.get('device.writePassword', '')) self.service = drayerdb.DocumentDatabase( os.path.join(self.serviceDir, name + '.db'), keypair=(vk, sk), autocleanDays=float(self.data.get('device.autocleanDays', '0'))) self.service.dataCallback = self.dataCallback if self.data.get('device.archiveNotifications', '').lower() == 'yes': from scullery import messagebus messagebus.subscribe("/system/notifications/#", self.insertNotification) if self.data.get('device.syncServer', ''): self.service.useSyncServer( self.data.get('device.syncServer', '')) except Exception: self.handleException()
def __init__(self, name, data): devices.Device.__init__(self, name, data) self.closed = False self.plock = threading.RLock() try: def f(*a): with self.plock: if self.closed: return x = [ 'gmediarender', '--gstout-videosink', 'glimagesink', '--gstout-audiopipe', 'jackaudiosink slave-method=0 port-pattern="jkhjkjhkhkhkhkjhk" client-name=' + data.get("device.advertiseName", 'DLNA') ] x += [ '-f', data.get("device.advertiseName", socket.gethostname()) or socket.gethostname() ] x += [ '-u', data.get("device.uuid", str(uuid.uuid4())) or str(uuid.uuid4()) ] self.process = subprocess.Popen(x) self.restart = f messagebus.subscribe("/system/jack/started", f) f() except: self.handleException()
def subscribe(self, f): messagebus.subscribe("/devices/" + self.name + "/keypress", f)
logging.exception("Save fail") setupFile() def saveSettings(*a, **k): persist.save(file, fn, private=True) persist.unsavedFiles.pop(fn, "") def settingsDirty(): persist.unsavedFiles[fn] = "Alert settings changed" messagebus.subscribe("/system/save", saveSettings) # This is a dict of all alerts that have not yet been acknowledged. # It is immutable and only ever atomically replaces unacknowledged = {} # Same as above except may be mutated under lock _unacknowledged = {} # see above, but for active alarms not just for unacknowledged active = {} _active = {} all = weakref.WeakValueDictionary() priorities = { 'debug': 10,