Beispiel #1
0
    def test_subscribe_pub_unsubscribe(self):
        ch = helper.gen_channel("test-subscribe-sub-pub-unsub")
        pubnub = PubNub(pnconf_sub_copy())
        subscribe_listener = SubscribeListener()
        publish_operation = NonSubscribeListener()
        message = "hey"

        try:
            pubnub.add_listener(subscribe_listener)

            pubnub.subscribe().channels(ch).execute()
            subscribe_listener.wait_for_connect()

            pubnub.publish().channel(ch).message(message).async(publish_operation.callback)

            if publish_operation.await() is False:
                self.fail("Publish operation timeout")

            publish_result = publish_operation.result
            assert isinstance(publish_result, PNPublishResult)
            assert publish_result.timetoken > 0

            result = subscribe_listener.wait_for_message_on(ch)
            assert isinstance(result, PNMessageResult)
            assert result.channel == ch
            assert result.subscription is None
            assert result.timetoken > 0
            assert result.message == message

            pubnub.unsubscribe().channels(ch).execute()
            subscribe_listener.wait_for_disconnect()
Beispiel #2
0
def startStockPicker(server,port):
    global globalQueueRef

    mongoconn = MongoClient(server, port)
    db = mongoconn.stockdb
    coll = db.stockcollection

    coll.create_index([('time', pymongo.DESCENDING)])

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = 'sub-c-f271816a-f3c4-11e6-88c3-0619f8945a4f'
    pnconfig.publish_key = 'pub-c-b4be713a-be4f-4872-b5c8-6232f76df1d4'
    pnconfig.ssl = False
    pb = PubNub(pnconfig)

    # metaDataInit(coll)

    updateTime = 10
	numOfItems = 4
    def test_add_remove_multiple_channels(self):
        ch1 = "channel-groups-unit-ch1"
        ch2 = "channel-groups-unit-ch2"
        gr = "channel-groups-unit-cg"
        pubnub = PubNub(pnconf_copy())

        # add
        envelope = pubnub.add_channel_to_channel_group() \
            .channels([ch1, ch2]) \
            .channel_group(gr) \
            .sync()

        assert isinstance(envelope.result, PNChannelGroupsAddChannelResult)

        time.sleep(1)

        # list
        envelope = pubnub.list_channels_in_channel_group() \
            .channel_group(gr) \
            .sync()

        assert isinstance(envelope.result, PNChannelGroupsListResult)
        assert len(envelope.result.channels) == 2
        assert ch1 in envelope.result.channels
        assert ch2 in envelope.result.channels

        # remove
        envelope = pubnub.remove_channel_from_channel_group() \
            .channels([ch1, ch2]) \
            .channel_group(gr) \
            .sync()

        assert isinstance(envelope.result, PNChannelGroupsRemoveChannelResult)

        time.sleep(1)

        # list
        envelope = pubnub.list_channels_in_channel_group() \
            .channel_group(gr) \
            .sync()

        assert isinstance(envelope.result, PNChannelGroupsListResult)
        assert len(envelope.result.channels) == 0
    def test_multiple_channels(self):
        ch1 = "state-native-sync-ch-1"
        ch2 = "state-native-sync-ch-2"
        pubnub = PubNub(pnconf_copy())
        pubnub.config.uuid = "state-native-sync-uuid"
        state = {"name": "Alex", "count": 5}

        envelope = pubnub.set_state().channels([ch1, ch2]).state(state).sync()

        assert isinstance(envelope.result, PNSetStateResult)
        assert envelope.result.state['name'] == "Alex"
        assert envelope.result.state['count'] == 5

        envelope = pubnub.get_state().channels([ch1, ch2]).sync()

        assert isinstance(envelope.result, PNGetStateResult)
        assert envelope.result.channels[ch1]['name'] == "Alex"
        assert envelope.result.channels[ch1]['count'] == 5
        assert envelope.result.channels[ch2]['name'] == "Alex"
        assert envelope.result.channels[ch2]['count'] == 5
    def test_single_channel(self):
        ch = "channel-groups-native-ch"
        gr = "channel-groups-native-cg"
        pubnub = PubNub(pnconf_copy())

        # add
        envelope = pubnub.add_channel_to_channel_group() \
            .channels(ch) \
            .channel_group(gr) \
            .sync()

        assert isinstance(envelope.result, PNChannelGroupsAddChannelResult)

        time.sleep(2)

        # list
        envelope = pubnub.list_channels_in_channel_group() \
            .channel_group(gr) \
            .sync()

        assert isinstance(envelope.result, PNChannelGroupsListResult)
        assert len(envelope.result.channels) == 1
        assert envelope.result.channels[0] == ch

        # remove
        envelope = pubnub.remove_channel_from_channel_group() \
            .channels(ch) \
            .channel_group(gr) \
            .sync()

        assert isinstance(envelope.result, PNChannelGroupsRemoveChannelResult)

        time.sleep(2)

        # list
        envelope = pubnub.list_channels_in_channel_group() \
            .channel_group(gr) \
            .sync()

        assert isinstance(envelope.result, PNChannelGroupsListResult)
        assert len(envelope.result.channels) == 0
