def __init__(self, surface):
        self.surface = surface
        self.display = Display(self.surface)

        self.clock = pg.time.Clock()

        self.car_img_width = 66
        self.car_img_height = 142

        self.player = PlayerBuilder().get_player()
Beispiel #2
0
 def __init__(self):
     super().__init__()
     self.window_close = False
     self.display = Display(self.interface)
     self.map = None
     self.hero_acted = False
     self.sprites = self.interface.GroupSprite()
     self.level = 0
     self.last_level = 2
     self.animations = []
class PygameClient(PygameSocketGame):
    """
    This class connects the control and display for the game.
    You shouldn't need to make changes here.
    """
    def __init__(self,
                 width,
                 height,
                 frame_rate,
                 name,
                 title,
                 server_host="localhost",
                 server_port=20149):
        PygameSocketGame.__init__(self, title, width, height, frame_rate,
                                  server_host, server_port)
        self.name = name
        self.display = Display(width, height)
        self.control = Control(width, height)
        self.control.player_image = "duck2.png"

        # music_path = os.path.join('display', 'music', 'LukHash_-_ARCADE_JOURNEYS.wav')
        # pygame.mixer.music(music_path).play(-1)

        return

    def game_logic(self, keys, newkeys, buttons, newbuttons, mouse_position):
        self.control.control(self.engine, keys, newkeys, buttons, newbuttons,
                             mouse_position)

        if self.control.get_state() == CONTROL_STATE_WANT_DUAL:
            self.new_game(game_engine.MODE_DUAL)
        elif self.control.get_state() == CONTROL_STATE_WANT_SINGLE:
            self.new_game(game_engine.MODE_SINGLE)
        elif self.control.get_state() == CONTROL_STATE_WANT_TOURNAMENT:
            self.new_game(game_engine.MODE_TOURNAMENT)
        elif self.control.get_state() == CONTROL_STATE_WANT_VIEW:
            self.new_game(game_engine.MODE_VIEW)

        if self.engine and self.engine.get_data().get_game_over():
            self.game_over_pause += 1
            if self.game_over_pause > self.frames_per_second * POST_GAME_WAIT_TIME:
                self.disconnect_from_server()
                self.set_engine(None)
        return

    def paint(self, surface):
        self.display.paint(surface, self.engine, self.control)
        return

    def new_game(self, mode):
        self.set_engine(ClientGameEngine(self.name, mode))
        self.disconnect_from_server()
        self.connect_to_server()
        self.game_over_pause = 0
        return
class PygameClient(PygameSocketGame):
    """
    This class connects the control and display for the game.
    You shouldn't need to make changes here.
    """

    def __init__(self, width, height, frame_rate, name, title, server_host="localhost", server_port=20149):
        PygameSocketGame.__init__(self, title, width, height, frame_rate, server_host, server_port)
        self.name = name
        self.display = Display(width, height)
        self.control = Control(width, height)
        self.control.player_image = 'shooter3.png'
        #pygame.mixer.init()
        #pygame.mixer.music('display/sounds/background.wav')
        #pygame.mixer.music.play()
        sound_path = os.path.join('display', 'sounds', 'bac2.wav')
        pygame.mixer.Sound(sound_path).play(-1)
        return
    
    def game_logic(self, keys, newkeys, buttons, newbuttons, mouse_position):
        self.control.control(self.engine, keys, newkeys, buttons, newbuttons, mouse_position)

        if self.control.get_state() == CONTROL_STATE_WANT_DUAL:
            self.new_game(game_engine.MODE_DUAL)
        elif self.control.get_state() == CONTROL_STATE_WANT_SINGLE:
            self.new_game(game_engine.MODE_SINGLE)
        elif self.control.get_state() == CONTROL_STATE_WANT_TOURNAMENT:
            self.new_game(game_engine.MODE_TOURNAMENT)
        elif self.control.get_state() == CONTROL_STATE_WANT_VIEW:
            self.new_game(game_engine.MODE_VIEW)
        
        if self.engine and self.engine.get_data().get_game_over():
            self.game_over_pause += 1
            if self.game_over_pause > self.frames_per_second * POST_GAME_WAIT_TIME:
                self.disconnect_from_server()
                self.set_engine(None)
        return

    def paint(self, surface):
        self.display.paint(surface, self.engine, self.control)
        return
    
    def new_game(self, mode):
        self.set_engine(ClientGameEngine(self.name, mode))
        self.disconnect_from_server()
        self.connect_to_server()
        self.game_over_pause = 0
        return
Beispiel #5
0
def main() -> None:
    print('--- Ping Pong Pi Client starting... ---')
    print('> Server URL:    %s' % SERVER_URL)
    print('> Resource Type: %s' % RESOURCE_TYPE)
    print()

    config = ClientConfig(SERVER_URL)
    display = Display.get_display()
    input = Input.get_input()
    atexit.register(input.clear)
    atexit.register(display.clear)

    try:
        with Resource(RESOURCE_TYPE, config) as resource:
            input.register_key_handler(lambda: handle_input(resource))
            last_status = resource.get_status()
            display.show_message(last_status.name,
                                 get_color_for_status(last_status))
            while True:
                status = resource.get_status()
                if last_status != status:
                    print('Status changed to: %s' % status)
                    display.show_message(status.name,
                                         get_color_for_status(status))
                    last_status = status
                try:
                    sleep(1)
                except KeyboardInterrupt:
                    exit()
    except ConnectionError:
        display.show_message('Initial status check failed - stopping',
                             Color.RED)
