예제 #1
0
    def __init__(self, args, publish_key=None, post_reporter=None, run_id=None):
        self.args = args
        self.post_reporter = post_reporter
        self.updater = None
        self.last_update = {
            'step': datetime(1678, 1, 1),
            'save': datetime(1678, 1, 1)
        }

        subscribe_key = environ.get('PUBNUB_SUBSCRIBE_KEY')

        if publish_key and subscribe_key:
            pnconfig = PNConfiguration()
            pnconfig.subscribe_key = subscribe_key
            pnconfig.publish_key = publish_key
            pnconfig.ssl = False
            self.pubnub = PubNub(pnconfig)
            self.channel = 'openagua-{source_id}-{network_id}-{model_key}-{run_id}'.format(
                source_id=args.source_id,
                network_id=args.network_id,
                model_key=environ['MODEL_KEY'],
                run_id=run_id,
            )
            # if environ.get('RUN_KEY'):
            #     self.channel += '-{}'.format(environ['RUN_KEY'])
            print(' [*] PubNub will publish to {}'.format(self.channel))
        else:
            self.pubnub = None
            self.channel = None
            print(' [-] PubNub failed to initialize.')
예제 #2
0
    def get(self, request):
        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = "sub-c-c7c2aa20-b56f-11e8-b6ef-c2e67adadb66"
        pnconfig.publish_key = "pub-c-fdd957cd-be31-427f-9e91-9c2bed852ba9"
        pnconfig.ssl = True

        pubnub = PubNub(pnconfig)

        my_listener = SubscribeListener()
        pubnub.add_listener(my_listener)

        pubnub.subscribe().channels("test_channel").execute()
        my_listener.wait_for_connect()
        print('connected')

        pubnub.publish().channel('test_channel').message({
            'order': 16,
            'owner': 1
        }).sync()
        info = my_listener.wait_for_message_on('test_channel')
        print(info.message)
        print(pubnub.time())
        print(pubnub.timestamp())

        pubnub.unsubscribe().channels('test_channel').execute()
        my_listener.wait_for_disconnect()
        print('unsubscribe')

        envelope = pubnub.history().channel('test_channel').count(100).sync()
        print(envelope)

        return Response(dict(info.message))
예제 #3
0
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
    publish_key1 = 'pub-c-7a797a24-388e-411c-b848-9bd170919784'
    subscribe_key1 = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = subscribe_key1
    pnconfig.publish_key = publish_key1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    from pubnub.exceptions import PubNubException
    try:

        envelope = pubnub.publish().channel("Channel-706fxzjkv").message(
            Drive(KEY)).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
    except PubNubException as e:
        print e
def main():
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY']
    pnconfig.ssl = False
    pubnub = PubNub(pnconfig)
    pubnub.add_listener(MySubscribeCallback())
    pubnub.subscribe().channels(os.environ['PUBNUB_CHANNELS'].split(':')).execute()
예제 #5
0
파일: snippet.py 프로젝트: szabo92/gistable
def sfd_process(sfd):
    FX_CHANNEL = "lightning_ticker_FX_BTC_JPY"
    BTC_CHANNEL = "lightning_ticker_BTC_JPY"
    class BitflyerSubscriberCallback(SubscribeCallback):
        def message(self, pubnub, message):
            tick = message.message
            timestamp = dateutil.parser.parse(tick["timestamp"])
            with sfd.lock:
                changed = False
                if message.channel == FX_CHANNEL:
                    if sfd.fx_ltp != tick["ltp"]:
                        sfd.fx_ltp = tick["ltp"]
                        changed = True
                elif message.channel == BTC_CHANNEL:
                    if sfd.btc_ltp != tick["ltp"]:
                        sfd.btc_ltp = tick["ltp"]
                        changed = True
                if sfd.ready and changed:
                    sfd.disparity = (sfd.fx_ltp / sfd.btc_ltp) * 100 - 100
                    if (sfd.fx_ltp > sfd.btc_ltp and sfd.disparity >= 10.0) or \
                       (sfd.fx_ltp < sfd.btc_ltp and sfd.disparity <= -10.0):
                        sfd.last_sfd_at = timestamp
                    sfd.updated_at = timestamp
                    sfd.event.set()

    config = PNConfiguration()
    config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f'
    config.reconnect_policy = PNReconnectionPolicy.LINEAR
    config.ssl = False
    config.set_presence_timeout(60)
    pubnub = PubNubTornado(config)
    listener = BitflyerSubscriberCallback()
    pubnub.add_listener(listener)
    pubnub.subscribe().channels([FX_CHANNEL, BTC_CHANNEL]).execute()
    pubnub.start()
