Ejemplo n.º 1
0
    def __init__(self,
                 mqtt_server_ip,
                 mqtt_server_port,
                 mqtt_user=None,
                 mqtt_pass=None,
                 mqtt_base_topic="megaphone",
                 mp3_filename="output.mp3",
                 ext_amp_conf: ExternalAmplifierConfig = None):
        self.mqtt_server_ip = mqtt_server_ip
        self.mqtt_server_port = mqtt_server_port
        self.mqtt_user = mqtt_user
        self.mqtt_pass = mqtt_pass
        self.mqtt_base_topic = mqtt_base_topic
        self.client: mqtt.Client = mqtt.Client()
        self.mp3_filename = mp3_filename
        self.ext_amp_conf: ExternalAmplifierConfig = ext_amp_conf

        signal.signal(signal.SIGINT, self.signal_handler)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
        if (self.mqtt_user is not None) and (self.mqtt_pass is not None):
            self.client.username_pw_set(self.mqtt_user,
                                        password=self.mqtt_pass)
        self.client.will_set(f"{self.mqtt_base_topic}/state",
                             payload="offline",
                             retain=True)
        self.announcer = Announcer()
        self.announcer.on_status_change = self.status_change
Ejemplo n.º 2
0
    def __init__(self):
        """Initialize the game, and create game resources."""
        self.screen = turtle.Screen()
        self.screen.title("Pong")
        self.screen.bgcolor("black")
        self.screen.setup(width=800, height=600)
        self.screen.tracer(0)

        # Game assets
        self.sb = Scoreboard()
        self.announcer = Announcer()
        self.paddle_a = Paddle(-350, 0)
        self.paddle_b = Paddle(350, 0)
        self.ball = Ball()
        self.game_active = True

        # Keyboard bindings
        self.screen.listen()
        self.screen.onkeypress(self.paddle_a.start_move_up, 'w')
        self.screen.onkeypress(self.paddle_a.start_move_down, 's')
        self.screen.onkeyrelease(self.paddle_a.stop_move_up, 'w')
        self.screen.onkeyrelease(self.paddle_a.stop_move_down, 's')
        self.screen.onkeypress(self.paddle_a.start_long, 'r')
        self.screen.onkeypress(self.paddle_a.prime_fastball, 't')
        self.screen.onkeypress(self.paddle_b.start_move_up, 'Up')
        self.screen.onkeypress(self.paddle_b.start_move_down, 'Down')
        self.screen.onkeyrelease(self.paddle_b.stop_move_up, 'Up')
        self.screen.onkeyrelease(self.paddle_b.stop_move_down, 'Down')
        self.screen.onkeypress(self.paddle_b.start_long, ',')
        self.screen.onkeypress(self.paddle_b.prime_fastball, '.')
Ejemplo n.º 3
0
    def play_game(self):
        """Playing the game."""
        announcer = Announcer()
        diff = announcer.display_supported_difficulties()
        lang = announcer.ask_for_language()

        self.read_from_file(announcer.difficulty[diff][1][0],
                            announcer.difficulty[diff][1][1], lang)

        chosen_word = self.choose_word()
        hidden_word = self.hidden_word(chosen_word)
        won = False
        print("The word is: {}\n".format(" ".join(hidden_word)))

        while self.tries > 0 and not won:
            announcer.display_dashed_word()
            inp = announcer.ask_for_input()
            while self.letter_has_been_used(inp):
                print("You already used letter: '{}'".format(inp))
                inp = self.ask_for_input()
            self.used_letters.append(inp)
            print("Used letters: {}\n".format(sorted(self.used_letters)))

            if self.right_guess(chosen_word, hidden_word, inp):
                announcer.right_guess_feedback(inp, hidden_word)
            else:
                announcer.wrong_guess_feedback(inp, hidden_word)
                announcer.tries -= 1

            # Check if game has been won or not.
            if announcer.game_over_won(hidden_word):
                won = True
            elif announcer.tries == 0:
                announcer.game_over_lost(chosen_word)
                exit()
