Exemplo n.º 1
0
    def __init__(self):
        self.running = False
        #self.runningJobsLock = threading.Lock() #TODO needed?
        self.jobsLock = threading.Lock()
        self.maintenanceJobsLock = threading.Lock()
        self.maintenanceJobs = []
        self.lastMaintenanceJobId = 0
        self.runningJobs = {}  #id:s as keys
        self.settings = Settings('telldus.scheduler')
        Application().registerShutdown(self.stop)
        Application().registerMaintenanceJobHandler(
            self.addMaintenanceJobGeneric)
        self.timezone = self.settings.get('tz', 'UTC')
        self.latitude = self.settings.get('latitude', '55.699592')
        self.longitude = self.settings.get('longitude', '13.187836')
        self.jobs = []
        self.fetchLocalJobs()
        self.live = TelldusLive(self.context)
        self.deviceManager = DeviceManager(self.context)
        if self.live.isRegistered():
            #probably not practically possible to end up here
            self.requestJobsFromServer()

        self.thread = threading.Thread(target=self.run)
        self.thread.start()
Exemplo n.º 2
0
    def allParameters(self):
        """
		Similar as parameters() but this returnes more values such as the device type and the room
		"""
        params = self.parameters()
        if isinstance(params, dict):
            # Copy so we don't alter the original
            params = params.copy()
        else:
            # parameters() must return a dict
            params = {}

        devicetype = self.metadata('devicetype', None)
        if devicetype is not None:
            # Devicetype in metadata overrides the devicetype
            params['devicetype'] = devicetype
        else:
            try:
                params['devicetype'] = self.deviceType()
            except Exception as error:
                params['devicetype'] = Device.TYPE_UNKNOWN
                Application.printException(error)
        if self._room is None:
            # Make sure it's removed
            params.pop('room', None)
        else:
            params['room'] = self._room
        return params
 def run(self):
     app = Application()
     path = '/tmp/%s' % self.name
     if os.path.exists(path):
         os.remove(path)
     s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     s.bind(path)
     s.listen(1)
     sockets = [s.fileno()]
     while self.running:
         r, w, e = select.select(sockets, [], [], 10)
         if len(r) == 0:
             continue
         if s.fileno() in r:
             conn, addr = s.accept()
             self.clients.append(Socket(conn))
             sockets.append(conn.fileno())
         for conn in self.clients:
             if conn.fileno() in r:
                 d = conn.read()
                 if conn.connected:
                     app.queue(self.cb, conn, d)
                 else:
                     sockets.remove(conn.fileno())
         self.clients[:] = [x for x in self.clients if x.connected]
     s.close()
Exemplo n.º 4
0
def main():
    from base import Application

    p = loadClasses(plugins)
    s = loadClasses(startup)

    app = Application(run=False)
    app.run(startup=s)
Exemplo n.º 5
0
def start_app():
    ''' Sparx server instantiation'''

    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    logging.info('*** Sparx-core - version '+ str(version) +'. started at:\
     http://localhost:%d/' % (options.port))
    tornado.ioloop.IOLoop.instance().start()
Exemplo n.º 6
0
 def discover(self):
     devices = pywemo.discover_devices()
     for device in devices:
         if isinstance(device, pywemo.Bridge):
             Application().queue(self.bridgeFound, device)
         elif isinstance(device, pywemo.Switch):
             Application().queue(self.switchFound, device)
         elif isinstance(device, pywemo.Motion):
             Application().queue(self.motionFound, device)
     Application().queue(self.deviceManager.finishedLoading, 'wemo')
