def test_error_invalid_key(self): conf = PNConfiguration() conf.publish_key = "fake" conf.subscribe_key = "demo" self.pubnub = PubNubTornado(conf, custom_ioloop=self.io_loop) self.assert_server_side_error(self.pubnub.publish().channel(ch).message("hey"), "Invalid Key") self.assert_server_side_error_yield(self.pubnub.publish().channel(ch).message("hey"), "Invalid Key")
def test_error_invalid_key(self): conf = PNConfiguration() conf.publish_key = "fake" conf.subscribe_key = "demo" pubnub = PubNubTwisted(conf) with pytest.raises(PubNubTwistedException) as exception: yield pubnub.publish().channel(channel).message("hey").deferred() self.assertEqual(exception.value.status.error_data.information, "HTTP Client Error (400): [0, u'Invalid Key', u'14767989321048626']")
def test_error_invalid_key(event_loop): conf = PNConfiguration() conf.publish_key = "fake" conf.subscribe_key = "demo" conf.enable_subscribe = False pubnub = PubNubAsyncio(conf, custom_event_loop=event_loop) yield from assert_server_side_error_yield(pubnub.publish().channel(ch).message("hey"), "Invalid Key") pubnub.stop()
def main(): pnconf = PNConfiguration() pnconf.subscribe_key = 'demo' pnconf.publish_key = 'demo' pubnub = PubNub(pnconf) def my_publish_callback(result, status): # Check whether request successfully completed or not if not status.is_error(): envelope = result # noqa 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 def status(self, pubnub, status): if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: pass # This event happens when radio / connectivity is lost 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 pubnub.publish().channel("awesome_channel").message("Hello!").pn_async(my_publish_callback), elif status.category == PNStatusCategory.PNReconnectedCategory: pass # Happens as part of our regular operation. This event happens when # radio / connectivity is lost, then regained. elif status.category == PNStatusCategory.PNDecryptionErrorCategory: pass # Handle message decryption error. Probably client configured to # encrypt messages and on live data feed it received plain text. def message(self, pubnub, message): # Handle new message stored in message.message pass pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('awesome_channel').execute() reactor.callLater(30, pubnub.stop) # stop reactor loop after 30 seconds pubnub.start()
def test_invalid_key(self): config = PNConfiguration() config.publish_key = "fake" config.subscribe_key = "demo" config.enable_subscribe = False try: PubNub(config).publish() \ .channel("ch1") \ .message("hey") \ .sync() self.fail(Exception("Should throw exception", 'pnsdk')) except PubNubException as e: assert "Invalid Key" in str(e)
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") \ .async(self.callback) self.event.wait() assert self.status.is_error() assert self.status.category is PNStatusCategory.PNBadRequestCategory assert self.status.original_response[0] is 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)
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")
def test_reconnection(self): 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 = PubNubTornado(pnconf, custom_ioloop=self.io_loop) time_until_open_again = 10 @gen.coroutine def close_soon(): yield gen.sleep(3) pubnub.http.close() pubnub.http = None print(">>> connection is broken") @gen.coroutine def open_again(): yield gen.sleep(time_until_open_again) pubnub.http = tornado.httpclient.AsyncHTTPClient(max_clients=PubNubTornado.MAX_CLIENTS) print(">>> connection is open again") @gen.coroutine def countdown(): yield gen.sleep(2) opened = False count = time_until_open_again while not opened: print(">>> %ds to open again" % count) count -= 1 if count <= 0: break yield gen.sleep(1) my_listener = MySubscribeCallback() pubnub.add_listener(my_listener) pubnub.subscribe().channels('my_channel').execute() yield gen.sleep(1000)
from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from listener import Listener import os pnConfig = PNConfiguration() pnConfig.subscribe_key = os.environ['SUB_KEY'] pnConfig.publish_key = os.environ['PUB_KEY'] pnConfig.ssl = False pubNub = PubNub(pnConfig) my_listener = Listener() pubNub.add_listener(my_listener) pubNub.subscribe().channels('tv').execute()
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"}
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-bab9dc6c-912f-11e9-9769-e24cdeae5ee1" pnconfig.publish_key = "pub-c-14a2c33b-ff74-4bb7-8139-ff46eed621cc" pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels('awesomeChannel').execute() my_listener.wait_for_connect() print('connected') result = my_listener.wait_for_message_on('awesomeChannel') while result != "": print(result.message) result = my_listener.wait_for_message_on('awesomeChannel') if result.message == "bye": break print("bye") print("Disconnected")
import sys import datetime """ helper functions """ def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) """ config """ pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f' pubnub = PubNub(pnconfig) class BitflyerSubscribeCallback(SubscribeCallback): def presence(self, pubnub, presensce): pass def status(self, pubnub, status): if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: eprint("unexpected disconecct") elif status.category == PNStatusCategory.PNConnectedCategory:
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub # MIDI and Music-related imports import mido # Time imports for capturing roundtrip delay # Verbose printing if DEBUG is true DEBUG = False # Define Channel name channel_name = 'sensor_data' # Standard PubNub object configuration under V4 API pnconfig = PNConfiguration() pnconfig.publish_key = 'pub-c-ff1da703-9b2a-41df-bdd4-96e21bbfb0b8' pnconfig.subscribe_key = 'sub-c-d1024ca8-74bb-11e7-8153-0619f8945a4f' pubnub = PubNub(pnconfig) # New V4 Python API requires a callback def publish_callback(result, status): print(result) pass # Do nothing # Handle PNPublishResult and PNStatus print("Entering main loop. Press Control-C to exit.")
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()
from pubnub import utils from pubnub.pnconfiguration import PNConfiguration try: from mock import patch except ImportError: from unittest.mock import patch # noqa: F401 pub_key = "pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52" sub_key = "sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe" pub_key_pam = "pub-c-98863562-19a6-4760-bf0b-d537d1f5c582" sub_key_pam = "sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f" sec_key_pam = "sec-c-MGFkMjQxYjMtNTUxZC00YzE3LWFiZGYtNzUwMjdjNmM3NDhk" pnconf = PNConfiguration() pnconf.publish_key = pub_key pnconf.subscribe_key = sub_key pnconf.enable_subscribe = False pnconf_sub = PNConfiguration() pnconf_sub.publish_key = pub_key pnconf_sub.subscribe_key = sub_key pnconf_enc = PNConfiguration() pnconf_enc.publish_key = pub_key pnconf_enc.subscribe_key = sub_key pnconf_enc.cipher_key = "testKey" pnconf_enc.enable_subscribe = False pnconf_enc_sub = PNConfiguration()
from os import listdir from os.path import isfile, join, isdir import os import getpass from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive if platform.system() == "Linux": current_path = "/home/" + getpass.getuser() + "/Downloads/" elif platform.system() == "Darwin": current_path = "/Users/" + getpass.getuser() + "/Downloads/" elif platform.system() == "Windows": pass ###################################################################################################################################### pnconfig = PNConfiguration() # These two keys has to be read from some configuration file and put here # For the time being its hard coded but this part of the code needs change pnconfig.subscribe_key = 'sub-c-56f8fe2a-0dcd-11e7-83b6-0619f8945a4f' pnconfig.publish_key = 'pub-c-b432bbef-d96b-4a40-91d4-7ae1c6d96ee6' pubnub = PubNub(pnconfig) server_message = '' def my_publish_callback(envelope, status): # Check whether request successfully completed or not if not status.is_error(): print "Published" pass # Message successfully published to specified channel.
import time from backend.blockchain.block import Block from backend.wallet.transaction import Transaction from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback pnconfig = PNConfiguration() pnconfig.publish_key = 'pub-c-bc7c9878-925b-4cd4-8a88-a18c778acefc' pnconfig.subscribe_key = 'sub-c-901ca74a-b475-11ea-a40b-6ab2c237bf6e' CHANNELS = {'TEST': 'TEST', 'BLOCK': 'BLOCK', 'TRANSACTION': 'TRANSACTION'} class Listener(SubscribeCallback): def __init__(self, blockchain, transaction_pool): self.blockchain = blockchain self.transaction_pool = transaction_pool def message(self, pubnub, message_object): print( f'\n-- Channel: {message_object.channel} | Message: {message_object.message}' ) if message_object.channel == CHANNELS['BLOCK']: block = Block.from_json(message_object.message) # using ":" without indexes will copy the entire list potential_chain = self.blockchain.chain[:] potential_chain.append(block)
def mc(): config = PNConfiguration() config.subscribe_key = SUB_KEY return PubNub(config).message_counts()
try: from mock import patch except ImportError: from unittest.mock import patch # noqa: F401 crypto = PubNubCryptodome() pub_key = "pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52" sub_key = "sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe" pub_key_pam = "pub-c-98863562-19a6-4760-bf0b-d537d1f5c582" sub_key_pam = "sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f" sec_key_pam = "sec-c-MGFkMjQxYjMtNTUxZC00YzE3LWFiZGYtNzUwMjdjNmM3NDhk" pnconf = PNConfiguration() pnconf.publish_key = pub_key pnconf.subscribe_key = sub_key pnconf.enable_subscribe = False pnconf_sub = PNConfiguration() pnconf_sub.publish_key = pub_key pnconf_sub.subscribe_key = sub_key pnconf_enc = PNConfiguration() pnconf_enc.publish_key = pub_key pnconf_enc.subscribe_key = sub_key pnconf_enc.cipher_key = "testKey" pnconf_enc.enable_subscribe = False pnconf_enc_sub = PNConfiguration()
#!/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:
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)
# summary print(df.index[len(df) - 1].strftime('%H:%M:%S'), 'BU/SE', format(buy_vol, '.2f'), format(sell_vol, '.2f'), 'PRICE', ex_price, local_pos, format(order_profit, '.2f'), format(order_profit_rate, '.4f'), 'SMPF', format(sum_profit, '.2f')) config = PNConfiguration() config.subscribe_key = 'sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f' config.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNubTornado(config) # pubnub receive @gen.coroutine def main(channels): class BitflyerSubscriberCallback(SubscribeCallback): def presence(self, pubnub, presence): pass def status(self, pubnub, status): if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: pass elif status.category == PNStatusCategory.PNConnectedCategory: pass
from picamera import PiCamera from time import sleep import pytesseract from PIL import Image import RPi.GPIO as GPIO from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.IN) pubnubConf = PNConfiguration() pubnubConf.subscribe_key = 'sub-c-1aa69146-117c-11e7-9faf-0619f8945a4f' pubnubConf.publish_key = 'pub-c-a2c67d8e-1b26-4e00-878b-8b74a6ef3393' pubnubConf.ssl = False pubnub = PubNub(pubnubConf) def my_publish_callback(result, status): # Check whether request successfully completed or not if not status.is_error(): pass # Message successfully published to specified channel. print(result) else: print(status.original_response) 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];
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
from pubnub import utils from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory, PNOperationType from pubnub.pubnub_asyncio import PubNubAsyncio d = os.path.dirname PUBNUB_ROOT = d(d(d(os.path.dirname(os.path.abspath(__file__))))) APP_ROOT = d(os.path.abspath(__file__)) sys.path.append(PUBNUB_ROOT) from pubnub.exceptions import PubNubException from pubnub.pnconfiguration import PNConfiguration pnconf = PNConfiguration() pnconf.subscribe_key = "sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe" pnconf.publish_key = "pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52" pnconf.uuid = "pubnub-demo-api-python-backend" DEFAULT_CHANNEL = "pubnub_demo_api_python_channel" EVENTS_CHANNEL = "pubnub_demo_api_python_events" APP_KEY = utils.uuid() loop = asyncio.get_event_loop() pubnub = PubNubAsyncio(pnconf) def publish_sync(): return _not_implemented_error({ "error": "Sync publish not implemented" })
import logging import asyncio from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub_tornado import PubNubTornado from tornado.ioloop import IOLoop pnconfig = PNConfiguration() pnconfig.publish_key = "pub-c-98863562-19a6-4760-bf0b-d537d1f5c582" pnconfig.subscribe_key = "sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f" pnconfig.secret_key = "sec-c-MGFkMjQxYjMtNTUxZC00YzE3LWFiZGYtNzUwMjdjNmM3NDhk" pnconfig.auth_key = "blah" pnconfig.enable_subscribe = False pubnub = PubNubTornado(pnconfig) async def grant(): envelope = await pubnub.grant().auth_keys("blah").channels( "history_channel").read(True).write(True).ttl(0).future() print("Grant access: %r" % envelope.status.is_error()) logger = logging.getLogger("pubnub") async def publish500(): for i in range(0, 500): envelope = await pubnub.publish()\ .message(['message#', i])\
import pytest import pubnub as pn import tornado from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep pn.set_stream_logger('pubnub', logging.DEBUG) from tornado.testing import AsyncTestCase from pubnub.exceptions import PubNubException from pubnub.models.consumer.pubsub import PNPublishResult from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub_tornado import PubNubTornado, TornadoEnvelope, PubNubTornadoException from tests.helper import pnconf_sub_copy corrupted_keys = PNConfiguration() corrupted_keys.publish_key = "blah" corrupted_keys.subscribe_key = "blah" pn.set_stream_logger('pubnub', logging.DEBUG) ch = "tornado-publish" class TestPubNubTornadoInvocations(AsyncTestCase): def setUp(self): super(TestPubNubTornadoInvocations, self).setUp() @tornado.testing.gen_test def test_publish_resultx(self): pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop)
''' __author__ = "@sgript" Makeshift client for testcases + videos recorded. ''' import json import time from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pnconfiguration import PNConfiguration, PNReconnectionPolicy from pubnub.pubnub import PubNub, SubscribeListener pnconfig = PNConfiguration() pnconfig.uuid = 'speedtestClient' pnconfig.publish_key = 'pub-c-85d5e576-5d92-48b0-af83-b47a7f21739f' pnconfig.subscribe_key = 'sub-c-12c2dd92-860f-11e7-8979-5e3a640e5579' pnconfig.auth_key = 'V575MH48KA' # pnconfig.auth_key = '0F2D18PV1CTA4JIM98MX9FTZ87Q9IZ4FW53LRHXT3R' # admin key pnconfig.ssl = True pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.subscribe_timeout = pnconfig.connect_timeout = pnconfig.non_subscribe_timeout = 9 ^ 99 pubnub = PubNub(pnconfig) pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels('SECURE.BN9NDS0PFC').execute() my_listener.wait_for_connect()
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.exceptions import PubNubException from pubnub.pubnub import PubNub from random import * import time pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-cb6369c0-0fdf-11e8-91c1-eac6831c625c' pnconfig.publish_key = 'pub-c-50d55c74-1141-477e-9456-36f1126859c1' pubnub = PubNub(pnconfig) #Set default variables light = 'green' vel = 50 temp = 21.2 status = 'OK' #Traffic lights changes manager def lights (light): if (light == 'green'): light = 'yellow' return light if (light == 'yellow'): light = 'red' return light if (light == 'red'): light = 'green'
import flask, time from flask import session from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNOperationType, PNStatusCategory from config import Config pnconfig = PNConfiguration() pnconfig.subscribe_key = Config.get('pubnub_subscribe_key') pnconfig.publish_key = Config.get('pubnub_publish_key') pnconfig.ssl = False pubnub = PubNub(pnconfig) 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
import os import inspect import pprint from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub CHANNEL = "file_test" pnconfig = PNConfiguration() pnconfig.publish_key = os.environ["PUBNUB_PUBKEY"] pnconfig.subscribe_key = os.environ["PUBNUB_SUBKEY"] pnconfig.uuid = "serverUUID-SUB" pubnub = PubNub(pnconfig) envelop = pubnub.list_files().channel(CHANNEL).sync() pprint.pprint(envelop.result.data)
import time from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback from backend.blockchain.block import Block from backend.wallet.transaction import Transaction # subscribe_key = 'sub-c-a2d145cc-dada-11ea-b0f5-2a188b98e439' # publish_key = 'pub-c-414cb4ad-ba55-4832-9a1e-818c820b3810' pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-a2d145cc-dada-11ea-b0f5-2a188b98e439' pnconfig.publish_key = 'pub-c-414cb4ad-ba55-4832-9a1e-818c820b3810' pubnub = PubNub(pnconfig) CHANNELS = {'TEST': 'TEST', 'BLOCK': 'BLOCK', 'TRANSACTION': 'TRANSACTION'} class Listener(SubscribeCallback): def __init__(self, blockchain, transaction_pool): self.blockchain = blockchain self.transaction_pool = transaction_pool def message(self, pubnub, message_object): print( f'\n-- Channel : {message_object.channel} | Message:{message_object.message}' ) if message_object.channel == CHANNELS['BLOCK']: block = Block.from_json(message_object.message) potential_chain = self.blockchain.chain[:] potential_chain.append(block)
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from numpy import * import time m = [] r = [] nowTime = lambda: int(round(t * 1000)) t = time.time() pnconfig = PNConfiguration() pnconfig.subscribe_key = 'demo' pnconfig.publish_key = 'demo' pnconfig.uuid = "my_custom_uuid" 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):
import time from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback from backend.blockchain.block import Block pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-666638f6-ec63-11e9-b715-9abbdb5d0da2' pnconfig.publish_key = 'pub-c-82bf7695-ce5e-4bc5-9cd9-a8f8147dc2a8' CHANNELS = {'TEST': 'TEST', 'BLOCK': 'BLOCK'} class Listener(SubscribeCallback): def __init__(self, blockchain): self.blockchain = blockchain def message(self, pubnub, message_object): print( f'\n-- Channel: {message_object.channel} | Message: {message_object.message}' ) if message_object.channel == CHANNELS['BLOCK']: block = Block.from_json(message_object.message) potential_chain = self.blockchain.chain[:] potential_chain.append(block) try: self.blockchain.replace_chain(potential_chain)
import time from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback from backend.blockchain.block import Block pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-7c05ce8e-61ab-11ea-aaa3-eab2515ceb0d' pnconfig.publish_key = 'pub-c-d7e75e4e-3274-4017-83d4-e940969268e1' pnconfig.reconnect_policy = 'PNReconnectionPolicy.EXPONENTIAL' CHANNELS = { 'TEST': 'TEST', 'BLOCK': 'BLOCK' } class Listener(SubscribeCallback): def __init__(self, blockchain): self.blockchain = blockchain def message(self, pubnub, message_object): print(f'\n-- Channel: {message_object.channel} | Message: {message_object.message}') if message_object.channel == CHANNELS['BLOCK']: block = Block.from_json(message_object.message) potential_chain = self.blockchain.chain[:] potential_chain.append(block) try:
import serial import time from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from pubnub.enums import PNStatusCategory from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNOperationType, PNStatusCategory pnconfig = PNConfiguration() pnconfig.subscribe_key = "" pnconfig.publish_key = "" pnconfig.ssl = False ser = serial.Serial('COM4', 9600) #Right around y-axis def wheel_turn_side(): return ser.write(b'2') #Left around x-axis def wheel_turn_vert(): return ser.write(b'1') #Left around y-axis def wheel_turn_side_rev(): return ser.write(b'5') #Right around x-axis def wheel_turn_vert_rev(): return ser.write(b'6')
import time from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback from backend.blockchain.block import Block from backend.wallet.transaction import Transaction subscribe_key = 'sub-c-75660ee4-8998-11ea-927a-2efbc014b69f' publish_key = 'pub-c-37f6471e-7c0e-4ec6-9244-01ab03b15326' pnconfig = PNConfiguration() pnconfig.subscribe_key = subscribe_key pnconfig.publish_key = publish_key CHANNELS = { 'TEST': 'TEST', 'BLOCK': 'BLOCK', 'TRANSACTION': 'TRANSACTION' } class Listener(SubscribeCallback): def __init__(self, blockchain, transaction_pool): self.blockchain = blockchain self.transaction_pool = transaction_pool def message(self, pubnub, message_object): print(f'\n-- Channel: {message_object.channel} | Message: {message_object.message}') if message_object.channel == CHANNELS['BLOCK']:
# Example Code of BMP180 Bosch Sensor connecting to PubNub # Running on a Raspberry Pi 2 # IoTIFY TECHNOLOGIES SL # 05-JULY -2017 from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub import time pnconfig = PNConfiguration() # SUBSCRIBE Key pnconfig.subscribe_key = 'sub_INTRODUCE_COMPLTE_SUB_KEY' # PUBLISH Key pnconfig.publish_key = 'pub-INTRODUCE_COMPLTE_PUB_KEY' pnconfig.ssl = False pubnub = PubNub(pnconfig) import Adafruit_BMP.BMP085 as BMP085 from time import gmtime, strftime # Raspberry Pi 2 uses I2C bus number 1 sensor = BMP085.BMP085(busnum=1) channel = "my_channel" # You can also optionally change the BMP085 mode to one of BMP085_ULTRALOWPOWER,
import serial import RPi.GPIO as GPIO import time, threading 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-25e6eef0-f44e-11e8-b4b3-36001c7c3431' pnconfig.publish_key = 'pub-c-09074860-0d78-4dce-90de-ad5efe037e74' pubnub = PubNub(pnconfig) myChannel = "myIOT" PIR_pin = 23 Buzzer_pin = 24 sensorsList = ["buzzer"] data = {} GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(PIR_pin, GPIO.IN) GPIO.setup(Buzzer_pin, GPIO.OUT) ser = serial.Serial('/dev/ttyACM0', 9600) def beep(repeat): for i in range(0, repeat):
# importing pubnub libraries from pubnub.pubnub import PubNub, SubscribeListener, SubscribeCallback, PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.exceptions import PubNubException from plantower import pt_pms5003 from ds18b20 import ds18b20_read import pubnub pnconf = PNConfiguration() pnconf.publish_key = '' pnconf.subscribe_key = '' pubnub = PubNub(pnconf) channel = 'jinz_station' pmx_str = 'jinz_getpmx' temp_str = 'jinz_gettemp' data = { # data to be published 'username': '******', 'message': 'Test Publish' } class MyListener(SubscribeCallback): # Not need for working of this program def status(self, pubnub, status): if status.category == PNStatusCategory.PNConnectedCategory: pubnub.publish().channel(channel).message({ 'fieldA': 'awesome', 'fieldB': 10 }).sync()
import logging import pubnub from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub_tornado import PubNubTornado, SubscribeListener from tornado.ioloop import IOLoop from tornado import gen pubnub.set_stream_logger('pubnub', logging.DEBUG) pnconfig = PNConfiguration() pnconfig.publish_key = "demo" pnconfig.subscribe_key = "demo" pubnub = PubNubTornado(pnconfig) @gen.coroutine def main(): my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels("awesomeChannel").execute() yield my_listener.wait_for_connect() print("connected") yield pubnub.publish().channel("awesomeChannel").message({'fieldA': 'awesome', 'fieldB': 10}).future() result = yield my_listener.wait_for_message_on("awesomeChannel") print(result.message)
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub import time import os pnconfig = PNConfiguration() pnconfig.publish_key = 'enter your pubnub publish key here' pnconfig.subscribe_key = 'enter your pubnub subscribe key here' pnconfig.ssl = True pubnub = PubNub(pnconfig) def my_publish_callback(envelope, status): # Check whether request successfully completed or not if not status.is_error(): pass class MySubscribeCallback(SubscribeCallback): def presence(self, pubnub, presence): pass def status(self, pubnub, status): pass def message(self, pubnub, message): print "from device 1: " + message.message
import requests import json import threading from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub import sched,time import os import threading import socket from twisted.internet import task, reactor pnconfig = PNConfiguration() pnconfig.publish_key = 'pub-c-cbac1ba8-84b2-469d-a59b-7d66d9b4cb2a' pnconfig.subscribe_key = 'sub-c-88b6488e-3adb-11eb-b6eb-96faa39b9528' pnconfig.ssl = True pubnub = PubNub(pnconfig) accidentDataFetched = None accidentDataPostResponse = None class PostAccidentSignalData: def __init__(self, rsuId, accidentLongitude, accidentLatitude, accidentVehicleId): self.rsuId = rsuId self.accidentLongitude = accidentLongitude self.accidentLatitude = accidentLatitude self.accidentVehicleId = accidentVehicleId def my_publish_callback(envelope, status): # Check whether request successfully completed or not
import time import RPi.GPIO as GPIO # Initialize the pubnub service from pubnub.pnconfiguration import PNConfiguration from pubnub.exceptions import PubNubException from pubnub.pubnub import PubNub # Set up the indicator LEDs GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) # Pin for when running GPIO.setup(20, GPIO.OUT) # Pin for error # Set up Pubnub configuration pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-24d83964-40ef-11e8-a2e8-d2288b7dcaaf" pnconfig.publish_key = "pub-c-deda0dd4-b711-466b-8bbb-c12e7e0e43e0" pnconfig.ssl = False pubnub = PubNub(pnconfig) channel_name = "temperature_monitoring" # Configure the bme interface port = 1 address = 0x77 bus = smbus2.SMBus(port) calibration_params = bme280.load_calibration_params(bus, address)
import pubnub from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub #from gpiozero import Button from time import sleep pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-1575c412-2116-11e8-a7d0-2e884fd949d2" pnconfig.publish_key = "pub-c-2d8f55f6-daa7-467b-923b-6a1e6570c9fc" pnconfig.ssl = False pubnub = PubNub(pnconfig) def publish_callback(result, status): pass # Handle PNPublishResult and PNStatus button = Button(5) tweet = "Hello World" msg = {"tweet": tweet} while True: if button.is_pressed: print("Pressed") pubnub.publish().channel('twitter-input').message(msg). async ( publish_callback) else: print("Released")
#!/usr/bin/python3 from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback from pubnub.exceptions import PubNubException from pubnub.pubnub import PubNub, SubscribeListener import sys pubconf = PNConfiguration() pubconf.subscribe_key = 'sub-c-dbf66bda-16b9-11e8-8f67-36fe363f7ef0' pubconf.publish_key = 'pub-c-14a6f403-3bab-4945-8656-7cba4ca4bb1f' secret_key = "sec-c-Nzk1ZWE3OTItNjdkOS00ZDVlLThiZjAtODBmMWU2MjI2Y2Ji" pubconf.ssl = False pubnub = PubNub(pubconf) # assign a channel my_channel = 'pi-weather-station' my_listener = SubscribeListener() pubnub.add_listener(my_listener) # # pubnub.subscribe(my_channel) # pubnub.start() def disconnect_channel(): pubnub.unsubscribe().channels(my_channel).execute() my_listener.wait_for_disconnect() print('unsubscribed')
import os from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub os.environ["pubsub_uuid"] = "feerposser-pc" pnconfig = PNConfiguration() pnconfig.publish_key = os.getenv("pubsub_pub") pnconfig.subscribe_key = os.getenv("pubsub_sub") pnconfig.uuid = os.getenv("pubsub_uuid") canal = "imedccso" usr = input("Seu nome: ") print("-" * 50) pubnub = PubNub(pnconfig) while True: msg = input("Fala ae: ") envelope = pubnub.publish().channel(canal).message({ "msg": msg, "usr": usr }).sync() if envelope.status.is_error(): print("->>>>> DEU PAU")
# You can use this same file on another raspberry pi or your computer and execute the file on both of them to exchange messages # install pubnub using the pip with following way not the 3. #sudo pip install 'pubnub>=4.0.13' import json, re from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub import RPi.GPIO as GPIO import time import sys pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-74c2a3a2-9b76-11e7-bec3-c65ebd354f7d' pnconfig.publish_key = 'pub-c-73a9c60e-26a6-4e5e-a92a-858d0a7247e2' pubnub = PubNub(pnconfig) GPIO.setmode (GPIO.BCM) GPIO.setwarnings(False) LED_PIN = 20 GPIO.setup(LED_PIN,GPIO.OUT)
from pubnub.pnconfiguration import PNConfiguration pnconf = PNConfiguration() pnconf.subscribe_key = "demo" pnconf.publish_key = "demo" pnconf.enable_subscribe = False
#PubNub import json #import pubnub pubnub.com/docs/python/pubnub-python-sdk from pubnub.pubnub import PubNub from pubnub.enums import PNStatusCategory, PNOperationType from pubnub.callbacks import SubscribeCallback from pubnub.pnconfiguration import PNConfiguration pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-911576ee-7967-11e9-89f1-56e8a30b5f0e' pnconfig.publish_key = 'pub-c-db0a76ee-2837-4015-8c80-fd01dd0e7f3a' pnconfig.uuid = 'dave' pubnub = PubNub(pnconfig) # from datetime import datetime import MySQLdb as mdb # DebugOn = False class MySubscribeCallback(SubscribeCallback): def status(self, pubnub, status): # 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:
import sys sys.path.append(".") import time from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback from backend.wallet.transaction import Transaction from backend.blockchain.block import Block pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-3ce86af8-aa68-11ea-baa3-a65cc700836a' pnconfig.publish_key = 'pub-c-a4f9cea7-1543-45bc-8464-8b8696a5dfbb' CHANNELS = { 'TEST': 'TEST', 'BLOCK': 'BLOCK', 'TRANSACTION': 'TRANSACTION' } class Listener(SubscribeCallback): def __init__(self, blockchain, transaction_pool): self.blockchain = blockchain self.transaction_pool = transaction_pool def message(self, pubnub, message_object): print(f'\n-- Channel: {message_object.channel} | Message: {message_object.message}') if message_object.channel == CHANNELS['BLOCK']: block = Block.from_json(message_object.message) potential_chain = self.blockchain.chain[:] potential_chain.append(block)
# Create login on pubnub.com # Copy the publish and subscribe keys from the demo project. # Replace the keys in this code (demo and demo) with your keys # On Raspberry Pi terminal - sudo pip install pubnub # Execute this file (with your keys) - A message will be published and the same terminal will also show the message as received. # You can use this same file on another raspberry pi or your computer and execute the file on both of them to exchange messages 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 = '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(): print ("Message published\n") #pass # Message successfully published to specified channel. else: print "Message publish failed" #pass # Handle message publish error. Check 'category' property to find out possible issue