class PubNubManager:
    channel = "chan-1"

    _pnconfig = PNConfiguration()

    config = Utils.load_ini_file(r"credentials.ini")
    _pnconfig.publish_key = config.get("PubNub", "publish_key")
    _pnconfig.subscribe_key = config.get("PubNub", "subscribe_key")

    if _pnconfig.publish_key == "" or _pnconfig.subscribe_key == "":
        raise ValueError(
            "The inner\\credentials.ini file is missing the publish key and / or the subscribe key.\n"
            "Create your publish and subscribe key from https://www.pubnub.com/docs/quickstarts/python\n"
            "All users must use the same publish and subscription keys")

    _pnconfig.ssl = True
    _pubnub = PubNub(_pnconfig)
    _pubnub.add_listener(_MySubscribeCallback())
    _pubnub.subscribe().channels(channel).execute()

    @staticmethod
    def send(message: str):
        if message is not None:
            PubNubManager._pubnub.publish() \
                .channel(PubNubManager.channel) \
                .message(str(message)) \
                .pn_async(PubNubManager._my_publish_callback)

    @staticmethod
    def receive():
        PubNubManager._pubnub.publish() \
            .channel(PubNubManager.channel) \
            .pn_async(PubNubManager._my_publish_callback)

        return _MySubscribeCallback.get_msg_and_empty()

    @staticmethod
    def _my_publish_callback(envelope, status):
        # Check whether request successfully completed or not
        if not status.is_error():
            pass
class PubSub():
    '''
    Handles the publish/subscribe layer of the application
    Provides communication between the nodes of the blockchain network.
    '''
    def __init__(self):
        self.pubnub = PubNub(pnconfig)
        self.pubnub.subscribe().channels([TEST_CHANNEL]).execute()
        self.pubnub.add_listener(Listener())

    def publish(self, channel, message):
        '''
        Publish the message object to the channel.
        '''
        self.pubnub.publish().channel(channel).message(message).sync()
Beispiel #8
0
def initPubNub(stdscr):
    """
    Ask for a pseudo if not in the path and init the pubnub.PubNub object.

    Parameters
    ----------
        stdscr: :class:curses._CursesWindow
            the screen initialised in main.py

    Returns
    -------
    :class:pubnub.PubNub
        with configuration
    """
    pseudo = os.getenv("PSEUDO")
    if pseudo == None:
        pseudo = ""
        while len(pseudo) < 2:
            stdscr.addstr(0, 0, "pseudo :")
            stdscr.refresh()
            editwin = curses.newwin(1, min(16, curses.COLS - 1), 1, 1)  # pylint: disable=no-member
            editwin.keypad(True)
            box = Textbox(editwin)
            box.edit()
            pseudo = " ".join(box.gather().split())
        alphabet = string.ascii_letters + string.digits
        pseudo += ''.join(secrets.choice(alphabet) for i in range(10))
        with open("assets/data/.env", "a") as file:
            file.write(f"\nPSEUDO=\"{pseudo}\"")
        editwin.erase()

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = os.getenv("SUB_KEY")
    pnconfig.publish_key = os.getenv("PUB_KEY")
    pnconfig.ssl = True
    pnconfig.cipher_key = os.getenv("CYPHER_KEY")
    pnconfig.uuid = pseudo
    pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL
    pnconfig.connect_timeout = 30

    return PubNub(pnconfig)
def main(gps_queue):

    # PunNub Instance

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "sub-c-5f7c7648-c99c-11e9-ac59-7e2323a85324"
    pnconfig.publish_key = "pub-c-af13eaae-73e7-4c64-a7e8-4ec6c0dc13d1"
    pnconfig.ssl = False
    pubnub = PubNub(pnconfig)

    while (True):
        msg = gps_queue.get()  # Will block until message is recieved

        latitude = msg.data[0]  # data is an array
        longitude = msg.data[1]
        timestamp = msg.data[2]

        if latitude and longitude is not None:
            dictionary = {"latitude": latitude, "longitude": longitude}
            pubnub.publish().channel('blue').message(dictionary).pn_async(
                publish_callback)
    def test_invalid_key(self):
        self.invalid_key_message = ""
        config = PNConfiguration()
        config.publish_key = "fake"
        config.subscribe_key = "demo"
        config.enable_subscribe = False

        PubNub(config).publish() \
            .channel("ch1") \
            .message("hey") \
            .pn_async(self.callback)

        self.event.wait()

        assert self.status.is_error()
        assert self.status.category is PNStatusCategory.PNBadRequestCategory
        assert self.status.original_response[0] == 0
        assert self.status.original_response[1] == 'Invalid Key'
        assert "HTTP Client Error (400):" in str(
            self.status.error_data.exception)
        assert "Invalid Key" in str(self.status.error_data.exception)