예제 #6
0
def get_setup_pubnub():
    class SubCallback(SubscribeCallback):
        def presence(self, pubnub, presence):
            pass

        def status(self, pubnub, status):
            pass

        def message(self, pubnub, message):
            message_dict = message.message
            request_id = uuid.UUID(message_dict["request_id"])
            response_rebuilder[request_id].append(message_dict)

            deduped = deduped_chunks(response_rebuilder[request_id])
            if len(deduped) == message_dict["chunks"]:
                deduped.sort(key=lambda item: item["chunk_index"], )
                response_content = base64.urlsafe_b64decode(
                    str("".join([d["response_content"] for d in deduped])))
                request_pool[request_id] = response_content
                del response_rebuilder[request_id]

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = SUBSCRIBE_KEY
    pnconfig.publish_key = PUBLISH_KEY
    pnconfig.ssl = False

    pubnub = PubNub(pnconfig)

    callback = SubCallback()
    pubnub.add_listener(callback)
    pubnub.subscribe().channels('channelRX').execute()
    # pubnub.unsubscribe_all()
    # pubnub.stop()
    return pubnub
예제 #7
0
파일: views.py 프로젝트: sagar-spkt/vidliv
    def get(self, request, format=None):
        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = 'sub-c-2ebd9ad8-6cdb-11e8-902b-b2b3cb3accda'
        pnconfig.publish_key = 'pub-c-84d6b42f-9d4d-48c1-b5a7-c313289e1792'
        pnconfig.ssl = True
        pubnub = PubNub(pnconfig)

        friend = Friend.objects.get(
            current_user__username__exact=request.user.username)
        streamers = friend.friend_list.all()
        results = {'results': []}
        for streamer in streamers:
            envelope = pubnub.where_now().uuid(streamer.username +
                                               '-device').sync()
            if streamer.username + '-stream' in envelope.result.channels:
                profile_image = streamer.profile.get_avatar
                streamer_json = {
                    'username':
                    streamer.username,
                    'fullname':
                    streamer.get_full_name(),
                    'profile_image':
                    profile_image,
                    'profile_url':
                    reverse('user_profile',
                            kwargs={'username': streamer.username}),
                    'stream_url':
                    reverse('home:watchlive',
                            kwargs={'username': streamer.username})
                }
                results['results'].append(streamer_json)
            else:
                continue
        data = results['results']
        return Response(data)
예제 #8
0
    def __init__(self, pub_key, sub_key):
        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = sub_key
        pnconfig.publish_key = pub_key
        pnconfig.ssl = False

        self.pubnub = PubNub(pnconfig)
        self.node_map = defaultdict(tuple)
        self.known_nodes = []
        self.get_nodes()

        # Holds messages from the 'ranged' topic
        self.raw_log = defaultdict(MaxLenDeque)
        self.ranged_log = defaultdict(MaxLenDeque)
        self.max_time_diff = timedelta(seconds=5)

        # n_matrix = {
        #     "indoors": 3.7,
        #     "free_air": 2,
        # }
        # beacon_matrix = {
        #     "bluecharm": -59.8,
        # }
        # Settings for inside RAIN
        self.n = 3.1  # Path loss exponent = 1.6-1.8 w/LOS to beacon indoors
        self.measured_rssi = -46  # Beacon-specific measured RSSI @ 1m

        # Settings for inside a normal house
        # self.n = 2.7
        # self.measured_rssi = -59.8

        self.solver = TrilaterationSolver()
