• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pubnub.Pubnub类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pubnub.Pubnub的典型用法代码示例。如果您正苦于以下问题:Python Pubnub类的具体用法?Python Pubnub怎么用?Python Pubnub使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Pubnub类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: setup

def setup(hass, config):
    """Setup the Wink component."""
    import pywink

    user_agent = config[DOMAIN][CONF_USER_AGENT]

    if user_agent:
        pywink.set_user_agent(user_agent)

    from pubnub import Pubnub
    access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)

    if access_token:
        pywink.set_bearer_token(access_token)
    else:
        email = config[DOMAIN][CONF_EMAIL]
        password = config[DOMAIN][CONF_PASSWORD]
        client_id = config[DOMAIN]['client_id']
        client_secret = config[DOMAIN]['client_secret']
        pywink.set_wink_credentials(email, password, client_id,
                                    client_secret)

    global SUBSCRIPTION_HANDLER
    SUBSCRIPTION_HANDLER = Pubnub(
        'N/A', pywink.get_subscription_key(), ssl_on=True)
    SUBSCRIPTION_HANDLER.set_heartbeat(120)

    # Load components for the devices in Wink that we support
    for component in WINK_COMPONENTS:
        discovery.load_platform(hass, component, DOMAIN, {}, config)
    return True
开发者ID:GadgetReactor,项目名称:home-assistant,代码行数:31,代码来源:wink.py


示例2: send_message

def send_message(app, message):
   app.logger.debug("Publish message {} to channel {}".format(message, PUBNUB_CHANNEL))

   client = Pubnub(publish_key=app.config['PUBNUB_PUBLISH'],
                   subscribe_key=app.config['PUBNUB_SUBSCRIBER'])
   return client.publish(channel=PUBNUB_CHANNEL,
                         message=message)
开发者ID:andysmith415,项目名称:porchlight,代码行数:7,代码来源:pubnub_client.py


示例3: setup

def setup(hass, config):
    """Setup the Wink component."""
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    import pywink
    from pubnub import Pubnub
    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])
    global SUBSCRIPTION_HANDLER
    SUBSCRIPTION_HANDLER = Pubnub("N/A", pywink.get_subscription_key(),
                                  ssl_on=True)
    SUBSCRIPTION_HANDLER.set_heartbeat(120)

    # Load components for the devices in the Wink that we support
    for component_name, func_exists in (
            ('light', pywink.get_bulbs),
            ('switch', lambda: pywink.get_switches or pywink.get_sirens or
             pywink.get_powerstrip_outlets),
            ('binary_sensor', pywink.get_sensors),
            ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays),
            ('lock', pywink.get_locks),
            ('rollershutter', pywink.get_shades),
            ('garage_door', pywink.get_garage_doors)):

        if func_exists():
            discovery.load_platform(hass, component_name, DOMAIN, {}, config)

    return True
开发者ID:12-hak,项目名称:hak-assistant,代码行数:30,代码来源:wink.py


示例4: __init__

class Pnub:
    
    def __init__(self, pkey, skey, channel):
        
        # Assign publisher key, subscriber key and channel1
        self.pkey = pkey
        self.skey = skey
        self.channel = channel
        
        # Create pubnub object
        self.pubnub = Pubnub(publish_key = self.pkey, subscribe_key = self.skey)
    
    def callback(self, m):
        #print(m)
        pass
        
    def error(self, m):
        print("Pubnub error:", m)
    
    def publish(self, keys, values):
        
        lenght = len(keys)
        if(lenght != len(values)):
            print("Lists must be of same length!")
            return
        
        json_map = {}
        for i in range(0, lenght):
            json_map[keys[i]] = values[i]
        
        result = json.dumps(json_map)    
        
        self.pubnub.publish(self.channel, result, callback = self.callback, error=self.error)
        
        
开发者ID:borislav-,项目名称:power_meter,代码行数:33,代码来源:pnub.py


示例5: pub_Init

def pub_Init():
	global pubnub
	try:
		pubnub = Pubnub(publish_key=pub_key,subscribe_key=sub_key) 
		pubnub.subscribe(channels='trail2pub_channel', callback=callback,error=error,
    	connect=connect, reconnect=reconnect, disconnect=disconnect)
	except Exception as pubException:
		print colored("The pubException is %s %s"%(pubException,type(pubException)),'red','on_white',attrs=['bold'])