Beispiel #6
0
    def initialize(self):
        Peripherals.init()
        if self.emulateSensor:
            self.sensor = FakeSensor()
        else:
            self.sensor = Sensor(Peripherals.devices["Pillow"])
        #self.led = LED(Peripherals.devices["Basestation"])
        #self.led.setLum(0, 0)

        actions.powerplug.PowerPlug.init()

        # toDo: ggf. zentraler Display Manager
        self.screenMult = 4
        #self.display = Display(self.screenMult*320, self.screenMult*240, self.isRaspberry)
        self.display = Display(1024, 600, self.isRaspberry)
        #self.graph = Graph(self.display, self.sensor)
        self.clock = Clock(self.display)
        self.settings = Settings(self.display)
        self.settings.onButton = self.onButton
        self.settings.onSetLight = self.onSetLight

        self.scheduler = Scheduler()
        # ToDo: Alarme in config File, periodisch auslesen
        self.scheduler.addAlarm("*", "7", "45",
                                actions.powerplug.PowerPlug.alarm)
Beispiel #7
0
    def __init__(self):
        self.board = ChessBoard()
        self.display = Display(self)
        self.player1 = PolicyPlayer(1, 2, self)
        self.player2 = PolicyPlayer(2, 1, self)

        super(PolicyPKPolicyGame, self).__init__(self.board, self.display,
                                                 self.player1, self.player2)
Beispiel #8
0
class PygameClient(PygameSocketGame):
    """
    This class connects the control and display for the game.
    You shouldn't need to make changes here.
    """

    def __init__(self, width, height, frame_rate, name, title, server_host="localhost", server_port=20149):
        PygameSocketGame.__init__(self, title, width, height, frame_rate, server_host, server_port)
        self.name = name
        self.display = Display(width, height)
        self.control = Control(width, height)
        return
    
    def game_logic(self, keys, newkeys, buttons, newbuttons, mouse_position):
        self.control.control(self.engine, keys, newkeys, buttons, newbuttons, mouse_position)

        if self.control.get_state() == CONTROL_STATE_WANT_DUAL:
            self.new_game(game_engine.MODE_DUAL)
        elif self.control.get_state() == CONTROL_STATE_WANT_SINGLE:
            self.new_game(game_engine.MODE_SINGLE)
        elif self.control.get_state() == CONTROL_STATE_WANT_TOURNAMENT:
            self.new_game(game_engine.MODE_TOURNAMENT)
        elif self.control.get_state() == CONTROL_STATE_WANT_VIEW:
            self.new_game(game_engine.MODE_VIEW)
        #elif self.control.get_state() == CONTROL_STATE_WANT_SELECT:
            self.new_game(game_engine.MODE_SELECT)
        
        if self.engine and self.engine.get_data().get_game_over():
            self.game_over_pause += 1
            if self.game_over_pause > self.frames_per_second * POST_GAME_WAIT_TIME:
                self.disconnect_from_server()
                self.set_engine(None)
        return

    def paint(self, surface):
        self.display.paint(surface, self.engine, self.control)
        return
    
    def new_game(self, mode):
        self.set_engine(ClientGameEngine(self.name, mode))
        self.disconnect_from_server()
        self.connect_to_server()
        self.game_over_pause = 0
        return
    def __init__(self,
                 width,
                 height,
                 frame_rate,
                 name,
                 title,
                 server_host="localhost",
                 server_port=20149):
        PygameSocketGame.__init__(self, title, width, height, frame_rate,
                                  server_host, server_port)
        self.name = name
        self.display = Display(width, height)
        self.control = Control(width, height)
        self.control.player_image = "duck2.png"

        # music_path = os.path.join('display', 'music', 'LukHash_-_ARCADE_JOURNEYS.wav')
        # pygame.mixer.music(music_path).play(-1)

        return
Beispiel #10
0
    def execute(self):
        display_init = Display(self.app_name, self.icon, self.display_size[0],
                               self.display_size[1])
        display_init.run()
        display = display_init.display

        app_quit = False

        while not app_quit:
            if self.state == States.menu:
                menu = Menu(self.app_name, display, self.display_size)
                self.state = States(menu.run())
            elif self.state == States.game:
                game = Game(self.app_name, display, self.display_size)
                self.state = States(game.run())
            elif self.state == States.settings:
                self.state = States(self.settings.run())
            elif self.state == States.app_exit:
                app_quit = True
Beispiel #11
0
 def _simulate_play(self, state):
     board = ChessBoard(self.game.board.width, self.game.board.height,
                        self.game.board.n_in_row, state)
     game = Game(board, None, None, None)
     display = Display(game)
     player1 = PolicyPlayer(self.other_index, self.index, game)
     player2 = PolicyPlayer(self.index, self.other_index, game)
     game.display = display
     game.player = game.player1 = player1
     game.player2 = player2
     game.mainloop()
     return display.win_player is not None and display.win_player.index == self.index
 def __init__(self, width, height, frame_rate, name, title, server_host="localhost", server_port=20149):
     PygameSocketGame.__init__(self, title, width, height, frame_rate, server_host, server_port)
     self.name = name
     self.display = Display(width, height)
     self.control = Control(width, height)
     self.control.player_image = 'shooter3.png'
     #pygame.mixer.init()
     #pygame.mixer.music('display/sounds/background.wav')
     #pygame.mixer.music.play()
     sound_path = os.path.join('display', 'sounds', 'bac2.wav')
     pygame.mixer.Sound(sound_path).play(-1)
     return