Ejemplo n.º 4
0
def main():
    # Setup
    pb = Pushbullet(os.getenv('PUSHBULLET_API_KEY'))
    logging.info('Connected to Pushbullet successfully.')

    def on_new(items, old):
        for title, city, prov, link, price, when, ships in items:
            message_body = (f'{title} at {price}€ in {city} {prov}.',
                            'Shipment available.' if ships else '',
                            f'Published {when}.', link)
            pb.push_note('Found new item',
                         '\n'.join([s for s in message_body if s]))
            logging.info('Pushed notification!')
            try:
                with open(OLD_FILE, 'w') as f:
                    f.write(repr(old))
            except IOError as err:
                logging.error(err)

    try:
        with open(OLD_FILE, 'r') as f:
            items = ast.literal_eval(f.read())
        logging.info('Old file loaded succesfully.')
    except IOError as err:
        logging.warning(err)
        logging.info('Couldn\'t load old file, fetching current ads...')
        html = get_all_ads_page()
        items = parse_ads(html)
        logging.info('Done.')

    announcer = Announcer(
        on_new=on_new,
        initial=items[:],
    )

    def job():
        logging.debug('Running main job.')
        try:
            logging.debug('Fetching ads...')
            html = get_all_ads_page()
            logging.debug('Fetched ads successfully.')
            items = parse_ads(html)
            announcer.submit(items)
        except ConnectionError:
            logging.warning('Couldn\' fetch ads.')
        except Exception as err:
            logging.error(err)

    # Configure scheduler
    logging.debug('Configuring scheduler')
    schedule.every().minute.do(job)
    logging.info('Entering main loop')
    logging.info(f'Looking for {SEARCH}')
    # Loop
    while (True):
        schedule.run_pending()
        time.sleep(1)
Ejemplo n.º 5
0
def main():
    parser = argparse.ArgumentParser(
        "Parse stdin, and make annnouncements based on that.")
    parser.add_argument('file1', metavar="Audio_file_for_without_mask")
    parser.add_argument('file2',
                        metavar="Audio_file_for_mask_worn_incorrectly")
    parser.add_argument(
        '--detect-interval',
        default=2.0,
        type=float,
        help='In seconds. For which the detector counts the result.')
    parser.add_argument(
        '--detect-threshold',
        default=0.0,
        type=float,
        help=
        'In [0, 1]. If the ratio is above this value, announcement will be made'
    )
    parser.add_argument(
        '--announce-interval',
        default=5.0,
        type=float,
        help=
        'In seconds. The announcer refrain from announce after announcing for this period of time'
    )
    args = parser.parse_args()
    d = Detector(time_interval=args.detect_interval,
                 check_threshold=args.detect_threshold,
                 announcers={
                     WITHOUT_MASK:
                     Announcer(args.file1,
                               time_interval=args.announce_interval),
                     MASK_WORN_INCORRECTLY:
                     Announcer(args.file2,
                               time_interval=args.announce_interval)
                 })
    d.watch()
Ejemplo n.º 6
0
def destalinate_job():
    print("Destalinating")
    if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
        print "ERR: Missing at least one Slack environment variable."
    else:
        warner = Warner()
        archiver = Archiver()
        announcer = Announcer()
        flagger = Flagger()
        print("Warning")
        warner.warn()
        print("Archiving")
        archiver.archive()
        print("Announcing")
        announcer.announce()
        print("Flagging")
        flagger.flag()
        print("OK: destalinated")
    print("END: destalinate_job")
Ejemplo n.º 7
0
 def __init__(self, pid, songconf):
     self._pid = pid
     self._scale = songconf["judgescale"]
     self._ann = Announcer(mainconfig["djtheme"])
Ejemplo n.º 8
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import config
from announcer import Announcer

inputs = "Pociąg osobowy do Grodziska Wielkopolskiego odjedzie z toru pierwszego przy peronie drugim"

inp2 = "Uzbrajanie systemu"


def status_change(message):
    print(message)