开发者ID:adamalfar,项目名称:Smart-Traffic-Management-System-for-Emergency-Services,代码行数:8,代码来源:server.py


示例6: run

 def run(callback):
     pubnub = Pubnub(
         'demo',
         'sub-c-78806dd4-42a6-11e4-aed8-02ee2ddab7fe'
     )
     pubnub.subscribe(
         channels='pubnub-twitter',
         callback= callback
     )
开发者ID:tclain,项目名称:languages-on-twitter,代码行数:9,代码来源:twitter.py


示例7: notify

def notify(msg):
    pubnub = Pubnub(
            publish_key=os.getenv('PUBLISH_KEY'),
            subscribe_key=os.getenv('SUBSCRIBE_KEY'),
            pooling=False
    )
    channel = 'service_channel'

    # Synchronous usage
    print pubnub.publish(channel, msg)
开发者ID:jms,项目名称:compress_service,代码行数:10,代码来源:compress.py


示例8: send_to_channel

def send_to_channel(ch,name,obj):
    from pubnub import Pubnub
    pubnub = Pubnub(publish_key, subscribe_key)
    s=json.dumps(obj)
    dl='-_-_'+str(len(s)+1000000)[1:]
    s=s+dl
    logging.warning(str(len(s)-10)+" "+ str(len(urllib.quote(s.encode("utf-8")))+97)) #pana a 16000…;la 18000 da err
    page_num=name
    for i in xrange(0, len(s), 12000):
        pubnub.publish(ch, name+page_num+str(i+1000000)[1:]+s[i:i+12000], callback= _callback, error= _callback)
开发者ID:abacusadvertising,项目名称:SEO-Spider,代码行数:10,代码来源:BrokenLinks.py


示例9: __init__

class Client:
    command_key = "command"

    def __init__(self, channel):
        self.channel = channel
        # Publish key is the one that usually starts with the "pub-c-" prefix
        publish_key = "pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        # Subscribe key is the one that usually starts with the "sub-c" prefix
        # Do not forget to replace the string with your subscribe key
        subscribe_key = "sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        self.pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key)
        self.pubnub.subscribe(channels=self.channel,
                              callback=self.callback,
                              error=self.callback,
                              connect=self.connect,
                              reconnect=self.reconnect,
                              disconnect=self.disconnect)

    def callback_command_message(self, message):
        print("I've received the following response from PubNub cloud: {0}".format(message))

    def error_command_message(self, message):
        print("There was an error when working with the PubNub cloud: {0}".format(message))

    def publish_command(self, command_name, key, value):
        command_message = {
            self.__class__.command_key: command_name,
            key: value}
        self.pubnub.publish(
            channel=self.channel,
            message=command_message,
            callback=self.callback_command_message,
            error=self.error_command_message)

    def callback(self, message, channel):
        if channel == self.channel:
            print("I've received the following message: {0}".format(message))

    def error(self, message):
        print("Error: " + str(message))

    def connect(self, message):
        print("Connected to the {0} channel".
              format(self.channel))
        print(self.pubnub.publish(
            channel=self.channel,
            message="Listening to messages in the PubNub Python Client"))

    def reconnect(self, message):
        print("Reconnected to the {0} channel".
              format(self.channel))

    def disconnect(self, message):
        print("Disconnected from the {0} channel".
              format(self.channel))
开发者ID:PacktPublishing,项目名称:Internet-of-Things-with-Python,代码行数:55,代码来源:iot_python_chapter_09_04.py


示例10: main

def main():
    publish_key = os.environ['PUBNUB_PUBLISH_KEY']
    subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY']
    pubnub = Pubnub(publish_key, subscribe_key, ssl_on=False)
    try:
        cpu = system.SystemInfo()
        while True:
            pubnub.publish(channel="kiettv.raspberry.os", message=cpu.get_cpu_percent(), callback=None, error=callback)
            time.sleep(1)
    except KeyboardInterrupt:
        pubnub.unsubscribe(channel='kiettv.raspberry.os')
        exit(0)