Beispiel #13
0
def main():
    try:
        opts, args = getopt.getopt(
            sys.argv[1:], "hs:lL:n:t:",
            ["help", "server=", "localhost", "logging=", "name=", "title="])
    except getopt.GetoptError as e:
        print(str(e))
        usage()
        sys.exit(1)

    show_help = False
    server = "rookie.cs.dixie.edu"
    name = DEFAULT_TEAM_NAME
    title = DEFAULT_GAME_TITLE
    logging_level = "error"
    for o, a in opts:
        if o in ("-h", "--help"):
            show_help = True
        elif o in ("-s", "--server"):
            server = a
        elif o in ("-l", "--localhost"):
            server = "127.0.0.1"
        elif o in ("-L", "--logging"):
            logging_level = a
        elif o in ("-n", "--name"):
            name = a
        elif o in ("-t", "--title"):
            title = a
        else:
            print("Unexpected option: %s" % (o))
            usage()
            sys.exit(1)
    if show_help:
        usage()
        sys.exit(1)

    if logging_level == "info":
        logging.basicConfig(level=logging.INFO)
    elif logging_level == "debug":
        logging.basicConfig(level=logging.DEBUG)
    elif logging_level == "warning":
        logging.basicConfig(level=logging.WARNING)
    elif logging_level == "error":
        logging.basicConfig(level=logging.ERROR)
    else:
        logging.basicConfig(level=logging.ERROR)

    display = Display(WINDOW_WIDTH, WINDOW_HEIGHT)
    control = Control(WINDOW_WIDTH, WINDOW_HEIGHT)
    g = PygameClient(display, control, WINDOW_WIDTH, WINDOW_HEIGHT,
                     FRAMES_PER_SECOND, name, title, server)
    g.main_loop()
    return
Beispiel #14
0
    def __init__(self):
        # Camera and display
        self.display = Display(SCREEN_WIDTH, SCREEN_HEIGHT)
        self.camera = CameraCapture()
        self.mqttClient = MqttClient(self.parsingPacket)

        self.teacherId = -1
        self.studentId = -1
        self.teacherStart = datetime.now()
        self.teacherTime = 0
        self.teacherDistance = 0
        self.studentStart = datetime.now()
        self.studentTime = 0
        self.studentDistance = 0
        self.studentLastTime = timedelta(seconds=0)
        self.studentLastDistance = 0

        # Face detection
        self.faceRecs = []
        self.showRecsCount = 0

        self.updateTime()
        self.updateCamera()
Beispiel #15
0
#!/usr/bin/python
# -*- coding:utf-8 -*-
import random
import time

from PIL import Image, ImageDraw

from display.display import Display
from display.symbols import Symbols

try:
    # w=104 h=212
    display = Display()

    X = Symbols.get_symbol('X')
    for i in range(0, 1000):
        display.print_symbol(X, random.randrange(0, 27), random.randrange(0, 13), display.black)
        display.print_symbol(X, random.randrange(0, 27), random.randrange(0, 13), display.yellow)
        display.show_on_hardware()

    # display.show_on_stub()
    # display.show_on_software()


except IOError as e:
    print(e)

except KeyboardInterrupt:
    exit()
Beispiel #16
0
    def __init__(self):
        self.display = Display()
        self.registration = Registration()

        self.on = False
        self.channels = []
        self.instance = vlc.Instance()
        self.log = vlc.Log()
        self.player = self.instance.media_player_new()
        self.events = self.player.event_manager()
        self.media = self.instance.media_new("")
        self.selectedChannel = None
        self.lastPowerState = None
        self.volume = int(os.environ["mnm_volume"])
        self.setVolume(self.volume)
        self.turnOnTime = None

        # A variable to hold the buffer timer.
        # Removes buffer from the state if there hasn't been sent another buffer event
        # since the timer started.
        self.bufferTimer = None

        # What the state was previous to buffering
        self.preBufferState = None

        # Is set when fetching channels. If it fails, we assume the server is down.
        self.serverUp = True

        # Bitrates
        # Put an int in the bitrate variable, and the stream closest to that bitrate will be used.
        # 32 kbps - Poor audio quality
        # 48 kbps - A reasonable lower end rate for longer speech-only podcasts
        # 64 kbps - A common bitrate for speech podcasts.
        # 128 kbps - Common standard for musical and high quality podcasts.
        # 320 kbps - Very high quality - almost indistinguishable from a CD.
        self.bitrate = int(os.environ["mnm_bitrate"])

        # Is set if the radio is updating (Dictionary)
        self.updating = None

        # String
        # Is set if there is a global error (ie. not related to channels)
        self.error = None

        # String
        # Is set if there is an error on the channel
        # Ie. if we couldn't open the channel
        self.channelError = None

        # State of radio (Dictionary)
        # { code: "buffering" || "ended" || "opening" || "paused" || "playing" || "stopped", text: "text description" }
        self.state = {"code": "starting", "text": _("Starting")}

        # When the user started listening. For analytics purposes.
        self.startedListeningTime = None

        self.saveListeningHistory = helpers.castToBool(
            os.environ["mnm_saveListeningHistory"])
        self.sendState = helpers.castToBool(os.environ["mnm_sendState"])

        # Listen for VLC events
        self.instance.log_set(logCallback, None)
        self.events.event_attach(vlc.EventType.MediaPlayerOpening,
                                 self.openingEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerBuffering,
                                 self.bufferingEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerPlaying,
                                 self.playingEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerPaused,
                                 self.pausedEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerStopped,
                                 self.stoppedEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerEndReached,
                                 self.endReachedEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerEncounteredError,
                                 self.errorEvent)
