Exemple #1
0
    async def __sendWelcomeMessage(self, host, room: str) -> bool:
        """Send welcome message with current status

        Parameters
        ----------
        host : string
            hostname of spacestatus-server instance
        room : string
            room id

        Returns
        -------
        bool
        """
        # Set welcome phrase to name and state
        welcomePhrase = \
            "Spacestatus started for %s. Current status is %s." % (
                data().getSpace(host),
                "OPEN" if data().getStateOpen(host) else "CLOSED"
            )

        # Try to join new room and haven't joined as that user, you can use
        # Joining if already joined will also be successfull
        joinResponse = await self.__matrixApi[host].join(room)
        if not isinstance(joinResponse, nio.JoinResponse):
            # Join to channel failed
            self.__matrixApi.pop(host)
            print('ERROR: Matrix join to room %s for %s failed.' %
                  (room, host),
                  file=sys.stderr)
            return False

        # Push status message to matrix
        messageResponse = await self.__matrixApi[host].room_send(
            room,
            message_type="m.room.message",
            content={
                "msgtype": "m.notice",
                "body": welcomePhrase
            })

        if isinstance(messageResponse, nio.RoomSendResponse):
            print('MATRIX: Welcome message for %s send successfully.' % host)
            return True
        else:
            # Cached session credetials invalid,
            # remove instance and output error message
            self.__matrixApi.pop(host)
            print('ERROR: Matrix cached session for %s is not valid.' % (host),
                  file=sys.stderr)
            return False
Exemple #2
0
def __updateTemperature(host: str, received: dict):
    """Update sensor temperature data

    Parameters
    ----------
    received : dict
        Received api data
    """
    try:
        if len(received['sensors']['temperature']) > 0:
            data().setSensorsTemperature(host,
                                         received['sensors']['temperature'])
        else:
            data().removeSensorsTemperature(host)
    except KeyError:
        pass
Exemple #3
0
def setTemperature(received: dict):
    """Set data received by api

    Parameters
    ----------
    received : dict
        Received api data
    """
    # Get requested host
    host = connexion.request.headers['Host']

    # Update current sensor temperature data
    __updateTemperature(host, received)

    data().commit(host)

    return connexion.NoContent, 200
Exemple #4
0
def status() -> dict:
    """Response the request for /status.json with the complete api output.

    Returns
    -------
    dict
        Dictionary with all api data for the requested host
    """
    return data().get(connexion.request.headers['Host'])
Exemple #5
0
def home() -> str:
    """
    Response the request for / with a rendered html page

    Returns
    -------
    string
        Rendered output of home.html
    """
    return \
        flask.render_template(
            'home.html',
            data=data().get(connexion.request.headers['Host'], True)
        )
Exemple #6
0
def statusMinimal() -> dict:
    """
    Response the request for /status-minimal.json with
    a minimal status output.

    Returns
    -------
    dict
        Dictionary with minimal status data for the requested host
    """
    json = data().get(connexion.request.headers['Host'])
    minimal = {
        'open':
        json['state']['open'],
        'icon':
        json['state']['icon']['open']
        if json['state']['open'] else json['state']['icon']['closed']
    }
    return minimal
Exemple #7
0
    async def __onStateOpenChangeAsync(self, stateOpen: bool) -> bool:
        """Send status message async

        Parameters
        ----------
        stateOpen : bool
            current status

        Returns
        -------
        bool
        """

        # Set phrase to name and state
        phrase = \
            "%s is %s." % (
                data().getSpace(self._getHost()),
                "open" if stateOpen else "closed"
            )

        # Push status message to matrix
        messageResponse = await self.__getMatrixApi().room_send(
            self.__getRoom(),
            message_type="m.room.message",
            content={
                "msgtype": "m.notice",
                "body": "%s" % phrase
            })

        if isinstance(messageResponse, nio.RoomSendResponse):
            print('MATRIX: Send message "%s" for host %s successfull.' %
                  (phrase, self._getHost()))
            return True
        else:
            # Error sending message
            print('ERROR: Send status message to Matrix for %s failed: %s' %
                  (self._getHost(), messageResponse),
                  file=sys.stderr)
            return False
Exemple #8
0
def set(received: dict):
    """Set data received by api

    Parameters
    ----------
    received : dict
        Received api data
    """
    # Get requested host
    host = connexion.request.headers['Host']

    # Update current sensor people data
    data().setSensorsPeople(host, received['sensors']['people_now_present'])

    # Update current sensor temperature data
    __updateTemperature(host, received)

    # Update open state if changes
    if (data().getStateOpen(host) != received['state']['open']):
        data().setStateOpen(host, received['state']['open'])
        # Run plugin hook
        pluginCollection().onStateOpenChange(received['state']['open'])

    # Update or remove state message
    try:
        data().setStateMessage(host, received['state']['message'])
    except KeyError:
        data().setStateMessage(host, None)

    data().setStateLastchange(host, received['state']['lastchange'])
    data().commit(host)

    return connexion.NoContent, 200