开发者ID:vothanhkiet,项目名称:raspberry,代码行数:12,代码来源:main.py


示例11: ImagePublisher

class ImagePublisher(object):

    def __init__(self):
        self.pubnub = Pubnub(
            publish_key=PUBNUB_PUBLISH_KEY,
            subscribe_key=PUBNUB_SUBSCRIBE_KEY,
            cipher_key='',
            ssl_on=False)

    def publish_frame(self, jpeg_frame):
        message = base64.b64encode(jpeg_frame)
        self.pubnub.publish(PUBLISH_CHANNEL, message)
开发者ID:slobdell,项目名称:blimp-client,代码行数:12,代码来源:image_publisher.py


示例12: __init__

    def __init__(self, wink):
        """Initialize the Wink device."""
        from pubnub import Pubnub

        self.wink = wink
        self._battery = self.wink.battery_level
        if self.wink.pubnub_channel in CHANNELS:
            pubnub = Pubnub("N/A", self.wink.pubnub_key, ssl_on=True)
            pubnub.set_heartbeat(120)
            pubnub.subscribe(self.wink.pubnub_channel, self._pubnub_update, error=self._pubnub_error)
        else:
            CHANNELS.append(self.wink.pubnub_channel)
            SUBSCRIPTION_HANDLER.subscribe(self.wink.pubnub_channel, self._pubnub_update, error=self._pubnub_error)
开发者ID:krzynio,项目名称:home-assistant,代码行数:13,代码来源:wink.py


示例13: _send_image_back_to_user

def _send_image_back_to_user(phone_num_or_email, watermark_image_url):
    if COMPANY_SETTINGS["web_flow"]:
        # TODO vars need renaming
        pubnub = Pubnub(
            publish_key=PUBNUB_PUBLISH_KEY,
            subscribe_key=PUBNUB_SUBSCRIBE_KEY,
        )
        pubnub.publish(phone_num_or_email, watermark_image_url)

    elif COMPANY_SETTINGS["sms_photos"]:
        ImageTexter().text_image(phone_num_or_email, watermark_image_url)

    elif COMPANY_SETTINGS["email_photos"]:
        ImageEmailer().email_image(phone_num_or_email, watermark_image_url)
开发者ID:slobdell,项目名称:blimp-client,代码行数:14,代码来源:tasks.py


示例14: MyPubnubConn

class MyPubnubConn():

    def __init__(self, channel):
        self.conn = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, ssl_on=True,
                           # cipherkey randomly generated for purposes of PoC, but it is too short and needs to be
                           #   securely stored.
                           # cipher_key=cipher_key
                           )
        self.channel = channel
        self.subscribed = threading.Event()

        # server doesn't need to subscribe, only publish
        #self.conn.subscribe(channels=self.channel, callback=self.incoming_message, error=self.error_cb,
        #                     connect=self.connect_cb, reconnect=self.reconnect_cb, disconnect=self.disconnect_cb)

    def incoming_message(self, message, channel):
        pass
        #print(message)

    def error_cb(self, message):
        pass
        #print("\tERROR : " + str(message))

    def connect_cb(self, message):
        self.subscribed.set()

    def reconnect_cb(self, message):
        self.subscribed.set()
        #print("\tRECONNECTED")

    def disconnect_cb(self, message):
        self.subscribed.clear()
        #print("\tDISCONNECTED")

    def send_cb(self, message):
        pass

    def discontinue(self):
        self.conn.unsubscribe(channel=self.channel)

    def publish(self, message):
        self.conn.publish(channel=self.channel, message=message, callback=self.send_cb, error=self.error_cb)

    def wait_until_ready(self):
        self.subscribed.wait()

    def print_status(self):
        print("\nCurrently connected to channel '%s'" % self.channel)
开发者ID:greenzxz,项目名称:gzz-pubnub-demo,代码行数:48,代码来源:myPubnubConn.py