Beispiel #17
0
class Radio():
    def __init__(self):
        self.display = Display()
        self.registration = Registration()

        self.on = False
        self.channels = []
        self.instance = vlc.Instance()
        self.log = vlc.Log()
        self.player = self.instance.media_player_new()
        self.events = self.player.event_manager()
        self.media = self.instance.media_new("")
        self.selectedChannel = None
        self.lastPowerState = None
        self.volume = int(os.environ["mnm_volume"])
        self.setVolume(self.volume)
        self.turnOnTime = None

        # A variable to hold the buffer timer.
        # Removes buffer from the state if there hasn't been sent another buffer event
        # since the timer started.
        self.bufferTimer = None

        # What the state was previous to buffering
        self.preBufferState = None

        # Is set when fetching channels. If it fails, we assume the server is down.
        self.serverUp = True

        # Bitrates
        # Put an int in the bitrate variable, and the stream closest to that bitrate will be used.
        # 32 kbps - Poor audio quality
        # 48 kbps - A reasonable lower end rate for longer speech-only podcasts
        # 64 kbps - A common bitrate for speech podcasts.
        # 128 kbps - Common standard for musical and high quality podcasts.
        # 320 kbps - Very high quality - almost indistinguishable from a CD.
        self.bitrate = int(os.environ["mnm_bitrate"])

        # Is set if the radio is updating (Dictionary)
        self.updating = None

        # String
        # Is set if there is a global error (ie. not related to channels)
        self.error = None

        # String
        # Is set if there is an error on the channel
        # Ie. if we couldn't open the channel
        self.channelError = None

        # State of radio (Dictionary)
        # { code: "buffering" || "ended" || "opening" || "paused" || "playing" || "stopped", text: "text description" }
        self.state = {"code": "starting", "text": _("Starting")}

        # When the user started listening. For analytics purposes.
        self.startedListeningTime = None

        self.saveListeningHistory = helpers.castToBool(
            os.environ["mnm_saveListeningHistory"])
        self.sendState = helpers.castToBool(os.environ["mnm_sendState"])

        # Listen for VLC events
        self.instance.log_set(logCallback, None)
        self.events.event_attach(vlc.EventType.MediaPlayerOpening,
                                 self.openingEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerBuffering,
                                 self.bufferingEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerPlaying,
                                 self.playingEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerPaused,
                                 self.pausedEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerStopped,
                                 self.stoppedEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerEndReached,
                                 self.endReachedEvent)
        self.events.event_attach(vlc.EventType.MediaPlayerEncounteredError,
                                 self.errorEvent)

    def errorEvent(self, event=None):
        logger.error("errorEvent:, " + str(event))

    def endReachedEvent(self, event=None):
        logger.error(
            "The player reacher the end... Weird... Did you lose the internet connection? Trying to restart the stream."
        )
        self.state = {"code": "endReached", "text": _("Stopped sending")}

        # Try to start stream again if it's "ended".
        time.sleep(1)
        self.player.play()

    def stoppedEvent(self, event=None):
        logger.debug("Stopped")
        self.state = {"code": "stopped", "text": _("Stopped playing")}

    def pausedEvent(self, event=None):
        logger.debug("Paused")
        self.state = {"code": "paused", "text": _("Paused playing")}

    def playingEvent(self, event=None):
        logger.debug("Playing")
        self.state = {"code": "playing", "text": _("Playing")}

    def openingEvent(self, event=None):
        logger.debug("Opening")
        self.state = {"code": "opening", "text": _("Opening channel")}

    def bufferingEvent(self, event=None):
        # The buffering event is sent very often while buffering, so let's limit setting state to once
        if self.state["code"] != "buffering":
            logger.debug("Buffering")

            self.preBufferState = self.state

            self.state = {"code": "buffering", "text": _("Buffering...")}

        # Cancel timer for setting state back from "buffering" if it's been set
        if self.bufferTimer:
            self.bufferTimer.cancel()

        # Start a timer to replace the "buffering" state with the state from before it was set to buffering
        self.bufferTimer = threading.Timer(0.2, self.setPreBufferState)
        self.bufferTimer.start()

    def setPreBufferState(self):
        if self.preBufferState["code"] == "playing":
            self.playingEvent()
        elif self.preBufferState["code"] == "opening":
            self.openingEvent()
        else:
            logger.error(
                "We don't support setting state to the registered preBufferState ("
                + self.preBufferState["code"] + ")")

        self.state = self.preBufferState

    def playChannel(self, channel):
        # Channel should always be valid, so this clause shouldn't trigger, unless there is a bug.
        if not channel:
            logger.error(
                "Channel parameter is not a valid channel. Can't start player."
            )
            return

        # Before we update the selected channel, store the last played one
        playedChannel = self.selectedChannel

        self.selectedChannel = channel
        bestBitrateMatch = self.getBestBitRateMatch(channel["streams"])
        logger.debug("Playing " + channel["name"] + " with a bitrate of " +
                     str(channel["streams"][bestBitrateMatch]["bitrate"]) +
                     "kbps")

        self.player.stop()
        url = channel["streams"][bestBitrateMatch]["url"]
        self.media = self.instance.media_new(url)
        self.player.set_media(self.media)
        self.player.play()

        # Add the previous listen to the history
        self.addToListeningHistory(self.startedListeningTime, playedChannel,
                                   self.selectedChannel)

        # Note when we started listening
        self.startedListeningTime = int(round(time.time() * 1000))

    def play(self):
        self.playChannel(self.selectedChannel)

    def stop(self):
        # Only stop the radio if something is playing. Otherwise we will get an error
        # if the user turns of the radio when the radio isn't registered
        if self.selectedChannel:
            self.media = self.instance.media_new("")
            self.player.stop()
            self.addToListeningHistory(self.startedListeningTime,
                                       self.selectedChannel)

    def fetchChannels(self):
        db = TinyDB('./db/db.json')
        radioTable = db.table("Radio_mnm")
        radio = radioTable.get(doc_id=1)

        try:
            # Define status_code here, as if the request fails, we go straight
            # to the exception block, which evaluates status_code
            status_code = None

            headers = {"apiKey": radio["apiKey"]}
            response = requests.get(config.apiServer +
                                    "/radio/api/1/channels?homeId=" +
                                    radio["homeId"],
                                    headers=headers,
                                    verify=config.verifyCertificate,
                                    timeout=3)
            status_code = response.status_code
            response = response.json()

            if status_code == 200:
                logger.debug("Successfully fetched channels (" +
                             str(status_code) + ")")
                self.channels = response["channels"]

                # Add channels to the database for use in case the server goes down
                radioTable.update({"channels": self.channels}, doc_ids=[1])

                self.serverUp = True
            else:
                logger.error(
                    "Failed to fetch channels with HTTP error code: " +
                    str(status_code))
                raise Exception(response, status_code)
        except Exception:
            self.display.notification(_("Failed to get\n\rchannels!"))
            time.sleep(2)
            logger.exception(Exception)

            # If status_code is not set, the request failed before returning
            if not status_code:
                logger.debug(
                    "Got no channels from the server (most likely a timeout). Is the server up?"
                )
                self.serverUp = False
            elif status_code == 410:
                self.display.notification(_("This radio was\n\runregistered!"))
                time.sleep(3)
                self.display.notification(
                    _("Resetting radio\n\rin three seconds"))
                self.registration.reset()
                return

            # Recover by using channels from local db instead if we have them
            channels = radio["channels"]
            if channels:
                self.display.notification(_("Using local\n\rchannels instead"))
                time.sleep(1)
                self.channels = channels
            else:
                self.display.notification(
                    _("Couldn't get\n\rchannels!") + " (" + str(status_code) +
                    ")")
                logger.error("------------ EXITED ------------")
                time.sleep(1)
                # Exit with code "112, Host is down"
                sys.exit(112)

        # Only sets selectedChannel if it's not set and the radio has channels.
        # If not, keep the None value
        if not self.selectedChannel and len(self.channels) > 0:
            self.selectedChannel = self.channels[0]

        # self.playChannel(self.selectedChannel)

    # Bumps the channel n times. Loops around if bumping past the last channel.
    def bump(self, bumps=1):
        if not self.channels:
            logger.debug("Can't bump channel when there are none available.")
            return

        bumpTo = 0

        # Number of channels to skip which remains after removing overflow.
        # (Overflow: if you are playing channel 3 of 10 and is instructed to skip 202 channels ahead,
        # you would end up on channel 205. The overflow is 200, and we should return channel 5 (3 + 2))
        remaining = (len(self.channels) + bumps) % len(self.channels)
        selectedChannelIndex = self.channels.index(self.selectedChannel)

        if selectedChannelIndex + remaining > len(self.channels) - 1:
            bumpTo = selectedChannelIndex - len(self.channels) + remaining

        elif selectedChannelIndex + remaining < 0:
            bumpTo = len(self.channels) + selectedChannelIndex + remaining

        else:
            bumpTo = selectedChannelIndex + remaining

        logger.debug("bumps " + str(bumps) + ", bumping to: " + str(bumpTo))
        self.playChannel(self.channels[bumpTo])

    def setVolume(self, volume):
        try:
            subprocess.call(
                ["amixer", "-D", "pulse", "sset", "Master",
                 str(volume) + "%"])
            return True

        except ValueError:
            pass

    def getBestBitRateMatch(self, streams):
        bestMatchIndex = 0
        bestMatchBitrate = streams[0]["bitrate"]

        for i in range(len(streams)):
            if min(streams[i]["bitrate"] - self.bitrate,
                   streams[bestMatchIndex]
                   ["bitrate"]) - self.bitrate != bestMatchBitrate:
                bestMatchBitrate = streams[i]["bitrate"]
                bestMatchIndex = i

        return bestMatchIndex

    # TODO: Make async, so we don't have to wait for request to be sent before switching channels
    def addToListeningHistory(self,
                              startedListening,
                              playedChannel,
                              playingChannel=None):
        # Don't send requests if the server is (was) down
        if not self.serverUp:
            return False

        if not self.saveListeningHistory:
            return False

        db = TinyDB('./db/db.json')
        radioTable = db.table("Radio_mnm")
        radio = radioTable.get(doc_id=1)

        # PlayingChannel can be None. Ie. if we are stopping the player.
        if playingChannel == None:
            playingChannel = {"_id": None}

        data = {
            "homeId": radio["homeId"],
            "apiKey": radio["apiKey"],
            "playedChannelId": playedChannel["_id"],
            "playedChannelStartTime": startedListening,
            "playedChannelEndTime":
            int(round(time.time() * 1000)),  # Now in UNIX time
            "playingChannelId": playingChannel["_id"]
        }

        response = requests.post(config.apiServer +
                                 "/radio/api/1/listeningHistory",
                                 data=data,
                                 verify=config.verifyCertificate,
                                 timeout=5)

        status_code = response.status_code
        response = response.json()

        if status_code == 200:
            logger.debug("Successfully posted listening history (" +
                         str(status_code) + ")")
        else:
            logger.error("Couldn't post listening history: " +
                         str(status_code))

    # TODO: Make async, so we don't have to wait for request to be sent before turning off
    def handleSendState(self, state):
        # Don't send requests if the server is (was) down
        if not self.serverUp:
            return False

        if not self.sendState:
            return False

        db = TinyDB('./db/db.json')
        radioTable = db.table("Radio_mnm")
        radio = radioTable.get(doc_id=1)

        # Stop if radio doesn't exist (if device is registered)
        if not radio:
            logger.debug(
                "Can't post radio state to the API when the radio isn't registered."
            )
            return False

        data = {
            "homeId": radio["homeId"],
            "apiKey": radio["apiKey"],
            "state": state,
            "ip": socket.gethostbyname(socket.gethostname())
        }

        response = requests.post(config.apiServer + "/radio/api/1/state",
                                 data=data,
                                 verify=config.verifyCertificate,
                                 timeout=5)

        status_code = response.status_code
        response = response.json()

        if status_code == 200:
            logger.debug("Successfully posted state " + state + " (" +
                         str(status_code) + ")")
        else:
            logger.error("Couldn't post state: " + str(status_code))

    def handleError(self, error):
        if "VLC is unable to open the MRL" in error:
            print("Can't open channel")
            config.radio.channelError = {
                "text": _("Can't open channel (MRL)"),
                "code": "cantOpenMrl"
            }

        # This error seems to resolve itself or just doesn't impact the radio
        elif "PulseAudio server connection failure: Connection refused" in error:
            # config.radio.error = {
            # 	"text": _("Can't output audio"),
            # 	"code": "pulseaudio"
            # }
            return False

        elif "unimplemented query (264) in control" in error:
            # TODO: Figure out what this is
            return False

    class StreamMonitor(threading.Thread):
        def __init__(self, parent):
            threading.Thread.__init__(self)
            self.parent = parent
            self.running = True
            self.stopCount = 0

            # When paused is set, the thread will run, when it's not set, the thread will wait
            self.pauseEvent = threading.Event()

        def run(self):
            while self.running:
                time.sleep(1)

                # If the radio is on and stopped on several checks, something is wrong
                if self.parent.on and self.parent.state["code"] == "stopped":
                    self.stopCount = self.stopCount + 1

                    if self.stopCount > 3:
                        logger.error(
                            "Radio stopped for some reason. Lost Internet connection? Trying to restart..."
                        )
                        self.parent.player.stop()
                        self.parent.player.play()

                        self.stopCount = 0
                else:
                    self.stopCount = 0

                # Recover from channel errors
                if self.parent.channelError:
                    logger.debug("Trying to recover from channel error: " +
                                 self.parent.channelError["code"])
                    self.parent.channelError = None
                    self.parent.player.stop()
                    self.parent.player.play()

            if not self.running:
                return

        def stop(self):
            self.running = False
            print("Stopped the stream monitor loop")

    def startStreamMonitor(self):
        self.streamMonitor = self.StreamMonitor(self)
        self.streamMonitor.start()
