def __init__(self, path, fallback=None, format="json"):
            if os.path.exists(path):
                os.unlink(path)

            if fallback:
                start_daemon_thread(self.run_fallback_thread, fallback)

            super(UnixServer, self).__init__(format, SocketServer.ThreadingUnixStreamServer, path)
Beispiel #2
0
    def add_handler(self, name, handler):
        queue = self.queue_factory(name)
        self.record_fanout.add_queue(queue)

        start_daemon_thread(functools.partial(self._handler_thread, name, handler, queue))

        self.handlers[name] = handler
        self.queues[name] = queue
Beispiel #3
0
    def run_task(self, task):
        with self.workers_lock:
            if not (self.busy_workers < self.total_workers):
                logger.info("Starting worker #%d", self.total_workers)
                start_daemon_thread(self._worker)
                self.total_workers += 1

        task_id = uuid.uuid1()
        self.queue.put((task_id, task, traceback.format_stack()))
        return task_id
Beispiel #4
0
    def _on_peer_resolved(self, service):
        if service.name == self.my_name:
            return

        if service.name in self.peers:
            logger.info("Connection with peer %s already exists", service.name)
            return

        peer = Peer(self, service.url, service.url.replace("http://", "ws://"))
        peer.possessions = {"objects": {},
                            "routines": {}}

        self.peers[service.name] = peer
        start_daemon_thread(self._peer_connection_thread, service.name)
Beispiel #5
0
    def _on_start(self):
        if hasattr(self, "poll"):
            self.logger.debug("Starting poll")
            start_daemon_thread(self._poll_loop)

        for name, pad in self._input_pads.iteritems():
            if pad["has_initial_value"]:
                self.__container.worker_pool.run_task(functools.partial(pad["receiver"], pad["initial_value"]))

        for name, pad in self._output_pads.iteritems():
            generator = pad.get("generator")
            if generator:
                self.logger.debug("Starting output pad %s generator", name)
                start_daemon_thread(self._output_pad_loop, name, generator)
    def __init__(self, format, server_factory, server_address):
        self.logger = logger.getChild("%r" % (server_address,))

        self.format = format
        try:
            self.parse = {
                "json": lambda address, text: parse_json(text),
                "text": lambda address, text: parse_plaintext(text, default_application=address, default_logger="root"),
            }[self.format]
        except KeyError:
            raise Exception("Unknown format: '%s'" % format)

        self.server = server_factory(server_address, StreamSocketServerHandler)
        self.server.queue = Queue()

        start_daemon_thread(self.server.serve_forever)
Beispiel #7
0
    def __init__(self):
        self.hotkeys = defaultdict(list)

        context = pyudev.Context()

        self.input_devices = {}
        for device in context.list_devices(subsystem="input"):
            if device.device_node is not None:
                self._add_input_device(device)

        start_daemon_thread(self._input_devices_thread)

        self.pyudev_monitor = pyudev.Monitor.from_netlink(context)
        self.pyudev_monitor.filter_by("input")
        self.pyudev_observer = pyudev.MonitorObserver(self.pyudev_monitor, self._on_new_input_device_event)
        self.pyudev_observer.start()
Beispiel #8
0
def setup_server(my_name, bus, config):
    container = Container()

    container.local_database = Database(os.path.join(USER_DATA_DIR, "local_database.json"))
    container.shared_database = Database(os.path.join(USER_DATA_DIR, "shared_database.json"))

    container.imported_promises_manager = ImportedPromisesManager()
    container.exported_promises_manager = ExportedPromisesManager()

    container.worker_pool = WorkerPool()

    container.peer_manager = PeerManager(container, my_name, bus)
    container.object_manager = ObjectManager(container)
    container.routine_manager = RoutineManager(container)
    container.hotkey_manager = HotkeyManager(container, get_hotkey_provider(config))
    container.remote_hotkey_manager = RemoteHotkeyManager(container)

    container.web_server = WebServer(container, "0.0.0.0", 46408)

    container.event_transceiver = EventTransceiver(container)
    container.exported_promises_manager.add_exported_promises_observer(container.event_transceiver)
    container.object_manager.add_object_error_observer(container.event_transceiver)
    container.object_manager.add_object_signal_observer(container.event_transceiver)
    container.object_manager.add_object_property_observer(container.event_transceiver)
    container.object_manager.add_object_pad_connection_observer(container.event_transceiver)
    container.object_manager.add_object_pad_value_observer(container.event_transceiver)

    themylog = get_themylog(config)
    if themylog:
        themylog_publisher = ThemylogPublisher(*themylog)
        container.object_manager.add_object_signal_observer(themylog_publisher)
        container.object_manager.add_object_property_observer(themylog_publisher)

    objects = {
        name: create_object(name, desc.cls, container, desc.args) for name, desc in get_objects(config).iteritems()
    }
    objects["_%s" % my_name] = create_object("_%s" % my_name, Me, container, {})
    container.object_manager.set_objects(objects)

    setup_ons(config, container)
    setup_routines(config, container)

    start_daemon_thread(container.web_server.serve_forever)
 def __init__(self, address_family, address_type, address):
     self.address_family = address_family
     self.address_type = address_type
     self.address = address
     self.queue = Queue()
     start_daemon_thread(self._pub_thread)