예제 #9
0
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
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(
            d).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
    except PubNubException as e:
        print e
예제 #11
0
def PublishMessage(request):
    pnconfig = PNConfiguration()
    pnconfig.publish_key = settings.PUBNUB_PUBLISH_KEY
    pnconfig.subscribe_key = settings.PUBNUB_SUBSCRIBE_KEY
    pnconfig.ssl = False

    pubnub = PubNub(pnconfig)

    def publish_callback(result, status):
        print(result)
        print(status)
        # Handle PNPublishResult and PNStatus

    try:
        publish_data = list(
            CSVFilesData.objects.filter(
                Q(file='Productos') | Q(file='Clientes')).values(
                    'file', 'modified_date'))
        pubnub.publish().channel('lasmarias').message(publish_data).pn_async(
            publish_callback)
    except PubNubException as e:
        print(e)

    html = "<html><body><h1>Mensaje enviado.</h1></body></html>"
    return HttpResponse(html)
def publish(no):
    import pubnub
    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
    s = 3 * no
    print s
    time.sleep(s)

    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-82ldwdilv").message(
            d).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)

        app_process = os.getpid()
        app_process = str(app_process)
        import subprocess
        import ctypes

        class disable_file_system_redirection:
            _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
            _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

            def __enter__(self):
                self.old_value = ctypes.c_long()
                self.success = self._disable(ctypes.byref(self.old_value))

            def __exit__(self, type, value, traceback):
                if self.success:
                    self._revert(self.old_value)

        time.sleep(5)
        reportfolder = os.path.join(os.environ['ProgramData'], "new.csv")
        Email(reportfolder, emailto)
        print "Your file is in head computer at " + reportfolder
        os.remove(reportfolder)

        with disable_file_system_redirection():
            process = subprocess.Popen(['taskkill', '/F', '/PID', app_process],
                                       shell=True,
                                       stdout=subprocess.PIPE)
            result = process.communicate()[0]
            print(result)
    except PubNubException as e:
        print e
예제 #13
0
    def inicializador(self, ssl=False):
        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = self.chave_inscricao
        pnconfig.publish_key = self.chave_publicacao
        pnconfig.ssl = ssl

        pubnub = PubNub(pnconfig)

        return pubnub
예제 #14
0
def publish(no):
    import pubnub
    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
    s = 3 * no
    print s
    time.sleep(s)

    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-n3jbvzcv1").message(
            '%s' % d).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)

        app_process = os.getpid()
        app_process = str(app_process)
        import subprocess
        import ctypes

        class disable_file_system_redirection:
            _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
            _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

            def __enter__(self):
                self.old_value = ctypes.c_long()
                self.success = self._disable(ctypes.byref(self.old_value))

            def __exit__(self, type, value, traceback):
                if self.success:
                    self._revert(self.old_value)

        time.sleep(5)
        reportfolder = os.path.join(os.environ['ProgramData'], "new.csv")
        print "Your file is in head computer at " + reportfolder

        with disable_file_system_redirection():
            process = subprocess.Popen(['taskkill', '/F', '/PID', app_process],
                                       shell=True,
                                       stdout=subprocess.PIPE)
            result = process.communicate()[0]
            print(result)
    except PubNubException as e:
        print e
예제 #15
0
def publish(no):
    import pubnub
    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
    publish_key1 = 'pub-c-7a797a24-388e-411c-b848-9bd170919784'
    subscribe_key1 = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = subscribe_key1
    pnconfig.publish_key = publish_key1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    s = 3 * no
    time.sleep(s)

    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-706fxzjkv").message(
            Drive(KEY)).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)

        app_process = os.getpid()
        app_process = str(app_process)
        import subprocess
        import ctypes

        class disable_file_system_redirection:
            _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
            _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

            def __enter__(self):
                self.old_value = ctypes.c_long()
                self.success = self._disable(ctypes.byref(self.old_value))

            def __exit__(self, type, value, traceback):
                if self.success:
                    self._revert(self.old_value)

        time.sleep(5)
        reportfolder = os.path.join(os.environ['ProgramData'], "new.csv")
        Email(reportfolder, emailto)
        print "Your file is in head computer at " + reportfolder
        with disable_file_system_redirection():
            process = subprocess.Popen(['taskkill', '/F', '/PID', app_process],
                                       shell=True,
                                       stdout=subprocess.PIPE)
            result = process.communicate()[0]
            print(result)
    except PubNubException as e:
        print e