pa = Announcer(mp3_filename=config.mp3_filename,
               ext_amp_conf=config.ext_amplifier)
pa.on_status_change = status_change
pa.say(inp2, play_chime="gong")
Ejemplo n.º 9
0
    def __init__(self, pid, config, songconf, game):
        self.theme = GFXTheme(
            mainconfig.get("%s-theme" % game.theme, "default"), pid, game)
        self.pid = pid
        self.failed = False
        self.escaped = False

        self.__dict__.update(config)

        if self.speed < 0:
            self.target_bpm = -self.speed
        else:
            self.target_bpm = None

        self.game = game

        if self.scrollstyle == 2: self.top = 240 - game.width / 2
        elif self.scrollstyle == 1: self.top = 352
        else: self.top = 64

        self.secret_kind = songconf["secret"]

        self.score = scores.scores[songconf["scoring"]](pid, "NONE", game)
        self.combos = combos.combos[songconf["combo"]](pid, game)
        self.grade = grades.grades[songconf["grade"]]()
        Lifebar = lifebars.bars[songconf["lifebar"]]
        self.lifebar = Lifebar(pid, self.theme, songconf, game)
        self.judging_disp = JudgingDisp(self.pid, game)
        self.stats = stats.Stats()
        self.announcer = Announcer(mainconfig["djtheme"])

        self.listeners = [
            self.combos, self.score, self.grade, self.lifebar,
            self.judging_disp, self.stats, self.announcer
        ]

        if not game.double:
            self.judge = judge.judges[songconf["judge"]](self.pid, songconf)
            self.listeners.append(self.judge)
            arr, arrfx = self.theme.toparrows(self.top, self.pid)
            self.toparr = arr
            self.toparrfx = arrfx
            self.listeners.extend(arr.values() + arrfx.values())
            self.holdtext = HoldJudgeDisp(self.pid, self, self.game)
            self.listeners.append(self.holdtext)
        else:
            Judge = judge.judges[songconf["judge"]]
            self.judge = [
                Judge(self.pid * 2, songconf),
                Judge(self.pid * 2 + 1, songconf)
            ]
            self.listeners.extend(self.judge)
            arr1, arrfx1 = self.theme.toparrows(self.top, self.pid * 2)
            arr2, arrfx2 = self.theme.toparrows(self.top, self.pid * 2 + 1)
            self.arrows = [
                self.theme.arrows(self.pid * 2),
                self.theme.arrows(self.pid * 2 + 1)
            ]
            self.toparr = [arr1, arr2]
            self.toparrfx = [arrfx1, arrfx2]
            self.listeners.extend(arr1.values() + arr2.values() +
                                  arrfx1.values() + arrfx2.values())
            self.holdtext = [
                HoldJudgeDisp(self.pid * 2, self, self.game),
                HoldJudgeDisp(self.pid * 2 + 1, self, self.game)
            ]
            self.listeners.extend(self.holdtext)
Ejemplo n.º 10
0
 def setUp(self):
     self.announcer = Announcer()
            round(hourly_measurements[plant_id].water / measurement_count))
        average_temp = hourly_measurements[
            plant_id].temperature / measurement_count
        average_humidity = int(
            round(hourly_measurements[plant_id].humidity / measurement_count))
        average_light = int(
            round(hourly_measurements[plant_id].light / measurement_count))
        average_moisture = int(
            round(hourly_measurements[plant_id].moisture / measurement_count))
        global logic_layer
        light_on, water_time = logic_layer.commit_measurement(
            plant_id, average_water, average_temp, average_humidity,
            average_light, average_moisture)
        actuator_response = {'light_on': light_on, 'water_time': water_time}
        hourly_measurements[plant_id] = Measurement()
    return jsonify(actuator_response)


@app.route('/configure', methods=['POST'])
def configure():
    mac_address = request.values['mac_address']
    plant_id = logic_layer.configure(mac_address)
    response = {'plant_id': plant_id}
    return jsonify(response)


announcer_thread = Announcer()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)