示例15: update

    def update(self, sessionToken, username):
        self.username = username
        self.sessionToken = sessionToken
        self.temperature = 0
        self.humidity = 0
        self.moisture = 0
        self.light = 0
        self.waterNow = False
        grovepi.pinMode(constants.LIGHT_PIN,"INPUT")
        grovepi.pinMode(constants.MOISTURE_PIN,"INPUT")
        grovepi.pinMode(constants.TEMP_HUMIDITY_PIN,"INPUT")
        grovepi.pinMode(constants.PUMP_RELAY_PIN,"OUTPUT")
        self.pubnub = Pubnub(publish_key=constants.PUBNUB_PUBLISH_KEY, subscribe_key=constants.PUBNUB_SUBSCRIBE_KEY, ssl_on = True)
        self.sendSensors = False
        while True: #keep trying until you have internet
            try:
                req = urllib2.Request(constants.ROOT_URL + 'active-plant')
                req.add_header('x-access-token', sessionToken)
                result = json.loads(urllib2.urlopen(req).read())

                self.waterAmount = result["waterAmount"]
                self.harvest = len(result["harvests"])
                self.moistureLimit = result["moistureLimit"]                
                break
            except Exception as e:
                s = str(e)
开发者ID:ndotz,项目名称:SmartGardenPi,代码行数:26,代码来源:SmartGarden.py


示例16: __init__

    def __init__(self):
        super().__init__()
        self._settings = OrderedDict(sorted(utils.init_settings().items(), key=lambda t: t[0]))
        self._history = utils.init_history()
        self._current_temperature = Decimal(0)
        self._temperature_range = (Decimal(0), Decimal(0))
        self._on_rpi = utils.on_rpi()
        self._mode = utils.Mode.OFF
        self._state = utils.State.IDLE

        self.logger = getLogger('app.thermostat')
        self.temperature_offset = Decimal('0.8')  # DEMO value, original Decimal('1.5')
        self.last_state_update = 0

        self.cost_table = None  # must init after thread starts
        self.pubnub = Pubnub(
            publish_key=config.PUBLISH_KEY,
            subscribe_key=config.SUBSCRIBE_KEY,
            uuid=config.THERMOSTAT_ID,
        )
        self.weather_thread = weather.WeatherAPI(
            self._settings['temperature_unit'],
            self._settings['city'],
            self._settings['country_code'],
        )
        # TODO: actively record user actions (input range, changes after prediction)
        self.history_thread = threading.Timer(600, self.set_history)
        self.history_thread.daemon = True
        self.locks = {
            'settings': threading.Lock(),
            'temperature_range': threading.Lock(),
        }
开发者ID:michael-mao,项目名称:titanium,代码行数:32,代码来源:thermostat.py


示例17: init

def init():
	#Pubnub Initialization
	global pubnub,client 
	pubnub = Pubnub(publish_key=PUB_KEY,subscribe_key=SUB_KEY)
	pubnub.subscribe(channels='garbageApp-req', callback=appcallback, error=appcallback, reconnect=reconnect, disconnect=disconnect)
	client = mqtt.Client()
	client.on_connect = on_connect
	client.on_message = on_message

	client.connect(HOST_IP, 1883, 60)

	# Blocking call that processes network traffic, dispatches callbacks and
	# handles reconnecting.
	# Other loop*() functions are available that give a threaded interface and a
	# manual interface.
	client.loop_forever()
开发者ID:suryasundarraj,项目名称:mqtt-rpi-ultrasonicSensor,代码行数:16,代码来源:garbageServer.py


示例18: main

def main(channel="devices", host="localhost", port=8086):
  #
  #initialize the PubNub handle
  #
  pub_key = os.environ['PUB_KEY']
  sub_key = os.environ['SUB_KEY']
  
  pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key)
  signal.signal(signal.SIGINT, signal_handler)
  
	# subscribe to a channel and invoke the appropriate callback when a message arrives on that 
	# channel
	#
  print("Subscribing from PubNub Channel '%s'" % (channel))
  pubnub.subscribe(channels=channel, callback=receive, error=on_error)
  pubnub.start()
开发者ID:agilemobiledev,项目名称:examples-2,代码行数:16,代码来源:subscribe_devices.py