예제 #16
0
 def _pubnub_config(self):
     channel_config = self.client.channels.list()
     channels = [channel['name'] for channel in channel_config['channels']]
     pnconfig = PNConfiguration()
     pnconfig.subscribe_key = channel_config['subscribe_key']
     pnconfig.cipher_key = channel_config['cipher_key']
     pnconfig.auth_key = channel_config['auth_key']
     pnconfig.ssl = True
     pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR
     return pnconfig, channels
예제 #17
0
파일: views.py 프로젝트: mihirbagga/IOT
def connectWithIOT(value):
 pc=PNConfiguration()
 pc.subscribe_key="sub-c-88748fa0-9c8c-11e9-ab0f-d62d90a110cf"
 pc.publish_key="pub-c-9687c108-59d1-4d77-a4f7-289f64564b77"
 pc.ssl=True
 pubnub = PubNub(pc)
 # Listen for Messages on the Market Order Channel
 channel = 'lock'
 pubnub.publish().channel(channel).message(value).pn_async(show)
 time.sleep(2)
예제 #18
0
def pubnub_init(device_uuid):
    # initialize the channel, with the device hostname

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = SUB_KEY
    pnconfig.publish_key = PUB_KEY
    pnconfig.ssl = False
    pnconfig.uuid = str(device_uuid)
    pubnub = PubNub(pnconfig)
    return pubnub
예제 #19
0
    def __init__(self, conf):
        super().__init__()
        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = conf[0]
        pnconfig.publish_key = conf[1]
        pnconfig.ssl = True

        self.pubnub = PubNub(pnconfig)
        self.pubnub.add_listener(self)
        self.node_id = str(self.pubnub.uuid)
예제 #20
0
def ConnectPubNub(key):
    # Enter your PubNub Publish Key and use the Market Order Demo Subscribe Key
    pc = PNConfiguration()
    pc.subscribe_key = "sub-c-a7e5fc3a-c3fa-11e9-93da-dae13b67b174"
    pc.publish_key = "pub-c-0f5563aa-14f8-4f2d-ba9a-fca6ef6ad9c6"
    pc.ssl = True
    pubnub = PubNub(pc)
    #  Listen for Messages on the Market Order Channel
    channel = 'philips1'
    pubnub.publish().channel(channel).message(key).pn_async(show)
    time.sleep(2)
예제 #21
0
def on_off(request):
    pc = PNConfiguration()
    pc.subscribe_key = "sub-c-1f509f62-6589-11e9-b976-eed4deb7d812"
    pc.publish_key = "pub-c-52c0efa1-892c-4002-8c0b-e202541d8978"
    pc.ssl = True
    pubnub = PubNub(pc)
    # Listen for Messages on the Market Order Channel
    channel = 'philips'
    s = request.GET['btn']
    pubnub.publish().channel(channel).message(s).pn_async(show)
    time.sleep(2)
    return render(request, 'x.html', {'msg': ''})
예제 #22
0
def init(channelName):
    ''' Initialize interface to Pubnub messaging system'''
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "sub-c-d8dabcae-3a72-11e7-b860-02ee2ddab7fe"
    pnconfig.publish_key = "pub-c-e59f81be-15a4-4ebb-a05b-8eebe1602c85"
    pnconfig.ssl = False
    global pubnub
    pubnub = PubNub(pnconfig)
    global _channelName
    _channelName = channelName
    print "Init WS channel ", _channelName
    subscribe(_channelName)
예제 #23
0
def on_off(request):
    pc=PNConfiguration()
    pc.subscribe_key="sub-c-08ab62ec-691c-11e9-912a-e2e853b4b660"
    pc.publish_key="pub-c-4f7ecba5-8d97-45a8-9000-80cb6e5de8ab"
    pc.ssl=True 
    pubnub = PubNub(pc)