Exemplo n.º 7
0
    def run(self):
        self.running = True
        app = Application()
        buffer = ''
        ttl = None
        state = 0

        while self.running:
            if self.dev is None:
                time.sleep(1)
                try:
                    self.dev = serial.serial_for_url(self.devUrl,
                                                     115200,
                                                     timeout=0)
                except Exception as e:
                    self.dev = None
                continue

            if state == 0:
                x = self.__readByte(interruptable=True)
                if x == '':
                    if self.__waitForResponse is not None and self.__waitForResponse.queued + 5 < time.time(
                    ):
                        self.__waitForResponse.timeout()
                        self.__waitForResponse = None
                    if len(self.__queue) and self.__waitForResponse is None:
                        state = 1
                    continue
                if x == '\r':
                    continue
                if x == '+':
                    # Start of data
                    buffer = ''
                    continue
                if x == '\n':
                    (cmd, params) = RF433Msg.parseResponse(buffer)
                    if cmd is None:
                        continue
                    if self.__waitForResponse is not None:
                        if cmd == self.__waitForResponse.cmd():
                            self.__waitForResponse.response(params)
                            self.__waitForResponse = None
                            continue
                    app.queue(self.handler.decodeData, cmd, params)
                    continue
                buffer = buffer + x

            elif state == 1:
                if len(self.__queue) == 0:
                    state = 0
                    continue
                self.__waitForResponse = self.__queue.pop(0)
                self.__send(self.__waitForResponse.commandString())
                self.__waitForResponse.queued = time.time()
                state = 0
Exemplo n.º 8
0
 def __init__(self):
     self._ready = False
     self._running = True
     self._knownDevices = None
     Application().registerShutdown(self.onShutdown)
     self.client = mqtt.Client(userdata=self)
     self.client_on_disconnect = self.onDisconnect
     self.client.on_connect = self.onConnect
     self.client.on_message = self.onMessage
     if self.config('hostname') != '':
         Application().queue(self.connect)
Exemplo n.º 9
0
 def remove(self):
     for cls in self.classes:
         plugin = self.context.components.get(cls)
         if not plugin:
             continue
         if not hasattr(plugin, 'tearDown'):
             continue
         try:
             plugin.tearDown()
         except Exception as error:
             Application.printException(error)
     shutil.rmtree(self.path)
Exemplo n.º 10
0
 def __init__(self):
     self.deviceManager = DeviceManager(self.context)
     self.username = None
     self.ssdp = None
     config = self.config('bridge')
     self.activated = config.get('activated', False)
     self.username = config.get('username', '')
     self.bridge = config.get('bridge', '')
     self.state = Hue.STATE_NO_BRIDGE
     self.lights = {}
     self.ssdp = SSDP(self.context)
     if self.activated:
         Application().queue(self.selectBridge, config.get('bridge'))
     Application().registerScheduledTask(self.update, minutes=1)
Exemplo n.º 11
0
 def registerSensorCleanup(self):
     Application().registerScheduledTask(self.cleanupSensors,
                                         hours=12)  # every 12th hour
     t = Timer(10, self.cleanupSensors)  # run a first time after 10 minutes
     t.daemon = True
     t.name = 'Sensor cleanup'
     t.start()
	def __init__(self):
		self.running = False
		self.timeLock = threading.Lock()
		self.triggers = {}
		Application().registerShutdown(self.stop)
		self.thread = threading.Thread(target=self.run)
		self.thread.start()
Exemplo n.º 13
0
 def proxyMethod(*args, **kwargs):
     # We are in the script thread here, we must syncronize with the main
     # thread before calling the attribute
     condition.acquire()
     args = list(args)
     if len(args) >= 2 and lua_type(args[1]) == 'table':
         # First parameter is a lua table. Handle this as **kwargs call
         kwargs = dict(args[1])
         del args[1]
     # TODO: Also loop through kwargs and look for lua types
     for i, arg in enumerate(args):
         if lua_type(arg) == 'function':
             t = LuaFunctionWrapper(self, arg)
             args[i] = t
             self.references.append(weakref.ref(t))
     try:
         Application().queue(mainThreadCaller, args, kwargs)
         condition.wait(
             20)  # Timeout to not let the script hang forever
         if 'error' in retval:
             self.p("Error during call: %s", retval['error'])
             raise AttributeError(retval['error'])
         elif 'return' in retval:
             if type(retval['return']) is dict:
                 # Wrap to lua table
                 return self.lua.table_from(retval['return'])
             return retval['return']
     finally:
         condition.release()
     raise AttributeError('The call to the function "%s" timed out' %
                          attrName)