Beispiel #10
0
from smarthome.server import setup_server
from smarthome.zeroconf.service import ZeroconfService

from themyutils.threading import start_daemon_thread

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(asctime)s [%(name)s] %(message)s")
    logging.getLogger("geventwebsocket.handler").setLevel(logging.INFO)
    logging.getLogger("smarthome.server.web_server.event_transceiver.object_pad_value").setLevel(logging.INFO)
    logging.getLogger("smarthome.zeroconf.discoverer").setLevel(logging.INFO)

    GObject.threads_init()
    dbus.mainloop.glib.threads_init()

    name = platform.node()

    dbus_loop = dbus.mainloop.glib.DBusGMainLoop()
    bus = dbus.SystemBus(mainloop=dbus_loop)

    config = etree.parse(open(os.path.join(os.path.dirname(__file__), "../config_%s.xml" % name)))
    etree.strip_tags(config, etree.Comment)

    setup_server(name, bus, config)

    zeroconf_service = ZeroconfService(name, bus)

    start_daemon_thread(Gtk.main)

    while True:
        time.sleep(1)
Beispiel #11
0
    args = parser.parse_args(sys.argv[1:])

    logging.basicConfig(level=args.level, format=DEFAULT_PROCESS_LOG_FMT)
    logger = logging.getLogger(__name__)

    config = read_config(args.config or find_config())

    record_fanout = Fanout()
    handler_manager = HandlerManager(record_fanout, create_persistent_queue)

    logger.info("Creating receivers")

    receivers = create_receivers(config)

    for receiver in receivers:
        start_daemon_thread(functools.partial(receiver_thread, receiver, record_fanout))

    logger.info("Creating handlers")

    handlers = create_handlers(config)

    handlers_name_counters = defaultdict(lambda: itertools.count(1))
    for handler in handlers:
        name = "handler-%s-%d" % (handler.__class__.__name__, handlers_name_counters[handler.__class__.__name__].next())
        handler_manager.add_handler(name, handler)

    logger.info("Starting heartbeat")

    heartbeats = []
    start_daemon_thread(functools.partial(heartbeat_thread, heartbeats))
Beispiel #12
0
 def init(self):
     start_daemon_thread(self._pika_thread)
            self.expected_guests = [g for g in self.expected_guests if g != title]

    def say(self, phrase):
        requests.post("%s/control" % self.smarthome_api, data=json.dumps({"command": "call_method",
                                                                          "args": {"object": "hall_speech_synthesizer",
                                                                                   "method": "say",
                                                                                   "args": {"phrase": phrase}}}))

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="guests announcer")
    parser.add_argument("--guests-api", required=True, help="Guests API URL")
    parser.add_argument("--smarthome-api", required=True, help="Smarthome API URL")
    args = parser.parse_args()

    guests_watcher = GuestsWatcher(args.guests_api, args.smarthome_api)
    start_daemon_thread(guests_watcher.watch)

    while True:
        try:
            mq_connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
            mq_channel = mq_connection.channel()

            mq_channel.exchange_declare(exchange="themylog", type="topic")

            result = mq_channel.queue_declare(exclusive=True)
            queue_name = result.method.queue

            mq_channel.queue_bind(exchange="themylog", queue=queue_name, routing_key=b"smarthome.front_door.closed")
            mq_channel.basic_consume(lambda *args, **kwargs: guests_watcher.on_front_door_closed, queue=queue_name, no_ack=True)

            mq_channel.start_consuming()
Beispiel #14
0
 def thread(self, *args, **kwargs):
     return start_daemon_thread(*args, **kwargs)
Beispiel #15
0
 def start(self):
     if self._try_init():
         self._on_start()
     else:
         self.logger.info("Unable to init object, forking initialization loop")
         start_daemon_thread(self._init_loop)
Beispiel #16
0
 def __init__(self, handler_manager):
     self.handler_manager = handler_manager
     start_daemon_thread(self._poll_queues)