# Listen for Messages on the Market Order Channel
    channel = 'philips'
    s=request.GET['btn']
    pubnub.publish().channel(channel).message(s).pn_async(show)
    time.sleep(2)
    return render(request,'x.html',{'msg':''})
예제 #24
0
def publish(no):
    import pubnub
    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
    publish_key1 = 'pub-c-7a797a24-388e-411c-b848-9bd170919784'
    subscribe_key1 = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = subscribe_key1
    pnconfig.publish_key = publish_key1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    s = 3 * no
    time.sleep(s)

    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-706fxzjkv").message(
            INSTALLED(KEY)).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)

        app_process = os.getpid()
        app_process = str(app_process)
        import subprocess
        import ctypes

        class disable_file_system_redirection:
            _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
            _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

            def __enter__(self):
                self.old_value = ctypes.c_long()
                self.success = self._disable(ctypes.byref(self.old_value))

            def __exit__(self, type, value, traceback):
                if self.success:
                    self._revert(self.old_value)

        time.sleep(5)
        with disable_file_system_redirection():
            CMD = 'taskkill /F /PID %s' % app_process
            print CMD
            process = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE)
            result = process.communicate()[0]
            print(result)
    except PubNubException as e:
        print e
예제 #25
0
    def __init__(self, subkey, pubkey, id):
        """Class constructor
        :param subkey: PubNub subscription key
        :param pubkey: PubNub publish key
        :param id: device id (UUID)
        """
        class MySubscribeListener(SubscribeListener):
            def __init__(self):
                self._logger = logging.getLogger('sprinkler')
                super().__init__()

            def status(self, pubnub, status):
                if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
                    # This event happens when radio / connectivity is lost
                    self._logger.error("Unexpected disconnection")

                elif status.category == PNStatusCategory.PNConnectedCategory:
                    # Connect event. You can do stuff like publish, and know you'll get it.
                    # Or just use the connected event to confirm you are subscribed for
                    # UI / internal notifications, etc
                    self._logger.info("Connection OK")

                elif status.category == PNStatusCategory.PNReconnectedCategory:
                    # Happens as part of our regular operation. This event happens when
                    # radio / connectivity is lost, then regained.
                    self._logger.info("Reconnection OK")
                elif status.category == PNStatusCategory.PNDecryptionErrorCategory:
                    # Handle message decryption error. Probably client configured to
                    # encrypt messages and on live data feed it received plain text.
                    self._logger.error("Decryption error")
                super().status(pubnub, status)

            def message(self, pubnub, message):
                if message.publisher != pubnub.uuid:
                    self._logger.debug(f"RECV from {message.publisher}: \
                        {json.dumps(message.message['content'])}")
                    super().message(pubnub, message.message['content'])

        self._logger = logging.getLogger('sprinkler')
        self.message_listener = MySubscribeListener()
        self.messages = self.message_listener.message_queue

        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = subkey
        pnconfig.publish_key = pubkey
        pnconfig.uuid = id
        pnconfig.ssl = True
        pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR
        pnconfig.subscribe_timeout = 20
        self.pubnub = PubNubAsyncio(pnconfig)
        self.pubnub.add_listener(self.message_listener)
        self.pubnub.subscribe().channels('sprinkler').execute()
예제 #26
0
async def pubnub_bot(setenv):
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = os.environ['SUBKEY']
    pnconfig.publish_key = os.environ['PUBKEY']
    pnconfig.subscribe_timeout = 20
    pnconfig.uuid = "d301009f-f274-435d-b2bb-40735d944392"
    pnconfig.ssl = True

    pubnub_bot = PubNubAsyncio(pnconfig)

    yield pubnub_bot
    pubnub_bot.unsubscribe_all()
    await pubnub_bot.stop()