Exemplo n.º 14
0
	def __init__(self):
		self.scripts = []
		self.load()
		self.fileobserver = Observer()
		self.fileobserver.schedule(FileChangedHandler(self), Board.luaScriptPath())
		self.fileobserver.start()
		Application().registerShutdown(self.shutdown)
Exemplo n.º 15
0
	def __init__(self):
		self.running = True
		self.mtimes = {}
		self.thread = Thread(target=self.run)
		self.thread.start()
		signal.signal(signal.SIGUSR1, Developer.debugshell)  # Register handler
		Application().registerShutdown(self.stop)
Exemplo n.º 16
0
	def registerSensorCleanup(self):
		"""Register scheduled job to clean up sensors that have not been updated for a while"""
		Application().registerScheduledTask(self.cleanupSensors, hours=12)  # every 12th hour
		tmr = Timer(600, self.cleanupSensors)  # run a first time after 10 minutes
		tmr.daemon = True
		tmr.name = 'Sensor cleanup'
		tmr.start()
Exemplo n.º 17
0
 def __init__(self):
     super(Server, self).__init__()
     mimetypes.init()
     port = 80 if os.getuid() == 0 else 8080
     cherrypy.config.update({
         'server.socket_host': '::',
         'server.socket_port': port,
         'tools.sessions.on': True,
         'tools.sessions.timeout': 60,
         'tools.sessions.httponly': True,
     })
     cherrypy.tree.mount(RequestHandler(self.context),
                         '',
                         config={
                             '/ws': {
                                 'tools.websocket.on': True,
                                 'tools.websocket.handler_cls':
                                 WebSocketHandler
                             }
                         })
     cherrypy.engine.autoreload.unsubscribe()
     WebSocketPlugin(cherrypy.engine).subscribe()
     cherrypy.tools.websocket = WebSocketTool()
     cherrypy.engine.start()
     Application().registerShutdown(self.stop)
Exemplo n.º 18
0
 def __init__(self):
     self.sensor = YRSensor()
     deviceManager = DeviceManager(self.context)
     deviceManager.addDevice(self.sensor)
     deviceManager.finishedLoading('yr')
     Application().registerScheduledTask(self.__requestWeather,
                                         hours=1,
                                         runAtOnce=True)
	def __disconnected(self):
		self.email = ''
		self.connected = False
		self.registered = False
		def sendNotification():
			self.liveDisconnected()
		# Syncronize signal with main thread
		Application().queue(sendNotification)
Exemplo n.º 20
0
 def configWasUpdated(self, key, value):
     if key in [
             'use_via', 'useConfigUrl', 'configUrl', 'useEntityCategories',
             'discovery_topic', 'device_name'
     ]:
         self.devices = []
         self.cleanupDevices()
         self.hub.deviceName = self.config('device_name')
         Application().queue(self.discoverAndConnect)
     elif key == 'state_retain' and value == False and self.mqtt_connected_flag:
         self._debug('Retain set to false, clear retained states')
         for topic in self.config('device_topics'):
             self.client.publish(
                 '%s/%s/state' % (self.config('discovery_topic'), topic),
                 None, 0, False)
     elif key in ['username', 'password', 'hostname', 'port']:
         Application().queue(self.connect)
Exemplo n.º 21
0
 def detectBroadlink(self):
     self.devices = broadlink.discover(timeout=5)
     for device in self.devices:
         self.deviceManager.addDevice(BroadDevice(device))
     self.deviceManager.finishedLoading('broadlink')
     Application().registerScheduledTask(self.updateValues,
                                         seconds=300,
                                         runAtOnce=True)