Beispiel #11
0
    def test_multiple_channels(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch1 = helper.gen_channel("here-now-native-sync-ch1")
        ch2 = helper.gen_channel("here-now-native-sync-ch2")
        pubnub.config.uuid = "here-now-native-sync-uuid"

        subscribe_listener = SubscribeListener()
        here_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels([ch1, ch2]).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(5)

        pubnub.here_now() \
            .channels([ch1, ch2]) \
            .async(here_now_listener.callback)

        if here_now_listener. await () is False:
            self.fail("HereNow operation timeout")
    def test_single_channel(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch = helper.gen_channel("wherenow-asyncio-channel")
        uuid = helper.gen_channel("wherenow-asyncio-uuid")
        pubnub.config.uuid = uuid

        subscribe_listener = SubscribeListener()
        where_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels(ch).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(2)

        pubnub.where_now() \
            .uuid(uuid) \
            .async(where_now_listener.callback)

        if where_now_listener.await() is False:
            self.fail("WhereNow operation timeout")
Beispiel #13
0
class PubSub(object, metaclass=Singleton):

    @staticmethod
    def _read_pubnub_config(conffile):
        if isinstance(conffile, str):
            with open(os.path.expanduser(conffile)) as cf:
                return json.load(cf)
        else:
            return json.load(conffile)

    def __init__(self, conffile=CONFIG):
        conf = self._read_pubnub_config(conffile)
        self.pnconfig = PNConfiguration()
        self.pnconfig.subscribe_key = conf.get("subscribe_key")
        if self.pnconfig.subscribe_key is None:
            raise PubSubError("subscribe key is not configured")
        self.pnconfig.publish_key = conf.get("publish_key")
        if self.pnconfig.publish_key is None:
            raise PubSubError("publish key is not configured")
        self.pnconfig.ssl = conf.get("ssl", False)
        self._channels = conf.get("channels")
        self._pubnub = PubNub(self.pnconfig)

    def publish(self, data, meta=None, channels=None):
        # TODO: throttle or queue up messages
        chs = channels or self._channels
        if isinstance(chs, str):
            chs = [chs]
        elif chs is None:
            raise PubSubError("need publish channel")

        for ch in chs:
            p = self._pubnub.publish().channel(ch)
            p.message(data)
            if meta:
                p.meta(meta)
            envelope = p.sync()
            if envelope.status.is_error():
                raise PubSubError("Error publishing to {}: {}".format(
                    ch, envelope.status.error))
 def pubnub_call(self, channel):
     pnconfig = PNConfiguration()
     pnconfig.subscribe_key = "sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f"
     pnconfig.ssl = False
     pubnub = PubNub(pnconfig)
     my_listener = SubscribeListener()
     pubnub.add_listener(my_listener)
     pubnub.subscribe().channels(channel).execute()
     my_listener.wait_for_connect()
     while True:
         bf_result = my_listener.wait_for_message_on(channel)
         bf_data = bf_result.message
         print bf_data
         # pubnub.unsubscribe().channels(channel).execute()
         # my_listener.wait_for_disconnect()
         return bf_data
Beispiel #15
0
class P2P():
    def __init__(self, blockchain, keychain, entry_pool, chain_syncher):
        self.pubnub = PubNub(pnconfig)
        self.pubnub.subscribe().channels(CHANNELS).execute()
        self.pubnub.add_listener(
            Listener(blockchain, keychain, entry_pool, chain_syncher, self))

        self.blockchain = blockchain
        self.keychain = keychain
        self.entry_pool = entry_pool
        self.chain_syncher = chain_syncher

    def publish(self, channel, message):
        self.pubnub.publish().channel(channel).message(message).sync()

    def broadcast_entry(self, entry):
        self.publish('ENTRY', entry.to_json())

    def broadcast_block(self, block):
        message = {
            "sender_address": self.keychain.address,
            "block": block.to_json()
        }
        self.publish('BLOCK', message)

    def send_chain(self, chain, address):
        message = {"recipient_address": address, "chain": chain.to_json()}
        self.publish('CHAIN', message)

    def sync_chain(self):
        message = {"sender_address": self.keychain.address}
        self.publish('SYNC', message)

        def wait_chains():
            try:
                new_chain_json = self.chain_syncher.get_chain()
                new_blockchain = Blockchain.from_json(new_chain_json)

                self.blockchain.replace_chain(new_blockchain, self.entry_pool)

                self.entry_pool.filter(self.blockchain)

                print('\nBlockchain synchronisiert')
            except Exception as e:
                print(f'\nBlockchain nicht synchronisiert -> {e}')

        threading.Timer(2.0, wait_chains).start()
    def test_fetch_messages_actions_include_uuid(self):
        ch = "fetch-messages-actions-uuid"
        pubnub = PubNub(pnconf_copy())
        uuid1 = "fetch-messages-uuid-1"
        uuid2 = "fetch-messages-uuid-2"

        pubnub.config.uuid = uuid1
        pubnub.publish().channel(ch).message("hey-uuid-1").sync()
        pubnub.config.uuid = uuid2
        pubnub.publish().channel(ch).message("hey-uuid-2").sync()
        time.sleep(1)
        envelope = pubnub.fetch_messages().channels(
            ch).include_message_actions(True).include_uuid(True).sync()

        assert envelope is not None
        assert isinstance(envelope.result, PNFetchMessagesResult)
        history = envelope.result.channels[ch]
        assert len(history) == 2
        assert history[0].uuid == uuid1
        assert history[1].uuid == uuid2
    def test_multiple_channels(self):

        pubnub = PubNub(pnconf_sub_copy())
        ch1 = "state-native-sync-ch-1"
        ch2 = "state-native-sync-ch-2"
        pubnub.config.uuid = "state-native-sync-uuid"
        uuid = pubnub.config.uuid

        subscribe_listener = SubscribeListener()
        where_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels([ch1, ch2]).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(2)

        pubnub.where_now() \
            .uuid(uuid) \
            .async(where_now_listener.callback)

        if where_now_listener.await() is False:
            self.fail("WhereNow operation timeout")
Beispiel #18
0
class PubSub():
    """
    Handles the publish/subscribe layer of the application
    Provides communication between the nodes of the blockchain network.
    """
    def __init__(self, blockchain):
        self.pubnub = PubNub(pnconfig)
        self.pubnub.subscribe().channels(CHANNELS.values()).execute()
        self.pubnub.add_listener(Listener(blockchain))

    def publish(self, channel, message):
        self.pubnub.publish().channel(channel).message(message).sync()

    def broadcast_block(self, block):
        """
        Broadcast a block object to all nodes
        """
        self.publish(CHANNELS['BLOCK'], block.to_json())
def pugbnub_test():
	''' 
	Subscreve no canal de dados da cisterna, solicita e imprime as últimas
	100 mensagens do histórico do canal 
	'''
	print("initializing pubnub")
	# initializing pubnub

	pnconfig = PNConfiguration()
	pnconfig.subscribe_key = "sub-c-6e52b6c2-8e6b-11e8-b7a4-ce74daf54d52"
	# pnconfig.publish_key = "pub-c-6ce39655-3209-4cea-acc9-543751fe4e55"
	pnconfig.ssl = False

	pubnub = PubNub(pnconfig)

	# subscribe
	pubnub.subscribe().channels('dados_cisterna1').execute()

	# retrieve messsages from histrory
	# https://www.pubnub.com/docs/python/api-reference-storage-and-playback#history
	envelope = pubnub.history().channel("dados_cisterna1").count(100).sync()
	print("envelope: ")
	print(envelope)
	print("str(envelope): ")
	print(str(envelope))
	print("envelope status")
	print(envelope.status)
	print(type(envelope))
	print(type(envelope.result))
	print(type(envelope.result.messages))
	# print(envelope.messages)
	for message in envelope.result.messages:
		print("message: ")
		print(message.entry)
		# 
		# print(message.timetoken)
	# unsubscribe
	pubnub.unsubscribe().channels("dados_cisterna1").execute()
	# pass
Beispiel #20
0
def mainScreen():
    titleLabel.place(x=0, y=0)
    setup()
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "sub-c-d7ac3638-ae96-11e9-b39e-aa7241355c4e"
    pnconfig.publish_key = "pub-c-416fd2e5-42a7-49f7-9952-fe8c5f13d25e"
    pnconfig.ssl = False
    pnconfig.uuid = mainUser.username

    global pubnub
    pubnub = PubNub(pnconfig)
    pubnub.add_listener(SubListener())
    pubnub.subscribe().channels(channel).execute()
    receiveBox.place(relx=0.007, rely=0.21)
    msgEntry.place(relx=0.015, rely=0.92)
    userLabel.place(relx=0.4, rely=0.05)
    msgEntry.bind("<Return>", sendMessage)
    history = pubnub.history().channel(channel).count(50).pn_async(history_callback)
    tk.protocol("WM_DELETE_WINDOW", closeProtocol)
    if len(mainUser.username) < 1 or len(mainUser.username) > 12:
        box.showinfo('Username', 'Please make your username between 1 and 12 characters long. You can do this in the Alpha Chat User Manager app.')
        tk.destroy()
    def test_encrypted(self, crypto_mock):
        ch = "history-native-sync-ch"
        pubnub = PubNub(pnconf_enc_copy())
        pubnub.config.uuid = "history-native-sync-uuid"

        for i in range(COUNT):
            envelope = pubnub.publish().channel(ch).message("hey-%s" % i).sync()
            assert isinstance(envelope.result, PNPublishResult)
            assert envelope.result.timetoken > 0

        time.sleep(5)

        envelope = pubnub.history().channel(ch).count(COUNT).sync()

        assert isinstance(envelope.result, PNHistoryResult)
        assert envelope.result.start_timetoken > 0
        assert envelope.result.end_timetoken > 0
        assert len(envelope.result.messages) == 5

        assert envelope.result.messages[0].entry == 'hey-0'
        assert envelope.result.messages[1].entry == 'hey-1'
        assert envelope.result.messages[2].entry == 'hey-2'
        assert envelope.result.messages[3].entry == 'hey-3'
        assert envelope.result.messages[4].entry == 'hey-4'
    def test_super_call(self):
        ch1 = "state-tornado-ch1"
        ch2 = "state-tornado-ch2"
        pnconf = pnconf_pam_copy()
        pubnub = PubNub(pnconf)
        pubnub.config.uuid = 'test-state-native-uuid-|.*$'
        state = {"name": "Alex", "count": 5}

        env = pubnub.set_state() \
            .channels([ch1, ch2]) \
            .state(state) \
            .sync()

        assert env.result.state['name'] == "Alex"
        assert env.result.state['count'] == 5

        env = pubnub.get_state() \
            .channels([ch1, ch2]) \
            .sync()

        assert env.result.channels[ch1]['name'] == "Alex"
        assert env.result.channels[ch2]['name'] == "Alex"
        assert env.result.channels[ch1]['count'] == 5
        assert env.result.channels[ch2]['count'] == 5
def publish_nonhead():
    import time    
    time.sleep(30)
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    k1= 'pub-c-529ac86d-f8bc-4094-9196-1fe0652ebc4f'
    k2= 'sub-c-5dec13b4-1c6f-11e8-9e0d-86843e43dc8b'
     
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = k2
    pnconfig.publish_key = k1
    pnconfig.ssl = True
     
    pubnub = PubNub(pnconfig)
    import time
    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-82ldwdilv").message(code).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
    except PubNubException as e:
            print e
def publish_nonhead():
    import time    
    time.sleep(30)
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    k1= 'pub-c-e4dca0d8-c948-42e9-a080-3a84922d77c4'
    k2= 'sub-c-ff76b412-17b2-11e8-bb84-266dd58d78d1'
     
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = k2
    pnconfig.publish_key = k1
    pnconfig.ssl = True
     
    pubnub = PubNub(pnconfig)
    import time
    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-n3jbvzcv1").message('%s'%d).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
    except PubNubException as e:
            print e
Beispiel #25
0
def main():
    pb = python_bitbankcc.public()
    btc = pb.get_ticker(pair)

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = SUBSCRIBE_KEY
    pubnub = PubNub(pnconfig)

    # inherits SubscribeCallBack class
    my_listener = BitbankSubscriberCallback(float(btc['sell']),
                                            float(btc['buy']))
    pubnub.add_listener(my_listener)
    pubnub.subscribe().channels(TICKER_CHANNEL).execute()

    while True:
        print("Calling the trade logic, best_ask {0}: best_bid {1}".format(
            my_listener.ask, my_listener.bid))
        logic.trade(my_listener.ask, my_listener.bid)
        time.sleep(10)
    def test_fetch_messages_actions_include_meta(self):
        ch = "fetch-messages-actions-meta-1"
        pubnub = PubNub(pnconf_copy())
        pubnub.config.uuid = "fetch-messages-uuid"

        pubnub.publish().channel(ch).message("hey-meta").meta({
            "is-this":
            "krusty-krab"
        }).sync()
        pubnub.publish().channel(ch).message("hey-meta").meta({
            "this-is":
            "patrick"
        }).sync()

        envelope = pubnub.fetch_messages().channels(
            ch).include_message_actions(True).include_meta(True).sync()

        assert envelope is not None
        assert isinstance(envelope.result, PNFetchMessagesResult)
        history = envelope.result.channels[ch]
        assert len(history) == 2
        assert history[0].meta == {"is-this": "krusty-krab"}
        assert history[1].meta == {'this-is': 'patrick'}
Beispiel #27
0
class PubSub():
    # establish communication between nodes
    def __init__(self, blockchain, tx_pool):
        self.pubnub = PubNub(pnconfig)
        self.pubnub.subscribe().channels(['BLOCK', 'TX']).execute()
        self.pubnub.add_listener(Listener(blockchain, tx_pool))


    def publish(self, channel, msg):
        self.pubnub.publish().channel(channel).message(msg).sync()


    def publish_block(self, block):
        # publish new block to nodes
        self.publish('BLOCK', block.__dict__)


    def publish_tx(self, tx):
        # publish new transaction to nodes
        self.publish('TX', tx.__dict__)
Beispiel #28
0
class PubSub():
    """
    Handles the pub/sub layer. 
    """
    def __init__(self, blockchain):
        self.pubnub = PubNub(pnconfig)
        self.pubnub.subscribe().channels(CHANNELS.values()).execute()
        self.pubnub.add_listener(Listener(blockchain))

    def publish(self, channel, message):
        """
        Publish the message object to the channel
        """
        self.pubnub.publish().channel(channel).message(message).sync()

    def broadcast_block(self, block):
        """
        Broadcast a block object to all nodes. 
        """
        self.publish(CHANNELS['BLOCK'], block.to_json())
Beispiel #29
0
class PubSub():
    # Handles the publish/subscribe layer of the application.
    # Provides comminucation between the nodes of the blockchain network.

    def __init__(self, blockchain, transaction_pool):
        self.pubnub = PubNub(pnconfig)
        self.pubnub.subscribe().channels(CHANNELS.values()).execute()
        self.pubnub.add_listener(Listener(blockchain, transaction_pool))

    def publish(self, channel, message):
        # Publish the message object to the channel.
        self.pubnub.publish().channel(channel).message(message).sync()

    def broadcast_block(self, block):
        # Broadcast the block object to all nodes.
        self.publish(CHANNELS['BLOCK'], block.to_json())

    def broadcast_transaction(self, transaction):
        # Broadcast the transaction object to all nodes.
        self.publish(CHANNELS['TRANSACTION'], transaction.to_json())
Beispiel #30
0
class PubSub():
    """
    Handles the publish/subscribe layer of the application
    Provides comminucation between the nodes of the blockchain network.
    """
    def __init__(self, blockchain, transaction_pool):
        self.pubnub = PubNub(pnconfig)
        self.pubnub.subscribe().channels(CHANNELS.values()).execute()
        self.pubnub.add_listener(Listener(blockchain, transaction_pool))

    def presence(self, pubnub, event):
        print("[PRESENCE: {}]".format(event.event))
        print("uuid: {}, channel: {}".format(event.uuid, event.channel))

    def status_callback(self, result, status, event):
        if status.is_error():
            print("Error %s" % str(status.error_data.exception))
            print("Error category #%d" % status.category)
        if not event.category == PNStatusCategory.PNConnectedCategory:
            print("[STATUS: PNConnectedCategory]")
            print("connected to channels: {}".format(event.affected_channels))
        else:
            print(str(result))

    def publish(self, channel, message):
        """
        Publish the message object to the channel.
        """
        self.pubnub.publish().channel(channel).message(message).sync()

    def broadcast_block(self, block):
        """
        Broadcast a block object to all nodes.
        """
        self.publish(CHANNELS['BLOCK'], block.to_json())

    def broadcast_transaction(self, transaction):
        """
        Bradcast a transaction to all nodes.
        """
        self.publish(CHANNELS['TRANSACTION'], transaction.to_json())
class PubSub():
    """
    Handles the publish/subscribe layer of the application.
    Provides communication between the nodes of the blockchain network.
    """
    def __init__(self, blockchain, transaction_pool, account):
        self.pubnub = PubNub(pnconfig)
        self.pubnub.subscribe().channels(CHANNELS.values()).execute()
        self.pubnub.add_listener(Listener(blockchain, transaction_pool, account))

    def publish(self, channel, message):
        """
        Publish the message object to the channel.
        """
        self.pubnub.publish().channel(channel).message(message).sync()

    def broadcast_block(self, block):
        """
        Broadcast a block object to all nodes.
        """
        self.publish(CHANNELS['BLOCK'], block.to_json())

    def broadcast_transaction(self, transaction):
        """
        Broadcast a transaction to all nodes.
        """
        self.publish(CHANNELS['TRANSACTION'], transaction.to_json())

    def broadcast_energy(self, etran):
        """
        Broadcast a energy request to all nodes.
        """
        print("broadcast etran")
        self.publish(CHANNELS['ENERGY'], etran.to_json())

    def broadcast_energy_tran(self, etran):
        """
        Broadcast a energy request to all nodes.
        """
        print("broadcast etran ack")
        self.publish(CHANNELS['ETRANACK'], etran.to_json())
Beispiel #32
0

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
import subprocess
import  time
import datetime
import math
pnconfig = PNConfiguration()

pnconfig.publish_key ='pub-c-9c260cad-9e78-4bea-a3a9-f584ea818532'
pnconfig.subscribe_key = 'sub-c-2e6e94ce-305d-11e9-a223-2ae0221900a7'
pubnub = PubNub(pnconfig)
x=10
def callback(message, status):
	print(message)
avg=0.0
count=0
while x>0:
	x-=1
	count+=1
	time.sleep(1)
	p = subprocess.check_output('lifepo4wered-cli get vbat',shell=True)
	b1=round(float(p)/1000,5)
	p = subprocess.check_output('lifepo4wered-cli get vout',shell=True)
	r1=round(float(p)/1000,5)
	data ={
	"eon":{"Battery Voltage (Volts)":b1,"Raspberry Pi Voltage (Volts)":r1}
	}
	avg=avg+r1
	data2={	"PL":20,"ON":round(avg/count,3),"W":"Working","S":x,"WT":"Not Set Yet"}
#!/usr/bin/python3

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"
pnconfig.ssl = False

pubnub = PubNub(pnconfig)

from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNOperationType, PNStatusCategory

class MySubscribeCallback(SubscribeCallback):
    def status(self, pubnub, status):
        pass
        # The status object returned is always related to subscribe but could contain
        # information about subscribe, heartbeat, or errors
        # use the operationType to switch on different options
        if status.operation == PNOperationType.PNSubscribeOperation \
                or status.operation == PNOperationType.PNUnsubscribeOperation:
            if status.category == PNStatusCategory.PNConnectedCategory:
                pass
                # This is expected for a subscribe, this means there is no error or issue whatsoever
            elif status.category == PNStatusCategory.PNReconnectedCategory:
                pass
                # This usually occurs if subscribe temporarily fails but reconnects. This means
                # there was an error but there is no longer any issue
            elif status.category == PNStatusCategory.PNDisconnectedCategory:
Beispiel #34
0
    def test_subscribe_unsubscribe(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch = helper.gen_channel("test-subscribe-sub-unsub")

        try:
            listener = SubscribeListener()
            pubnub.add_listener(listener)

            pubnub.subscribe().channels(ch).execute()
            assert ch in pubnub.get_subscribed_channels()
            assert len(pubnub.get_subscribed_channels()) == 1

            listener.wait_for_connect()
            assert ch in pubnub.get_subscribed_channels()
            assert len(pubnub.get_subscribed_channels()) == 1

            pubnub.unsubscribe().channels(ch).execute()
            assert ch not in pubnub.get_subscribed_channels()
            assert len(pubnub.get_subscribed_channels()) == 0

            listener.wait_for_disconnect()
            assert ch not in pubnub.get_subscribed_channels()
            assert len(pubnub.get_subscribed_channels()) == 0

        except PubNubException as e:
            self.fail(e)
        finally:
            pubnub.stop()
Beispiel #35
0
    def test_subscribe_cg_join_leave(self):
        ch = helper.gen_channel("test-subscribe-unsubscribe-channel")
        gr = helper.gen_channel("test-subscribe-unsubscribe-group")

        pubnub = PubNub(pnconf_sub_copy())
        pubnub_listener = PubNub(pnconf_sub_copy())
        non_subscribe_listener = NonSubscribeListener()

        pubnub.add_channel_to_channel_group() \
            .channel_group(gr) \
            .channels(ch) \
            .async(non_subscribe_listener.callback)
        result = non_subscribe_listener.await_result_and_reset()
        assert isinstance(result, PNChannelGroupsAddChannelResult)

        time.sleep(1)

        callback_messages = SubscribeListener()
        callback_presence = SubscribeListener()

        pubnub_listener.add_listener(callback_presence)
        pubnub_listener.subscribe().channel_groups(gr).with_presence().execute()
        callback_presence.wait_for_connect()

        prs_envelope = callback_presence.wait_for_presence_on(ch)
        assert prs_envelope.event == 'join'
        assert prs_envelope.uuid == pubnub_listener.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        pubnub.add_listener(callback_messages)
        pubnub.subscribe().channel_groups(gr).execute()

        prs_envelope = callback_presence.wait_for_presence_on(ch)

        assert prs_envelope.event == 'join'
        assert prs_envelope.uuid == pubnub.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        pubnub.unsubscribe().channel_groups(gr).execute()
        prs_envelope = callback_presence.wait_for_presence_on(ch)

        assert prs_envelope.event == 'leave'
        assert prs_envelope.uuid == pubnub.uuid
        assert prs_envelope.channel == ch
        assert prs_envelope.subscription == gr

        pubnub_listener.unsubscribe().channel_groups(gr).execute()
        callback_presence.wait_for_disconnect()

        pubnub.remove_channel_from_channel_group() \
            .channel_group(gr) \
            .channels(ch) \
            .async(non_subscribe_listener.callback)
        result = non_subscribe_listener.await_result_and_reset()
        assert isinstance(result, PNChannelGroupsRemoveChannelResult)

        pubnub.stop()
        pubnub_listener.stop()
Beispiel #36
0
from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()

pnconfig.subscribe_key = 'sub-c-a41be4e8-b620-11e5-a916-0619f8945a4f'
pnconfig.publish_key = 'pub-c-b525a8c0-3301-432e-a37b-d8fec5583788'
pnconfig.subscribe_key = 'demo'
pnconfig.publish_key = 'demo'

pubnub = PubNub(pnconfig)


def my_publish_callback(envelope, status):
    # Check whether request successfully completed or not
    if not status.is_error():
        pass  # Message successfully published to specified channel.
    else:
        pass  # Handle message publish error. Check 'category' property to find out possible issue


# because of which request did fail.
# Request can be resent using: [status retry];


class MySubscribeCallback(SubscribeCallback):
    def presence(self, pubnub, presence):
        pass  # handle incoming presence data
        kafka_hosts = args.kafka
        print("Writing to kafka ...")
        print(my_topic)
        producer = KafkaProducer(bootstrap_servers=kafka_hosts)
        push_to_kafka = True
        if args.debug:
            PRINT_TERM = True
        else:
            PRINT_TERM = False
    except:
        print("Printing to console. Will not write to kafka.")
        PRINT_TERM = True

    if PRINT_TERM:
        print("Print pubnub events to terminal.")
    else:
        print("Will not print events to terminal.")

    # bootstrap the config object
    pnconf = PNConfiguration()
    PUBNUB_SUBSCRIBE_KEY = stream_info['sub_key']
    CHANNEL = stream_info['channel']

    pnconf.subscribe_key = PUBNUB_SUBSCRIBE_KEY
    pnconf.ssl = False
    # create the pub / sub client
    pubnub = PubNub(pnconf)

    pubnub.add_listener(MySubscribeCallback())
    pubnub.subscribe().channels(CHANNEL).execute()
Beispiel #38
0
    def test_join_leave(self):
        ch = helper.gen_channel("test-subscribe-join-leave")

        pubnub = PubNub(pnconf_sub_copy())
        pubnub_listener = PubNub(pnconf_sub_copy())
        callback_messages = SubscribeListener()
        callback_presence = SubscribeListener()

        pubnub.config.uuid = helper.gen_channel("messenger")
        pubnub_listener.config.uuid = helper.gen_channel("listener")

        try:
            pubnub.add_listener(callback_messages)
            pubnub_listener.add_listener(callback_presence)

            pubnub_listener.subscribe().channels(ch).with_presence().execute()
            callback_presence.wait_for_connect()

            envelope = callback_presence.wait_for_presence_on(ch)
            assert envelope.channel == ch
            assert envelope.event == 'join'
            assert envelope.uuid == pubnub_listener.uuid

            pubnub.subscribe().channels(ch).execute()
            callback_messages.wait_for_connect()

            envelope = callback_presence.wait_for_presence_on(ch)
            assert envelope.channel == ch
            assert envelope.event == 'join'
            assert envelope.uuid == pubnub.uuid

            pubnub.unsubscribe().channels(ch).execute()
            callback_messages.wait_for_disconnect()

            envelope = callback_presence.wait_for_presence_on(ch)
            assert envelope.channel == ch
            assert envelope.event == 'leave'
            assert envelope.uuid == pubnub.uuid

            pubnub_listener.unsubscribe().channels(ch).execute()
            callback_presence.wait_for_disconnect()
        except PubNubException as e:
            self.fail(e)
        finally:
            pubnub.stop()
            pubnub_listener.stop()
Beispiel #39
0
    def test_cg_subscribe_unsubscribe(self):
        ch = helper.gen_channel("test-subscribe-unsubscribe-channel")
        gr = helper.gen_channel("test-subscribe-unsubscribe-group")

        pubnub = PubNub(pnconf_sub_copy())
        callback_messages = SubscribeListener()
        cg_operation = NonSubscribeListener()

        pubnub.add_channel_to_channel_group()\
            .channel_group(gr)\
            .channels(ch)\
            .async(cg_operation.callback)
        result = cg_operation.await_result()
        assert isinstance(result, PNChannelGroupsAddChannelResult)
        cg_operation.reset()

        time.sleep(1)

        pubnub.add_listener(callback_messages)
        pubnub.subscribe().channel_groups(gr).execute()
        callback_messages.wait_for_connect()

        pubnub.unsubscribe().channel_groups(gr).execute()
        callback_messages.wait_for_disconnect()

        pubnub.remove_channel_from_channel_group()\
            .channel_group(gr)\
            .channels(ch)\
            .async(cg_operation.callback)
        result = cg_operation.await_result()
        assert isinstance(result, PNChannelGroupsRemoveChannelResult)

        pubnub.stop()
Beispiel #40
0

class MySubscribeCallback(SubscribeCallback):
    def status(self, pubnub, status):
        print("### status changed to: %s" % status.category)
        if status.category == PNStatusCategory.PNReconnectedCategory:
            pubnub.stop()

    def message(self, pubnub, message):
        pass

    def presence(self, pubnub, presence):
        pass


pnconf = PNConfiguration()
pnconf.publish_key = "demo"
pnconf.subscribe_key = "demo"
pnconf.origin = "localhost:8089"
pnconf.subscribe_request_timeout = 10
pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR
pubnub = PubNub(pnconf)

time_until_open_again = 8

my_listener = MySubscribeCallback()
pubnub.add_listener(my_listener)
pubnub.subscribe().channels('my_channel').execute()

# atexit.register(pubnub.stop)
Beispiel #41
0
    def test_subscribe_cg_publish_unsubscribe(self):
        ch = helper.gen_channel("test-subscribe-unsubscribe-channel")
        gr = helper.gen_channel("test-subscribe-unsubscribe-group")
        message = "hey"

        pubnub = PubNub(pnconf_sub_copy())
        callback_messages = SubscribeListener()
        non_subscribe_listener = NonSubscribeListener()

        pubnub.add_channel_to_channel_group() \
            .channel_group(gr) \
            .channels(ch) \
            .async(non_subscribe_listener.callback)
        result = non_subscribe_listener.await_result_and_reset()
        assert isinstance(result, PNChannelGroupsAddChannelResult)

        time.sleep(1)

        pubnub.add_listener(callback_messages)
        pubnub.subscribe().channel_groups(gr).execute()
        callback_messages.wait_for_connect()

        pubnub.publish().message(message).channel(ch).async(non_subscribe_listener.callback)
        result = non_subscribe_listener.await_result_and_reset()
        assert isinstance(result, PNPublishResult)
        assert result.timetoken > 0

        pubnub.unsubscribe().channel_groups(gr).execute()
        callback_messages.wait_for_disconnect()

        pubnub.remove_channel_from_channel_group() \
            .channel_group(gr) \
            .channels(ch) \
            .async(non_subscribe_listener.callback)
        result = non_subscribe_listener.await_result_and_reset()
        assert isinstance(result, PNChannelGroupsRemoveChannelResult)

        pubnub.stop()
Beispiel #42
0
    def test_timeout_event_on_broken_heartbeat(self):
        ch = helper.gen_channel("heartbeat-test")

        pubnub = PubNub(messenger_config)
        pubnub_listener = PubNub(listener_config)

        pubnub.config.uuid = helper.gen_channel("messenger")
        pubnub_listener.config.uuid = helper.gen_channel("listener")

        callback_presence = SubscribeListener()
        callback_messages = SubscribeListener()

        # - connect to :ch-pnpres
        pubnub_listener.add_listener(callback_presence)
        pubnub_listener.subscribe().channels(ch).with_presence().execute()
        callback_presence.wait_for_connect()

        presence_message = callback_presence.wait_for_presence_on(ch)
        assert ch == presence_message.channel
        assert 'join' == presence_message.event
        assert pubnub_listener.uuid == presence_message.uuid

        # - connect to :ch
        pubnub.add_listener(callback_messages)
        pubnub.subscribe().channels(ch).execute()
        callback_messages.wait_for_connect()

        prs_envelope = callback_presence.wait_for_presence_on(ch)
        assert ch == prs_envelope.channel
        assert 'join' == prs_envelope.event
        assert pubnub.uuid == prs_envelope.uuid

        # wait for one heartbeat call
        time.sleep(6)

        # - break messenger heartbeat loop
        pubnub._subscription_manager._stop_heartbeat_timer()

        # - assert for timeout
        presence_message = callback_presence.wait_for_presence_on(ch)
        assert ch == presence_message.channel
        assert 'timeout' == presence_message.event
        assert pubnub.uuid == presence_message.uuid

        pubnub.unsubscribe().channels(ch).execute()
        callback_messages.wait_for_disconnect()

        # - disconnect from :ch-pnpres
        pubnub_listener.unsubscribe().channels(ch).execute()
        callback_presence.wait_for_disconnect()

        pubnub.stop()
        pubnub_listener.stop()