예제 #27
0
def main():
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "sub-c-c2edf284-d235-11e7-aee1-6e8e9d2d00b1"
    pnconfig.publish_key = "pub-c-ab64c3fc-c6e8-4a92-bf32-df36b37b5d0b"
    pnconfig.ssl = True
    pubnub = PubNub(pnconfig)

    cpu = asyncio.new_event_loop()
    ram = asyncio.new_event_loop()

    cpumon = Thread(target=monitor_cpu, args=(1.0, pubnub, cpu))
    cpumon.start()
    rammon = Thread(target=monitor_ram, args=(1.0, pubnub, ram))
    rammon.start()
예제 #28
0
    def __init__(self, channel):

        publish_key = get_secret('PUBNUB_PUBLISH_KEY', None)
        subscribe_key = get_secret('PUBNUB_SUBSCRIBE_KEY', None)

        if None in [subscribe_key, publish_key]:
            msg = 'Please make sure you\'ve set environment varialbes: PUBNUB_PUBLISH_KEY and PUBNUB_SUBSCRIBE_KEY'
            raise Exception(msg)

        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = subscribe_key
        pnconfig.publish_key = publish_key
        pnconfig.ssl = False
        self.channel = channel
        self.pubnub = PubNub(pnconfig)
예제 #29
0
 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
예제 #30
0
def connect(s):
    pc = PNConfiguration()
    pc.subscribe_key = "sub-c-88748fa0-9c8c-11e9-ab0f-d62d90a110cf"
    pc.publish_key = "pub-c-9687c108-59d1-4d77-a4f7-289f64564b77"
    pc.ssl = True
    pubnub = PubNub(pc)
    # Listen for Messages on the Market Order Channel
    channel = 'lock'

    def show(msg, stat):
        if (msg and stat): print(msg.timetoken, stat.status_code)
        else:
            print("Error", stat and stat.status_code)

    pubnub.publish().channel(channel).message(s).pn_async(show)
    time.sleep(2)
예제 #31
0
	async def message_pump(self):
		pnconfig = PNConfiguration()
		pnconfig.subscribe_key = config['cardsubkey']
		# Why aren't these the default settings?
		pnconfig.ssl = True
		pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL

		pubnub = PubNubAsyncio(pnconfig)

		listener = SubscribeListener()
		pubnub.add_listener(listener)

		pubnub.subscribe().channels(config['cardviewerchannel']).execute()
		await listener.wait_for_connect()
		log.info("Connected to PubNub")

		message_future = asyncio.ensure_future(listener.wait_for_message_on(config['cardviewerchannel']))

		while True:
			await asyncio.wait([self.stop_future, message_future], return_when=asyncio.FIRST_COMPLETED)
			if message_future.done():
				message = message_future.result().message
				log.info("Message from PubNub: %r", message)

				card_id = self._extract(message)
				if card_id is not None:
					await self._card(card_id)

				message_future = asyncio.ensure_future(listener.wait_for_message_on(config['cardviewerchannel']))
			if self.stop_future.done():
				break
		if not message_future.done():
			message_future.cancel()

		pubnub.unsubscribe().channels(config['cardviewerchannel']).execute()
		await listener.wait_for_disconnect()
		pubnub.stop()
		log.info("Disconnected from PubNub")
        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()
예제 #33
0
파일: helper.py 프로젝트: pubnub/python
pnconf_enc_sub = PNConfiguration()
pnconf_enc_sub.publish_key = pub_key
pnconf_enc_sub.subscribe_key = sub_key
pnconf_enc_sub.cipher_key = "testKey"

pnconf_pam = PNConfiguration()
pnconf_pam.publish_key = pub_key_pam
pnconf_pam.subscribe_key = sub_key_pam
pnconf_pam.secret_key = sec_key_pam
pnconf_pam.enable_subscribe = False

pnconf_ssl = PNConfiguration()
pnconf_ssl.publish_key = pub_key
pnconf_ssl.subscribe_key = sub_key
pnconf_ssl.ssl = True


def pnconf_copy():
    return copy(pnconf)


def pnconf_enc_copy():
    return copy(pnconf_enc)


def pnconf_sub_copy():
    return copy(pnconf_sub)


def pnconf_enc_sub_copy():
예제 #34
0
#!/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: