Пример #1
0
class Logs(object):
	def __init__(self):
		self.config = Config()

	def init_pubnub(func):
		def wrapper(self, *args, **kwargs):
			if not hasattr(self, 'pubnub'):
				pubnub_key = self.config.get_pubnub_keys()
				self.pubnub = Pubnub(publish_key=pubnub_key['publish_key'], subscribe_key=pubnub_key['subscribe_key'])
			return func(self, *args, **kwargs)
		return wrapper

	@init_pubnub
	def subscribe(self, uuid, callback, error):
		channel = self.get_channel(uuid)
		self.pubnub.subscribe(channels=channel, callback=callback, error=error)

	@init_pubnub
	def history(self, uuid, callback, error):
		channel = self.get_channel(uuid)
		self.pubnub.history(channel=channel, callback=callback, error=error)

	def unsubscribe(self, uuid):
		if hasattr(self, 'pubnub'):
			channel = self.get_channel(uuid)
			self.pubnub.unsubscribe(channel=channel)

	@staticmethod
	def get_channel(uuid):
		return 'device-{uuid}-logs'.format(uuid=uuid)
Пример #2
0
class Logs(object):
    """
    This class implements functions that allow processing logs from device.

    This class is implemented using pubnub python sdk.

    For more details about pubnub, please visit: https://www.pubnub.com/docs/python/pubnub-python-sdk

    """
    def __init__(self):
        self.config = Config()

    def _init_pubnub(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            if not hasattr(self, 'pubnub'):
                pubnub_key = self.config.get_all()['pubnub']
                self.pubnub = Pubnub(publish_key=pubnub_key['publish_key'],
                                     subscribe_key=pubnub_key['subscribe_key'])
            return func(self, *args, **kwargs)

        return wrapper

    @_init_pubnub
    def subscribe(self, uuid, callback, error):
        """
        This function allows subscribing to device logs.
        Testing

        Args:
            uuid (str): device uuid.
            callback (function): this callback is called on receiving a message from the channel.
            error (function): this callback is called on an error event.
            For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#subscribe

        Examples:
            >>> def callback(message, channel):
            ... print(message)

            >>> def error(message):
            ... print('Error:'+ str(message))

            >>> Logs.subscribe(uuid=uuid, callback=callback, error=error)

        """

        channel = self.get_channel(uuid)
        self.pubnub.subscribe(channels=channel, callback=callback, error=error)

    @_init_pubnub
    def history(self, uuid, callback, error):
        """
        This function allows fetching historical device logs.

        Args:
            uuid (str): device uuid.
            callback (function): this callback is called on receiving a message from the channel.
            error (function): this callback is called on an error event.
            For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#history

        Examples:
            >>> def callback(message):
            ... print(message)

            >>> def error(message):
            ... print('Error:'+ str(message))

            Logs.history(uuid=uuid, callback=callback, error=error)

        """

        channel = self.get_channel(uuid)
        self.pubnub.history(channel=channel, callback=callback, error=error)

    def unsubscribe(self, uuid):
        """
        This function allows unsubscribing to device logs.

        Args:
            uuid (str): device uuid.

        """

        if hasattr(self, 'pubnub'):
            channel = self.get_channel(uuid)
            self.pubnub.unsubscribe(channel=channel)

    @staticmethod
    def get_channel(uuid):
        """
        This function returns pubnub channel for a specific device.

        Args:
            uuid (str): device uuid.

        Returns:
            str: device channel.

        """

        return 'device-{uuid}-logs'.format(uuid=uuid)
Пример #3
0
class Logs(object):
    """
    This class implements functions that allow processing logs from device.

    This class is implemented using pubnub python sdk.

    For more details about pubnub, please visit: https://www.pubnub.com/docs/python/pubnub-python-sdk

    """

    def __init__(self):
        self.config = Config()

    def _init_pubnub(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            if not hasattr(self, 'pubnub'):
                pubnub_key = self.config.get_all()['pubnub']
                self.pubnub = Pubnub(
                    publish_key=pubnub_key['publish_key'],
                    subscribe_key=pubnub_key['subscribe_key']
                )
            return func(self, *args, **kwargs)
        return wrapper

    @_init_pubnub
    def subscribe(self, uuid, callback, error):
        """
        This function allows subscribing to device logs.
        Testing

        Args:
            uuid (str): device uuid.
            callback (function): this callback is called on receiving a message from the channel.
            error (function): this callback is called on an error event.
            For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#subscribe

        Examples:
            >>> def callback(message, channel):
            ... print(message)

            >>> def error(message):
            ... print('Error:'+ str(message))

            >>> Logs.subscribe(uuid=uuid, callback=callback, error=error)

        """

        channel = self.get_channel(uuid)
        self.pubnub.subscribe(channels=channel, callback=callback, error=error)

    @_init_pubnub
    def history(self, uuid, callback, error):
        """
        This function allows fetching historical device logs.

        Args:
            uuid (str): device uuid.
            callback (function): this callback is called on receiving a message from the channel.
            error (function): this callback is called on an error event.
            For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#history

        Examples:
            >>> def callback(message):
            ... print(message)

            >>> def error(message):
            ... print('Error:'+ str(message))

            Logs.history(uuid=uuid, callback=callback, error=error)

        """

        channel = self.get_channel(uuid)
        self.pubnub.history(channel=channel, callback=callback, error=error)

    def unsubscribe(self, uuid):
        """
        This function allows unsubscribing to device logs.

        Args:
            uuid (str): device uuid.

        """

        if hasattr(self, 'pubnub'):
            channel = self.get_channel(uuid)
            self.pubnub.unsubscribe(channel=channel)

    @staticmethod
    def get_channel(uuid):
        """
        This function returns pubnub channel for a specific device.

        Args:
            uuid (str): device uuid.

        Returns:
            str: device channel.

        """

        return 'device-{uuid}-logs'.format(uuid=uuid)
Пример #4
0
def main():
    chatroom = input("Please enter the name of chat room you want to enter: ")
    user_name = input("Please enter your name: ")
    print("Hello {}. Welcome to {} chatroom".format(user_name, chatroom))

    pn = Pubnub(publish_key="demo",
                subscribe_key="demo",
                ssl_on=False,
                uuid=user_name)

    channel = chatroom

    def _callback(message, channel):
        if message['user_name'] != user_name:
            print("\n{}: {}".format(message['user_name'], message['message']))
            print("{}: ".format(user_name))

    # def _presence_callback(message):
    #     print(message)
    #     if message['action'] == 'join':
    #         print("\n{} joined...".format(message['uuid']))
    #
    #     if message['action'] == 'leave':
    #         print("\n{} left...".format(message['uuid']))

    def _error(error):
        print(error)

    def _history_callback(message):
        for msg in message[0]:
            print("\n{}: {}".format(msg['user_name'], msg['message']))

    def _whosonline_callback(message):
        print("Following are online :")
        print("-------------")
        for msg in message['uuids']:
            print(msg)

    def _howmanyonline_callback(message):
        print("\n{} online...".format(message['occupancy']))

    def get_input():
        message = input("{}: ".format(user_name))

        if str(message) in ['quit', 'QUIT', 'Quit', 'exit', 'Exit', 'EXIT']:
            print("Quitting...")
            pn.unsubscribe(channel=channel)
            sys.stdout.flush()
            os._exit(0)
        elif str(message) in ['whosonline', 'whoisonline']:
            pn.here_now(channel=channel,
                        callback=_whosonline_callback,
                        error=_error)
        elif str(message) in ['howmanyonline']:
            pn.here_now(channel=channel,
                        callback=_howmanyonline_callback,
                        error=_error)
        else:
            msg_object = dict(user_name=user_name, message=message)
            pn.publish(channel=channel, message=msg_object)

    pn.subscribe(channels=channel, callback=_callback)

    # presence_channel = "{}-pnpres".format(channel)
    # pn.subscribe(channels=presence_channel, callback=_presence_callback)

    pn.history(channel=channel,
               count=100,
               callback=_history_callback,
               error=_error)

    while True:
        get_input()
Пример #5
0
cipher_key = len(sys.argv) > 4 and sys.argv[4] or ''
ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False

# -----------------------------------------------------------------------
# Initiate Pubnub State
# -----------------------------------------------------------------------
pubnub = Pubnub(publish_key=publish_key,
                subscribe_key=subscribe_key,
                secret_key=secret_key,
                cipher_key=cipher_key,
                ssl_on=ssl_on)
channel = 'a'

# Synchronous usage

print(pubnub.history(channel, count=2))

# Asynchronous usage


def callback(message):
    print(message)


pubnub.history(channel, count=2, callback=callback, error=callback)

# Synchronous usage

print(pubnub.history(channel, count=2, include_token=True))

# Asynchronous usage
Пример #6
0
class Logs(object):
    """
    This class implements functions that allow processing logs from device.

    This class is implemented using pubnub python sdk.

    For more details about pubnub, please visit: https://www.pubnub.com/docs/python/pubnub-python-sdk

    """
    def __init__(self):
        self.config = Config()
        self.device = Device()

    def _init_pubnub(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            if not hasattr(self, 'pubnub'):
                pubnub_key = self.config.get_all()['pubnub']
                self.pubnub = Pubnub(publish_key=pubnub_key['publish_key'],
                                     subscribe_key=pubnub_key['subscribe_key'])
            return func(self, *args, **kwargs)

        return wrapper

    @_init_pubnub
    def subscribe(self, uuid, callback, error):
        """
        This function allows subscribing to device logs.
        There are fields (`m`, `t`, `s`, `c`) in the output which can be unclear. They stand for:
            m - The log message itself.
            t - The log timestamp.
            s - Is this a system message?
            c - The id of the service which produced this log (or null if the device does not support multiple containers).

        Args:
            uuid (str): device uuid.
            callback (function): this callback is called on receiving a message from the channel.
            error (function): this callback is called on an error event.
            For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#subscribe

        Examples:
            # Define callback and error.
            >>> def callback(message, channel):
            ...     print(message)
            >>> def error(message):
            ...     print('Error:'+ str(message))
            >>> Logs.subscribe(uuid=uuid, callback=callback, error=error)

        """

        channel = self.get_channel(uuid)
        self.pubnub.subscribe(channels=channel, callback=callback, error=error)

    @_init_pubnub
    def history(self, uuid, callback, error):
        """
        This function allows fetching historical device logs.

        Args:
            uuid (str): device uuid.
            callback (function): this callback is called on receiving a message from the channel.
            error (function): this callback is called on an error event.
            For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#history

        Examples:
            # Define callback and error.
            >>> def callback(message):
            ...     print(message)
            >>> def error(message):
            ...     print('Error:'+ str(message))
            Logs.history(uuid=uuid, callback=callback, error=error)

        """

        channel = self.get_channel(uuid)
        self.pubnub.history(channel=channel, callback=callback, error=error)

    def unsubscribe(self, uuid):
        """
        This function allows unsubscribing to device logs.

        Args:
            uuid (str): device uuid.

        """

        if hasattr(self, 'pubnub'):
            channel = self.get_channel(uuid)
            self.pubnub.unsubscribe(channel=channel)

    def get_channel(self, uuid):
        """
        This function returns pubnub channel for a specific device.

        Args:
            uuid (str): device uuid.

        Returns:
            str: device channel.

        """

        if not hasattr(self, 'logs_channel'):
            device_info = self.device.get(uuid)
            if 'logs_channel' in device_info:
                self.logs_channel = device_info['logs_channel']
            else:
                self.logs_channel = uuid

        return 'device-{logs_channel}-logs'.format(
            logs_channel=self.logs_channel)
Пример #7
0
publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
cipher_key = len(sys.argv) > 4 and sys.argv[4] or ''
ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False

# -----------------------------------------------------------------------
# Initiate Pubnub State
# -----------------------------------------------------------------------
pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key,
                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on)
channel = 'a'

# Synchronous usage

print(pubnub.history(channel, count=2))

# Asynchronous usage


def callback(message):
    print(message)

pubnub.history(channel, count=2, callback=callback, error=callback)

# Synchronous usage

print(pubnub.history(channel, count=2, include_token=True))

# Asynchronous usage