本文整理汇总了Python中Pubnub.Pubnub.subscribe方法的典型用法代码示例。如果您正苦于以下问题:Python Pubnub.subscribe方法的具体用法?Python Pubnub.subscribe怎么用?Python Pubnub.subscribe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Pubnub.Pubnub
的用法示例。
在下文中一共展示了Pubnub.subscribe方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RemotePubNub
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
class RemotePubNub():
def __init__(self, PUBNUB_PUBLISH_KEY="demo", PUBNUB_SUBSCRIBE_KEY="demo", queue=None):
self.pubnub = Pubnub(publish_key=PUBNUB_PUBLISH_KEY, subscribe_key=PUBNUB_SUBSCRIBE_KEY)
self.queue = queue
def get_queue(self):
return self.queue
def publish(self, channel, message):
self.pubnub.publish(channel, message)
#logging.info("message published")
def subscribe(self, channel):
self.pubnub.subscribe(
channel, callback=self.parse_command, error=self.sub_error,
connect=self.sub_connect, disconnect=self.sub_disconnect)
def parse_command(self, message, channel):
if self.queue is not None:
print message
self.queue.put(message)
def sub_error(message):
logging.ERROR(message)
def sub_connect(self, channel):
message = 'Connected to: %s' % channel
logging.info(message)
def sub_disconnect(self, message):
logging.info(message)
示例2: run
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
def run(self, channel, latency, bufferSize):
self.mutex = Lock()
self.outqueuebuffers = {}
self.outbuffers = {}
self.senders = {}
self.channels = None
self.channel = channel
self.buffer_size = bufferSize
self.timestamp_buffer = [None] * self.buffer_size
self.debug = False
self.index = 0
self.offset = None
self.latency = latency
self.setupDone = False
self.channel_count = 0
pubnub = Pubnub("pub-c-e655613e-f776-4301-9f29-f71edbcd6559",
"sub-c-2eafcf66-c636-11e3-8dcd-02ee2ddab7fe",
"sec-c-ZjUwZDgzMTItYzE2Mi00ZGYyLTg2NGMtNmE5N2Q3MGI0MTli",
False)
self.m = MQTT()
broker = config.mqtt['Broker']
print("Connecting to broker: " + broker)
self.m.connect(broker)
while(True):
pubnub.subscribe({
'channel': self.channel,
'callback': self.setData
})
示例3: main
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
def main():
resetAVR()
print("Establishing Connections...")
pubnub = Pubnub(publish_key = 'pub-c-f83b8b34-5dbc-4502-ac34-5073f2382d96',
subscribe_key = 'sub-c-34be47b2-f776-11e4-b559-0619f8945a4f',
uuid = "pi")
channel = 'leap2pi'
GPIO.output(4, False)
def _connect(m):
print("Connected to PubNub!")
GPIO.output(4, True)
def _reconnect(m):
print("Reconnected to PubNub!")
GPIO.output(4, True)
def _disconnect(m):
print("Disconnected from PubNub!")
GPIO.output(4, False)
def _callback(m,n):
left_byte = 0
right_byte = 0
# ==============================Left Hand==============================
left_hand = m.get("left_hand",{})
if left_hand != {}:
left_byte = handleLeft(left_hand)
#print(left_hand)
# ==============================Right Hand=============================
right_hand = m.get("right_hand",{})
if right_hand != {}:
right_byte= handleRight(right_hand)
#print(right_hand)
byte = left_byte | right_byte
#print(byte)
#====send i2c=====#
try:
bus.write_byte(0x47,byte)
except IOError:
print("Error!!!!")
resetAVR()
bus.write_byte(0x47,byte)
#Catch and Print Error
def _error(m):
GPIO.output(4, False)
print(m)
#Subscribe to subchannel, set callback function to _callback and set error fucntion to _error
pubnub.subscribe(channels=channel, callback=_callback, error=_error, connect=_connect, reconnect=_reconnect, disconnect=_disconnect)
示例4: startStockPicker
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
def startStockPicker(server,port):
global globalQueueRef
#Step 1 - Initialize MongoDB & PubNub Connection
mongoconn = pymongo.MongoClient(server,port)
db = mongoconn.stockdb
coll = db.stockcollection
#Setup index on time to fetch the latest update
coll.create_index([('time',DESCENDING)])
#YOUR PUBNUB KEYS - Replace the publish_key and subscriber_key below with your own keys
pubnub = Pubnub(publish_key="<your publish key>",subscribe_key="<your subscribe key>")
#Step 2 - Check and define the metadata ( index names )
metaDataInit(coll)
#Step 3 - Set the parameters , max periodicity , random range
updateTime = 10 #Max ten seconds for every price update
numOfItems = 4 #Four indices to manage
random.seed()
#Step 4 - Setup the Queue and ClientListener Thread
clientQueue = Queue()
clientListener = ClientListenerThread(server,port,clientQueue,pubnub)
clientListener.start()
globalQueueRef = clientQueue
#Step 5 - Setup PubNub Subscription for client requests
pubnub.subscribe("stockhistory", historyCallback,historyError)
#Step 6 - Start the stock picking loop
while True:
#Step 6.1 - Wait for random time
time.sleep(random.randint(1,updateTime))
#Step 6.2 - Wake up and update the stock price for one of the index
newPriceData = getUpdatedPrice(coll)
#Step 6.3 - Update the new price in DB
print "New Price Update " + str(newPriceData)
coll.insert(newPriceData)
#Step 6.4 - Publish over Pubnub , stockdata channel
broadcastData = { 'name' : newPriceData['name'],
'value' : newPriceData['value'],
'change' : newPriceData['change'],
'time' : newPriceData['time'],
}
pubnub.publish('stockdata',json.dumps(broadcastData))
示例5: startStockPicker
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
def startStockPicker(server,port):
global globalQueueRef
global graph
#Step 1 - Initialize MongoDB & PubNub Connection
# py2neo.set_auth_token('%s:%s' % (NEO_HOST, NEO_PORT), NEO_AUTH_TOKEN)
graph = Graph('%s://%s:%[email protected]%s:%s/db/data/' %
(NEO_PROTOCOL, NEO_USER, NEO_PASSWORD, NEO_HOST, NEO_PORT))
#YOUR PUBNUB KEYS - Replace the publish_key and subscriber_key below with your own keys
pubnub = Pubnub(publish_key="<your pub key>",subscribe_key="<your sub key>")
#Step 2 - Check and define the metadata ( index names )
metaDataInit()
#Step 3 - Set the parameters , max periodicity , random range
updateTime = 10 #Max ten seconds for every price update
numOfItems = 4 #Four indices to manage
random.seed()
#Step 4 - Setup the Queue and ClientListener Thread
clientQueue = Queue()
clientListener = ClientListenerThread(server,port,clientQueue,pubnub)
clientListener.start()
globalQueueRef = clientQueue
#Step 5 - Setup PubNub Subscription for client requests
pubnub.subscribe("stockhistory", historyCallback,historyError)
#Step 6 - Start the stock picking loop
while True:
#Step 6.1 - Wait for random time
time.sleep(random.randint(1,updateTime))
#Step 6.2 - Wake up and update the stock price for one of the index
newPriceData = getUpdatedPrice()
#Step 6.3 - Update the new price in DB
print "New Price Update " + str(newPriceData)
#Step 6.4 - Publish over Pubnub , stockdata channel
broadcastData = { 'name' : newPriceData['name'],
'value' : newPriceData['value'],
'change' : newPriceData['change'],
'time' : newPriceData['time'],
}
pubnub.publish('stockdata',json.dumps(broadcastData))
示例6: iotbridge
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
class iotbridge(object):
def __init__(self, publish_key, subscribe_key, uuid):
self.publish_key = publish_key
self.subscribe_key = subscribe_key
self.uuid = uuid
self.pubnub = Pubnub("demo", "demo", None, False)
self.pubnub.uuid = self.uuid
def send(self, channel, message):
# Sending message on the channel
self.pubnub.publish(channel, message)
def connect(self, channel, callback):
# Listening for messages on the channel
self.pubnub.subscribe(channel, callback=callback)
示例7: init
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
def init(func):
global pubnub
global pubnub_freeboard
global message_cb
try:
message_cb = func
log.info("pubnub SUBSCRIBE")
pubnub = Pubnub(publish_key=PUB_KEY, subscribe_key=SUB_KEY, cipher_key=CHIPER_KEY, ssl_on=True)
pubnub.subscribe(CHANNEL, callback=pubnub_message_cb, error=pubnub_error_cb, connect=pubnub_connect_cb, reconnect=pubnub_reconnect_cb, disconnect=pubnub_disconnect_cb)
pubnub_freeboard = Pubnub(publish_key=PUB_KEY, subscribe_key=SUB_KEY, ssl_on=False)
log.info("pubnub SUBSCRIBED")
except:
log.error("Error initializing pubnub...Cannot continue")
raise SystemExit
示例8: Streamteam
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
class Streamteam(object):
def __init__(self, args):
self.channel = args.channel
self.pubnub = Pubnub(
args.publish,
args.subscribe,
None,
False
)
def publish(self, m):
def callback(message):
return message
self.pubnub.publish(
self.channel,
m,
callback=callback,
error=callback
)
def subscribe(self):
def callback(message, channel):
print(message)
def error(message):
print("ERROR : " + str(message))
def connect(message):
print("CONNECTED")
def reconnect(message):
print("RECONNECTED")
def disconnect(message):
print("DISCONNECTED")
self.pubnub.subscribe(
self.channel,
callback=callback,
error=callback,
connect=connect,
reconnect=reconnect,
disconnect=disconnect
)
示例9: main
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
def main():
print "started"
global t
t = threading.Timer(TEMPO, callback_timer)
t.start()
pubnub = Pubnub(
"pub-e10385fe-9f9f-46a4-b969-f3c8ba11ff59", ## PUBLISH_KEY
"sub-f8f2ff3a-a176-11e1-bbc1-f151a023fb9a", ## SUBSCRIBE_KEY
"sec-OGY5MTk3Y2QtMDY2OS00NThiLTlmZjItNWFkZGM3NDgxMmZi",
False
)
print("subscribing...")
pubnub.subscribe({
'channel' : 'fbhackaton_newquestion',
'callback' : receive
})
示例10: Streamteam
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
class Streamteam(object):
def __init__(self, args):
self.channel = args.channel
self.pubnub = Pubnub(
args.publish,
args.subscribe,
None,
False
)
def publish(self, message):
self.pubnub.publish({
'channel' : self.channel,
'message' : message
})
def subscribe(self):
def receive(message):
# q = ""
s = ""
v = ""
names = "gyroX gyroY AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4".split(" ")
os.system('clear')
for i in names:
# q += str(message['quality'][i]) + " "
v += str(message['values'][i]) + " "
while len(i) < 7:
i += " "
s += i
print("Channel : " + s)
# print("Quality : " + q)
print("Values : " + v)
return True
self.pubnub.subscribe({
'channel' : self.channel,
'callback' : receive
})
示例11: WatchRemote
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
class WatchRemote():
"""monitoring remote repository"""
def __init__(self, pid, path, key ):
self.pid = pid
self.path = path
self.pubnub = Pubnub( None, key, None, False )
def receive(self,message) :
notify('GitBox Download', 'receiving new and changed files in %s' % self.path)
cmd = 'git push'
process = subprocess.Popen(cmd.split(' '), cwd=self.path)
process.communicate()
return True
def start(self):
## Initiat Class
self.pubnub.subscribe({'channel' : self.pid, 'callback' : self.receive })
def stop(self):
pass
示例12: Pubnub
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
ser = serial.Serial('COM4', 9600)
pubnub = Pubnub(publish_key="pub-c-6a3d5bbe-652b-49a2-bca1-ccb6db8bb50d", subscribe_key="sub-c-5fa82184-f7ba-11e4-8fd2-02ee2ddab7fe")
def _callback(message, channel):
if message["sender"] == "browser":
print(message['setSystemStatus'])
signal.set()
#time.sleep(2)
out_message = {"sender": "bric", "body": "status update"}
pubnub.publish("demo_tutorial", out_message, callback=callback, error=callback)
def _error(message):
print("error")
pubnub.subscribe(channels="demo_tutorial", callback=_callback, error=_error)
def callback(message):
print("callback place holder")
while True:
if not signal.is_set():
s = ser.readline()
out_message = {"sender": "bric", "body": s}
pubnub.publish("demo_tutorial", out_message, callback=callback(out_message), error=callback(out_message))
time.sleep(1)
elif signal.is_set():
print "status configuration"
time.sleep(2)
output = subprocess.check_output('ipconfig')
print("Programming Arduino...done")
示例13: main
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
def main():
resetAVR()
print("Establishing Connections...")
pubnub = Pubnub(publish_key = 'pub-c-f83b8b34-5dbc-4502-ac34-5073f2382d96',
subscribe_key = 'sub-c-34be47b2-f776-11e4-b559-0619f8945a4f',
uuid = "pi")
channel = 'leap2pi'
GPIO.output(4, False)
def checkValue(value):
if (value < SERVO_MIN):
value = SERVO_MIN
elif(value > SERVO_MAX):
value = SERVO_MAX
return value
def invertValue(value):
value = checkValue(value)
return SERVO_MAX - value + SERVO_MIN
def _connect(m):
print("Connected to PubNub!")
GPIO.output(4, True)
def _reconnect(m):
print("Reconnected to PubNub!")
GPIO.output(4, True)
def _disconnect(m):
print("Disconnected from PubNub!")
GPIO.output(4, False)
def _callback(m,n):
left_byte = 0
right_byte = 0
yaw = 0
pitch = 0
byte = 0
# Handle message
left_hand = m.get("left_hand",{})
right_hand = m.get("right_hand",{})
if (servo_mode == MIRROR):
# Leap Motion: Left hand, Servos: Stage Left
if left_hand != {}:
yaw = left_hand["left_yaw"]
yaw = checkValue(yaw)
pitch = left_hand["left_pitch"]
pitch = checkValue(pitch)
left_byte = left_hand["left_byte"]
pwm.setPWM(0, 0, yaw)
pwm.setPWM(1, 1, pitch)
# Leap Motion: Left hand, Servos: Stage Right
if right_hand != {}:
yaw = right_hand["right_yaw"]
yaw = checkValue(yaw)
pitch = right_hand["right_pitch"]
pitch = checkValue(pitch)
right_byte = right_hand["right_byte"] >> 4
pwm.setPWM(2, 2, yaw)
pwm.setPWM(3, 3, pitch)
byte = left_byte | (right_byte << 4)
elif (servo_mode == CLONE):
# Leap Motion: Left hand, Servos: Stage Right
if left_hand != {}:
yaw = left_hand["left_yaw"]
yaw = invertValue(yaw)
pitch = left_hand["left_pitch"]
pitch = invertValue(pitch)
left_byte = left_hand["left_byte"]
pwm.setPWM(2, 2, yaw)
pwm.setPWM(3, 3, pitch)
# Leap Motion: Left hand, Servos: Stage Left
if right_hand != {}:
yaw = right_hand["right_yaw"]
yaw = invertValue(yaw)
pitch = right_hand["right_pitch"]
pitch = invertValue(pitch)
right_byte = right_hand["right_byte"] >> 4
pwm.setPWM(0, 0, yaw)
pwm.setPWM(1, 1, pitch)
byte = (left_byte << 4) | right_byte
else:
byte = -1
#====send i2c=====#
if (byte >= 0):
try:
bus.write_byte(0x47,byte)
except IOError:
print("Error!!!!")
resetAVR()
bus.write_byte(0x47,byte)
#.........这里部分代码省略.........
示例14: init
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
def init():
global pubnub
pubnub = Pubnub(publish_key="demo", subscribe_key="demo")
pubnub.subscribe(channels=pubnub_responsechannel, callback=_callback, error=_error)
示例15: test
# 需要导入模块: from Pubnub import Pubnub [as 别名]
# 或者: from Pubnub.Pubnub import subscribe [as 别名]
## -----------------------------------------------------------------------
history = pubnub.history({
'channel' : crazy,
'limit' : 1
})
test(
history[0].encode('utf-8') == crazy,
'History Message: ' + history[0]
)
test( len(history) == 1, 'History Message Count' )
## -----------------------------------------------------------------------
## PubNub Server Time Example
## -----------------------------------------------------------------------
timestamp = pubnub.time()
test( timestamp > 0, 'PubNub Server Time: ' + str(timestamp) )
## -----------------------------------------------------------------------
## Subscribe Example
## -----------------------------------------------------------------------
def receive(message) :
print(message)
return True
pubnub.subscribe({
'channel' : crazy,
'callback' : receive
})