示例19: __init__

	def __init__(self, url, keepAlive = False, sendReceipts = False):
		super(Server, self).__init__()
		self.sendReceipts = sendReceipts
		self.keepAlive = keepAlive
		self.db = create_engine(url, echo=False, pool_size=10, pool_timeout=600,pool_recycle=300)

		self.Session = sessionmaker(bind=self.db)
		self.s = self.Session()
		self.job = None

		self.pubnub = Pubnub(os.environ['PUB_KEY'], os.environ['SUB_KEY'], None, False)

		self.timeout = int(os.getenv('TIMEOUT', 3600))
		connectionManager = YowsupConnectionManager(self.timeout)

		connectionManager.setAutoPong(keepAlive)		

		self.signalsInterface = connectionManager.getSignalsInterface()
		self.methodsInterface = connectionManager.getMethodsInterface()
		
		self.signalsInterface.registerListener("message_received", self.onMessageReceived)
		self.signalsInterface.registerListener("group_messageReceived", self.onGroupMessageReceived)
		self.signalsInterface.registerListener("image_received", self.onImageReceived)
		self.signalsInterface.registerListener("video_received", self.onVideoReceived)
		self.signalsInterface.registerListener("audio_received", self.onAudioReceived)
		self.signalsInterface.registerListener("vcard_received", self.onVCardReceived)
		self.signalsInterface.registerListener("location_received", self.onLocationReceived)
		self.signalsInterface.registerListener("receipt_messageSent", self.onReceiptMessageSent)
		self.signalsInterface.registerListener("receipt_messageDelivered", self.onReceiptMessageDelivered)		
		
		self.signalsInterface.registerListener("auth_success", self.onAuthSuccess)
		self.signalsInterface.registerListener("auth_fail", self.onAuthFailed)
		self.signalsInterface.registerListener("disconnected", self.onDisconnected)

		self.signalsInterface.registerListener("contact_gotProfilePicture", self.onGotProfilePicture)
		self.signalsInterface.registerListener("profile_setStatusSuccess", self.onSetStatusSuccess)
		self.signalsInterface.registerListener("group_createSuccess", self.onGroupCreateSuccess)
		self.signalsInterface.registerListener("group_createFail", self.onGroupCreateFail)
		self.signalsInterface.registerListener("group_gotInfo", self.onGroupGotInfo)
		self.signalsInterface.registerListener("group_addParticipantsSuccess", self.onGroupAddParticipantsSuccess)
		self.signalsInterface.registerListener("group_removeParticipantsSuccess", self.onGroupRemoveParticipantsSuccess)
		self.signalsInterface.registerListener("group_imageReceived", self.onGroupImageReceived)


		self.signalsInterface.registerListener("group_subjectReceived", self.onGroupSubjectReceived)
		self.signalsInterface.registerListener("notification_removedFromGroup", self.onNotificationRemovedFromGroup)
		self.signalsInterface.registerListener("notification_groupParticipantAdded", self.onNotificationGroupParticipantAdded)
		self.signalsInterface.registerListener("group_gotParticipants", self.onGotGroupParticipants)

		self.signalsInterface.registerListener("media_uploadRequestSuccess", self.onUploadRequestSuccess)
		# self.signalsInterface.registerListener("media_uploadRequestFailed", self.onUploadRequestFailed)
		self.signalsInterface.registerListener("media_uploadRequestDuplicate", self.onUploadRequestDuplicate)
		self.signalsInterface.registerListener("presence_available", self.onPresenceAvailable)
		self.signalsInterface.registerListener("presence_unavailable", self.onPresenceUnavailable)
		
		self.cm = connectionManager
		self.url = os.environ['URL']

		self.post_headers = {'Content-type': 'application/json', 'Accept': 'application/json'}		
		self.done = False
开发者ID:pungoyal,项目名称:wassup,代码行数:60,代码来源:server.py


示例20: resetKeys

	def resetKeys(self):
		try:
			from pubnub import Pubnub
			self.pubnub = Pubnub(
				publish_key = str(self.pubEdit.text()),
				subscribe_key = str(self.subEdit.text()))
		except Exception as e:
			self.responseLabel.setText (e)
开发者ID:jithinbp,项目名称:SEELablet-apps,代码行数:8,代码来源:virtual.py



注:本文中的pubnub.Pubnub类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pubnub_asyncio.PubNubAsyncio类代码示例发布时间:2022-05-25
下一篇:
Python models.Feedback类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap