コード例 #1
0
    def __init__(self, name, warrant):
        super().__init__(name, warrant)

        def message_cb(topic, message):
            try:
                data = json.loads(message)

                # station, name, duty, warrant
                station = data.get("station", None)
                name = data.get("name", None)
                duty = data.get("duty", None)
                warrant = data.get("warrant", None)

                if station is None or name is None:
                    raise Exception("Invalid message: {0}".format(message))

                # TODO: check if station is valid
                # TODO: check if duty is valid
                # TODO: check if warrant is valid

                # send the message to the specified station
                station_topic = config.topic_name_station_get(station)
                del data["station"]
                self._publish(station_topic, json.dumps(data))

                # remove the agent that the station should call back
                with Writer(config.DB_PATH) as db_write:
                    db_write.write(("DELETE FROM Agents "
                                    "WHERE (Station = ?) "
                                    "AND (Name = ?) "),
                                   parameters=(station, name))
                if duty is not None:
                    # save the agent that the station should dispatch
                    with Writer(config.DB_PATH) as db_write:
                        db_write.write((
                            "INSERT INTO Agents (Station, Name, Duty, Warrant) "
                            "VALUES (?, ?, ?, ?)"),
                                       parameters=(station, name, duty,
                                                   json.dumps(warrant)))

            except Exception as e:
                l.error("Unable to process message '{0}': {1}".format(
                    message, str(e)))

        self.message_cb = message_cb
        self._mqtt_topics.append(
            config.topic_name_officer_get(config.station_name_get(),
                                          "dispatcher"))
コード例 #2
0
        def message_cb(topic, message):
            if topic == HEARTBEAT_1_MINUTE:
                if self._is_first:
                    # delay the check
                    self._is_first = False
                    return

                # go through all the recorded agents and ask them their message status
                agents = []
                with Reader(config.DB_PATH) as db_read:
                    agents = db_read.read(
                        ("SELECT Station, Name, Duty, Warrant "
                         "FROM Agents "))
                for agent in agents:
                    agent_status_topic_name = config.topic_name_agent_status_get(
                        agent[0], agent[1])

                    # check previous status
                    status = self._vitals.get(agent_status_topic_name, "0")
                    if status != "1":
                        l.warn("Agent {0}/{1} is not alive".format(
                            agent[0], agent[1]))

                        # try to revive the agent
                        dispatcher_topic_name = config.topic_name_officer_get(
                            config.station_name_get(), "dispatcher")
                        data = {
                            "station": agent[0],
                            "name": agent[1],
                            "duty": agent[2],
                            "warrant": json.loads(agent[3])
                        }
                        self._mqtt_client.publish(dispatcher_topic_name,
                                                  json.dumps(data))

                    # ask for the current one
                    self._mqtt_client.publish(agent_status_topic_name, "s")

                # reset the vitals
                self._vitals = {}
            else:
                if message != "s":
                    # someone's status
                    self._vitals[topic] = message
コード例 #3
0
ファイル: Agent.py プロジェクト: adrian-vlad/MagicAceXpress
    def _prepare(self):
        # prepare mqtt client
        def mqtt_cb(message):
            self._messages.put(message)

        self._mqtt_client = MQTTWrap(self._name)
        self._mqtt_topic_status = config.topic_name_agent_status_get(
            config.station_name_get(), self._name)
        self._mqtt_topics.append(self._mqtt_topic_status)
        self._mqtt_client.init(self._mqtt_topics, mqtt_cb,
                               self._mqtt_topic_status, "0")
        self._say_hi()

        # prepare signals
        def signal_handler(sig, frame):
            if sig == signal.SIGINT or sig == signal.SIGTERM:
                self._shutdown = True

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
コード例 #4
0
    def __init__(self, name, warrant):
        super().__init__(name, warrant)

        self._mqtt_topic_name = config.topic_name_officer_get(
            config.station_name_get(), self._name)
        self._mqtt_topics.append(self._mqtt_topic_name)
コード例 #5
0
    def __init__(self, name, warrant):
        super().__init__(name, warrant)

        self._mqtt_topic_name = config.topic_name_officer_get(
            config.station_name_get(), self._name)
        self._device = None

        # bluetooth connection
        def cb_connect(device):
            if self._device is None:
                device = os.path.basename(
                    device)[len(BLUEZ_DEVICE_PREFIX):].replace("_", ":")
                self._device = device
                l.debug("New device %s" % (device))
                self._bl.connect(self._device)

                # start sending audio
                self._streaming = True

        def cb_disconnect(device):
            device = os.path.basename(
                device)[len(BLUEZ_DEVICE_PREFIX):].replace("_", ":")
            if device == self._device:
                self._bl.disconnect(self._device)
                self._device = None
                l.debug("Disconnected device %s" % (device))

                # stop sending audio
                self._streaming = False

        self._bl = BluetoothAgent(cb_connect, cb_disconnect)
        self._th_bl = threading.Thread(target=self._bl.loop)
        self._th_bl.start()

        # bluetooth audio streaming
        self._streaming = False
        self._stop = False

        def stream():
            while not self._stop:
                if self._streaming:
                    try:
                        inp = alsaaudio.PCM(
                            alsaaudio.PCM_CAPTURE,
                            alsaaudio.PCM_NORMAL,
                            device="bluealsa:HCI=hci0,DEV={0},PROFILE=a2dp".
                            format(self._device))
                        inp.setchannels(2)
                        inp.setrate(48000)
                        inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
                        inp.setperiodsize(2000)

                        while self._streaming:
                            ln, data = inp.read()
                            self._stream_audio(data)
                    except Exception as e:
                        l.error("Error while streaming: {0}".format(
                            type(e).__name__))
                        time.sleep(1)
                else:
                    time.sleep(1)

        self._th_stream = threading.Thread(target=stream)
        self._th_stream.start()