Beispiel #18
0
 def __init__(self, width, height, frame_rate, name, title, server_host="localhost", server_port=20149):
     PygameSocketGame.__init__(self, title, width, height, frame_rate, server_host, server_port)
     self.name = name
     self.display = Display(width, height)
     self.control = Control(width, height)
     return
Beispiel #19
0
#!/usr/bin/python
# -*- coding:utf-8 -*-
import time

from PIL import Image, ImageDraw

from display.display import Display

try:
    # w=104 h=212
    display = Display()

    display.black.ellipse((26, 26, 78, 78), fill=0)
    display.yellow.ellipse((26, 52, 78, 104), fill=0)

    # display.show_on_hardware()
    display.show_on_software()
    # display.show_on_stub()

except IOError as e:
    print(e)

except KeyboardInterrupt:
    exit()
Beispiel #20
0
class Manage:
    def __init__(self):
        # Camera and display
        self.display = Display(SCREEN_WIDTH, SCREEN_HEIGHT)
        self.camera = CameraCapture()
        self.mqttClient = MqttClient(self.parsingPacket)

        self.teacherId = -1
        self.studentId = -1
        self.teacherStart = datetime.now()
        self.teacherTime = 0
        self.teacherDistance = 0
        self.studentStart = datetime.now()
        self.studentTime = 0
        self.studentDistance = 0
        self.studentLastTime = timedelta(seconds=0)
        self.studentLastDistance = 0

        # Face detection
        self.faceRecs = []
        self.showRecsCount = 0

        self.updateTime()
        self.updateCamera()

    #------------------ Parsing ------------------

    # Parsing data to info
    def parsingPacket(self, topic, packet):
        try:
            # Handle gps result
            if topic == GPS_TOPIC:
                gps = json.loads(packet)
                if (gps["command"] == "update"):
                    self.display.setLocation(str(gps["latitude"]),
                                             str(gps["longitude"]))

                    # Update distance
                    if self.teacherId > 0:
                        self.teacherDistance += gps["distance"]
                        self.display.setTeacherDistance(
                            str(self.teacherDistance))
                    # Student
                    if self.studentId > 0:
                        self.studentDistance += gps["distance"]
                        self.studentLastDistance += gps["distance"]
                        # Display
                        self.display.setStudentDistance(
                            str(self.studentDistance))
                        self.display.setStudentLastDistance(
                            str(self.studentLastDistance))

            # Handle RFID result
            elif topic == RFID_TOPIC:
                rfid = json.loads(packet)
                if (rfid["command"] == "update"):
                    self.manageCheckInOut(rfid["card_id"])

            # Face recognition result
            elif topic == FR_TOPIC:
                self.showRecsCount = 0
                f_r = json.loads(packet)
                self.faceRecs = f_r["face_list"]

        except:
            print("error packet == " + packet)

    #------------------ Update ------------------

    # Update current time
    def updateTime(self):
        now = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")  # Get current time
        self.display.setCurrentTime(now)  # Show current time
        self.display.parent.after(1000,
                                  self.updateTime)  # Call function after 1s

        # Update teacher time
        if self.teacherId > 0:
            time = datetime.now() - self.teacherStart
            self.display.setTeacherTime(str(time).split('.', 2)[0])

        # Update student time
        if self.studentId > 0:
            time = datetime.now() - self.studentStart
            self.studentLastTime += timedelta(seconds=1)
            # Display
            self.display.setStudentTime(str(time).split('.', 2)[0])
            self.display.setStudentLastTime(str(self.studentLastTime))

    # Stream camera
    def updateCamera(self):
        # Get a frame from the video source
        ret, frame = self.camera.get_frame()

        if ret:
            self.camera.save_frame(frame)

            # If face detected, show rectangles
            if len(self.faceRecs):
                try:
                    for faceRec in self.faceRecs:
                        x1 = faceRec["left"]
                        y1 = faceRec["top"]
                        x2 = faceRec["right"]
                        y2 = faceRec["bottom"]
                        if faceRec["person_id"] == self.studentId:
                            cv2.rectangle(frame, (x1, y1), (x2, y2),
                                          FACE_OK_COLOR, 2)
                        else:
                            cv2.rectangle(frame, (x1, y1), (x2, y2),
                                          FACE_ERROR_COLOR, 2)
                except:
                    print("Face ractangle invalid")
                    print(self.faceRecs)
                    self.faceRecs.clear()

            self.display.showCamera(frame)
        else:
            print("Cannot get camera frame")

        # Clear list after delay
        self.showRecsCount += 1
        if (self.showRecsCount > 5):
            self.faceRecs.clear()

        # Loop
        self.display.parent.after(10, self.updateCamera)

    #------------------ Check in/ out ------------------

    def clearTeacherInfo(self):
        self.teacherId = -1
        self.teacherStart = datetime.now()
        self.teacherDistance = 0
        # Display
        self.display.setTeacherName("")
        self.display.setTeacherStart("")
        self.display.setTeacherTime("")
        self.display.setTeacherDistance("")

    def clearStudentInfo(self):
        self.studentId = -1
        self.studentStart = datetime.now()
        self.studentDistance = 0
        # Display
        self.display.setStudentName("")
        self.display.setStudentStart("")
        self.display.setStudentTime("")
        self.display.setStudentDistance("")
        self.display.setStudentLastDistance("")
        self.display.setStudentLastTime("")

    def manageCheckInOut(self, card_id):
        for person in personList:
            if person["id"] == card_id:
                if person["type"] == "teacher":
                    # New or change teacher
                    if self.teacherId != card_id:
                        self.teacherId = card_id
                        self.teacherStart = datetime.now()
                        self.teacherDistance = 0
                        # Display
                        self.display.setTeacherName(person["name"])
                        self.display.setTeacherStart(
                            self.teacherStart.strftime("%m/%d/%Y, %H:%M:%S"))
                        self.display.setTeacherTime("00:00:00")
                        self.display.setTeacherDistance("0")
                        self.display.setNotify("")
                        print("Teacher checkin")

                    # Teacher checkout
                    else:
                        self.clearTeacherInfo()
                        self.clearStudentInfo()
                        print("Teacher checkout")

                if person["type"] == "student":
                    # Teacher is checkout
                    if self.teacherId != -1:
                        # New or change student
                        if self.studentId != card_id:
                            self.studentId = card_id
                            self.studentStart = datetime.now()
                            self.studentDistance = 0
                            self.studentLastTime = timedelta(
                                seconds=person["last_t"])
                            self.studentLastDistance = person["last_s"]

                            # Display
                            self.display.setStudentName(person["name"])
                            self.display.setStudentStart(
                                self.studentStart.strftime(
                                    "%m/%d/%Y, %H:%M:%S"))
                            self.display.setStudentTime("00:00:00")
                            self.display.setStudentDistance("0")
                            self.display.setStudentLastDistance(
                                str(self.studentLastDistance))
                            self.display.setStudentLastTime(
                                str(self.studentLastTime))
                            self.display.setNotify("")

                            # Send to verify id
                            data_set = {
                                "command": "update",
                                "card_list": [str(card_id)],
                                "numbs_card": 1
                            }
                            json_mess = json.dumps(data_set)
                            self.mqttClient.publish(FACE_VERIFY_TOPIC,
                                                    json_mess)
                            print("Student checkin")

                        # Student checkout
                        else:
                            self.clearStudentInfo()
                            print("Student checkout")

                    # Need a teacher before
                    else:
                        self.display.setNotify("Giảng viên cần check in trước")