Exemplo n.º 22
0
	def __init__(self):
		self.loaded = False
		self.armState = None
		self.alarmDevice = AlarmDevice()
		deviceManager = DeviceManager(self.context)
		deviceManager.addDevice(self.alarmDevice)
		self.devices = {}
		Application().registerScheduledTask(fn=self.__fetch, minutes=10, runAtOnce=True)
Exemplo n.º 23
0
 def __init__(self):
     self.lastCheckedDate = None
     self.device = HolidayDevice()
     deviceManager = DeviceManager(self.context)
     deviceManager.addDevice(self.device)
     deviceManager.finishedLoading('holiday')
     Application().registerScheduledTask(self.checkDay,
                                         minutes=1,
                                         runAtOnce=False)
Exemplo n.º 24
0
	def allParameters(self):
		"""
		Similar as parameters() but this returnes more values such as the device type
		"""
		params = self.parameters()
		if isinstance(params, dict):
			# Copy so we don't alter the original
			params = params.copy()
		else:
			# parameters() must return a dict
			params = {}

		try:
			params['devicetype'] = self.deviceType()
		except Exception as error:
			params['devicetype'] = Device.TYPE_UNKNOWN
			Application.printException(error)
		return params
Exemplo n.º 25
0
	def __init__(self, port, context):
		HapConnection.HTTPDServer = self
		self.context = context
		self.connections = []
		self.httpServer = ThreadedTCPServer(('', port), HapConnection)
		self.thread = Thread(target=self.httpServer.serve_forever, name='HomeKit http server')
		self.thread.daemon = True
		self.thread.start()
		Application().registerShutdown(self.shutdown)
Exemplo n.º 26
0
 def onMqttConnect(self, client, userdata, flags, result):
     self.mqtt_connected_flag = True
     self._debug('Mqtt connected')
     self.publishDevices()
     self.client.subscribe(
         '%s/+/%s/+/set' %
         (self.config('discovery_topic'), self.config('device_name')))
     self.client.subscribe(
         '%s/+/%s/+/set/#' %
         (self.config('discovery_topic'), self.config('device_name')))
     Application().queue(self.cleanupDevices)
Exemplo n.º 27
0
		def asyncFetch():
			# This is run in a separate thread and can block
			try:
				session = verisure.Session(self.config('username'), self.config('password'))
				session.login()
				overview = session.get_overview()
				session.logout()
			except Exception as e:
				logging.warning("Could not fetch Verisure data")
				return
			Application().queue(parseValues, overview)
Exemplo n.º 28
0
 def __init__(self, run=True):
     self.lastMinute = None
     self.running = False
     self.timeLock = threading.Lock()
     # TODO, the list below should be written to file
     self.triggered = {}  # keep track of when triggered between reloads
     self.triggers = {}
     Application(run).registerShutdown(self.stop)
     if run:
         self.thread = threading.Thread(target=self.run)
         self.thread.start()
Exemplo n.º 29
0
	def __init__(self):
		self.listener = None
		self.clientAddress = None
		CommandHandler.rf433 = RF433(self.context)
		CommandHandler.context = self.context
		if TelldusZWave is not None:
			self.zwave = TelldusZWave(self.context)
		Application().registerShutdown(self.__stop)
		self.autoDiscovery = SocketServer.UDPServer(('0.0.0.0', 30303), AutoDiscoveryHandler)
		self.commandSocket = SocketServer.UDPServer(('0.0.0.0', 42314), CommandHandler)
		Thread(target=self.__autoDiscoveryStart).start()
		Thread(target=self.__commandSocketStart).start()
Exemplo n.º 30
0
	def handle(self):
		sock = self.request[1]
		product = ''.join(x.capitalize() for x in Board.product().split('-'))
		live = TelldusLive(Application.defaultContext())
		msg = '%s:%s:%s:%s:%s' % (
			product,
			AutoDiscoveryHandler.getMacAddr(Board.networkInterface()),
			Board.secret(),
			Board.firmwareVersion(),
			live.uuid,
		)
		sock.sendto(msg, self.client_address)