当前位置: 首页>>代码示例>>Python>>正文


Python pubnub.Pubnub类代码示例

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


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


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