Beispiel #21
0
#!/usr/bin/python
# -*- coding:utf-8 -*-
import time

from PIL import Image, ImageDraw

from display.display import Display
from display.symbols import Symbols

try:
    # w=104 h=212
    display = Display()

    A = Symbols.get_symbol('A')
    X = Symbols.get_symbol('X')
    NOT_A = Symbols.get_symbol('!A')

    display.print_symbol(A, 1, 0, display.black)
    display.print_symbol(X, 1, 1, display.black)
    display.print_symbol(NOT_A, 1, 2, display.black)

    display.print_symbol(A, 2, 0, display.yellow)
    display.print_symbol(X, 2, 1, display.yellow)
    display.print_symbol(NOT_A, 2, 2, display.yellow)

    display.black.rectangle((0, 24, 23, 31), fill=0)
    display.print_symbol(A, 3, 0, display.yellow)
    display.print_symbol(X, 3, 1, display.yellow)
    display.print_symbol(A, 3, 2, display.black)
    display.print_symbol(NOT_A, 3, 2, display.yellow)
Beispiel #22
0
class MainGame(Process):
    """ Process of main game with dungeons and level"""
    def __init__(self):
        super().__init__()
        self.window_close = False
        self.display = Display(self.interface)
        self.map = None
        self.hero_acted = False
        self.sprites = self.interface.GroupSprite()
        self.level = 0
        self.last_level = 2
        self.animations = []

    def new_level(self):
        """ Creating a new level - dungeon with new monsters """
        self.level += 1
        self.map = generate_map(self.level)
        self.map.spawn()
        self.map.render_map()

        self.sprites.clear()
        self.sprites.add(self.map.exit)
        for monster in self.map.mobs.values():
            self.sprites.add(monster)

        self.map.hero.center_camera(self.display)

    def main_loop(self):
        """ Main loop of program - processing each tick/frame of game """
        self.new_level()
        while not self.window_close:
            self.process_events()
            self.game_logic()
            self.draw()
            self.display.update()
            self.interface.wait(settings.frame_wait)

    def is_animation(self):
        """ Checks is there any animation proceeding """
        if self.map.hero.animation:
            return True
        for m in self.map.mobs.values():
            if m.animation:
                return True
        if len(self.animations) > 0:
            return True
        return False

    def process_events(self):
        """ Processing all events - clicking buttons - and respectively moving objects by commands """
        events = self.interface.Event.get_event()
        for event in events:
            event_type = self.interface.Event.get_event_type(event)
            if event_type == settings.quit_flag:
                self.window_close = True
            if event_type == settings.keydown_flag:
                event_key = self.interface.Event.get_key(event)
                if event_key == settings.escape_key:
                    self.display.fullscreen()
                if not self.is_animation():
                    self.hero_acted = self.map.hero.act(event_key, self.map)

    def game_logic(self):
        """ Automatic move of objects/units/monsters, checking collisions, and other game logic """
        if self.is_animation():
            return
        if isinstance(self.hero_acted, list):
            self.animations.append(
                swipe_animation(self.display, self.hero_acted))
            self.animations.append(shake_screen_animation(self.display))
        if self.hero_acted:
            self.monsters_turn()
            self.hero_acted = False
        self.map.exit.react(self.map)
        self.check_new_level()
        self.kill_mobs()

    def draw(self):
        """ Drawing all objects to the window """
        self.display.screen_fill(settings.colors["BLACK"])

        self.sprites.update(self.display)
        self.map.update(self.display)

        self.map.draw(self.display)
        self.sprites.draw(self.display)

        self.do_animations()

    def monsters_turn(self):
        """ Do the monsters turn - all of them acting """
        current_monsters = list(self.map.mobs.values())
        for monster in current_monsters:
            if monster != self.map.hero:
                monster.act(self.map)

    def check_new_level(self):
        """ Check if hero reached exit on current level """
        if self.map.is_reached_exit():
            if self.last_level == self.level:
                self.window_close = True
                return
            self.display.fade(False)
            self.new_level()
            self.draw()
            self.display.fade(True)

    def kill_mobs(self):
        """ Kills all mobs with hp less then 0 """
        now_mobs = list(self.map.mobs.values())
        for mob in now_mobs:
            if not mob.is_alive():
                self.sprites.erase(mob)
                self.map.erase_mob(mob)

    def do_animations(self):
        for anim in self.animations:
            try:
                next(anim)
            except StopIteration:
                self.animations.remove(anim)
Beispiel #23
0
  print('| mode 5: show boxplot               |')
  print('| mode 6: show scatter               |')
  print('| mode 7: show scatter (one pos)     |')
  print('--------------------------------------')
  mode = input('Enter a mode(0~7) or -1 to exit this program: ')
  mode = int(mode)
  
  if mode == 0:
    if my_display:
      my_display.reset()
    # Unused position
    pos_list = []
    # Unused time
    time = ['2020 02 02', '2020 02 03']
    # create a Display object
    my_display = Display(pos_list, time)
    # get and print recent data
    my_display.get_all_data()
    my_display.print_recent_data()
    break

  elif mode == 1:
    if my_display:
      my_display.reset()
    # input time & a position
    time = input_time()
    pos_list = input_pos(multiple=False)
    # create a Display object
    my_display = Display(pos_list, time)
    # plt
    my_display.get_data_by_pos()
Beispiel #24
0
from display.display import Display
import config

if __name__ == "__main__":
    server = Display(config)
    #server.run()
from buttons.push import add_buttons_events


GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

DISPLAY_SLEEP = 0.2
CONVEY_LIMIT = 5
UPDATE_API_CYCLES_COUNT = 50


def get_api_data():
    return int(client.get_stats()['current'])


display = Display()
counter = get_api_data()


def reset_callback(channel):
    print("Button 'RESET was pushed!")
    global counter
    counter = 0
    display.setValue(counter)
    client.reset()


def enter_callback(channel):
    print("Button '+1' was pushed!")
    global counter
    counter += 1
Beispiel #26
0
# Read about what each thing does in the respective class
# !!! WARNING !!! The game will break if the level does not contain the player ("C") within; the game may break if the door Top and Bottom is not found as well.

import pygame

from Entities.player import Player
from Entities.platform import Platform
from Entities.door import Door
from Entities.coins import Coins
from Entities.spike import Spike
from Entities.trophies import Trophy
from display.display import Display
from BuildFunctions.directory import Directory

Display = Display()
Directory = Directory()


class LevelLoader(object):
    """
    This class actually handles a lot of things; while also handling the level loading, it also must be used to call from another class in the game
    class itself.  For example, to use anything from the Player class, the user must have LevelLoader()getPlayer().functionHere.
    In all honesty, this class handles pretty much everything that has anything to do with levels.
    """
    def __init__(self):
        self.level = 0
        self.platforms = []

        self.doorsClosed = True

        self.entities = pygame.sprite.Group()
class SinglePlayerEngine:
    def __init__(self, surface):
        self.surface = surface
        self.display = Display(self.surface)

        self.clock = pg.time.Clock()

        self.car_img_width = 66
        self.car_img_height = 142

        self.player = PlayerBuilder().get_player()

    def game_loop(self):
        NUM_OBSTACLES = 4
        obstacle_manager = ObstacleManager()
        obstacle_manager.generate_random_obstacles(NUM_OBSTACLES)

        level = 1
        target_score = 10

        while self.player.lives > 0:
            self.display.clear()
            self.display.draw_level(level)
            is_next_level = self.round_start(target_score, obstacle_manager)

            if is_next_level:
                level += 1
                self.player.level_up()
                obstacle_manager.level_up()
            else:
                self.player.lives -= 1
                self.display.draw_crash()

        self.display.draw_game_over()

    def round_start(self, target_score, obstacle_manager):
        '''Returns True if target_score has been reach or False if collision happened'''
        self.player.reset()
        obstacle_manager.reset_all()

        is_collision = False
        round_score = 0

        while not is_collision and round_score < target_score:

            for event in pg.event.get():
                if event.type == pg.QUIT:
                    pg.quit()
                    quit()

                pressed_keys = pg.key.get_pressed()
                self.player.update_key(pressed_keys)

            self.display.clear()

            self.player.update()
            # update coordinates and draw obstacles
            round_score += obstacle_manager.update(self.surface)
            obstacle_manager.draw_all(self.surface)

            self.player.draw(self.surface)
            self.display.draw_score(round_score)
            self.display.draw_lives(self.player.lives)
            self.display.update()

            is_collision = is_collision_with_any_obstacle(self.player.car, obstacle_manager.obstacle_list)

            # pg.display.update(xxx) - updates a specific object
            # pg.display.update() - updates entire surface
            # pg.display.flip() - updates entire surface

            self.clock.tick(settings.FPS)

        if is_collision:
            return False
        else:
            return True