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)
def sms_message(request): twilio_message = request.POST['Body'] phone_number = request.POST['From'] incoming_phone_number = request.POST['To'] hashtag, body = _split_message(twilio_message, incoming_phone_number) print hashtag, body if hashtag is not None and body is not None: message = models.Message() message.message = body message.phone_number = phone_number message.wall = models.Wall.objects.get(hashtag=hashtag) message.save() print message pubnub = Pubnub(settings.PUBNUB_PUBLISH_KEY, settings.PUBNUB_SUBSCRIBE_KEY, settings.PUBNUB_SECRET, False) print pubnub.publish({ 'channel': hashtag, 'message': { 'message': body } }) return HttpResponse("Success!") return HttpResponse("Error")
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))
def post_save(cls, sender, document, **kwargs): cfg = current_app.config pubnub = Pubnub( publish_key=cfg["PUBNUB_PUB_KEY"], subscribe_key=cfg["PUBNUB_SUB_KEY"], ssl_on=False, ) pubnub.publish(channel="globaldisaster", message=json.dumps(document.asdict()))
def post_save(cls, sender, document, **kwargs): cfg = current_app.config pubnub = Pubnub( publish_key=cfg["PUBNUB_PUB_KEY"], subscribe_key=cfg["PUBNUB_SUB_KEY"], ssl_on=False, ) pubnub.publish(channel="globaldisaster", message=json.dumps(document.asdict()))
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))
class pubnubmessager(Observer): def __init__(self): self.pn = Pubnub(config.pubnub_pubkey, config.pubnub_subkey) print("Started") def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc, weighted_buyprice, weighted_sellprice): if profit > config.profit_thresh and perc > config.perc_thresh: message = "profit: %f USD with volume: %f BTC - buy at %.4f (%s) sell at %.4f (%s) ~%.2f%%" % (profit, volume, buyprice, kask, sellprice, kbid, perc) self.pn.publish({'channel' : config.pubnub_topic, 'message' :{ 'msg' : message}})
class pinterest(object): def __init__(self, publish_key, subscribe_key): self.publish_key = publish_key self.subscribe_key = subscribe_key self.pubnub = Pubnub('pub-c-6f928209-b8a8-4131-9749-7470ead38747', 'sub-c-6d212f32-404e-11e4-a498-02ee2ddab7fe', None, False) def send(self, channel, message): # Sending message on the channel self.pubnub.publish({'channel': channel, 'message': message})
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:%s@%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))
class pinterest(object): def __init__(self, publish_key, subscribe_key): self.publish_key = publish_key self.subscribe_key = subscribe_key self.pubnub = Pubnub( 'pub-c-6f928209-b8a8-4131-9749-7470ead38747', 'sub-c-6d212f32-404e-11e4-a498-02ee2ddab7fe', None, False) def send(self, channel, message): # Sending message on the channel self.pubnub.publish({ 'channel' : channel, 'message' : message})
def push(cls, channel, message_dict): pubnub = Pubnub(PUBLISH_KEY, SUBSCRIBE_KEY, SECRET_KEY, False ) info = pubnub.publish({ 'channel' : channel, 'message' : json.dumps(message_dict) }) return info
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)
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)
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 )
def push_cbk(sender, **kwargs): istance = kwargs.get('instance') if istance: print "Account balance: %s" % istance.balance pubnub = Pubnub(publish_key='pub-ed4e8fc6-b324-426c-8697-ec763129b026', subscribe_key='sub-31c9765c-c453-11e1-b76c-1b01c696dab3', ssl_on=True) info = pubnub.publish({'channel' : istance.notif_channel, 'message' : 'Current balance ' + unicode(istance.balance) }) print info
def publish_event(self, channel, event): # XXX: work around for missing attributes import socket socket.TCP_KEEPINTVL = 0x101 socket.TCP_KEEPCNT = 0x102 from Pubnub import Pubnub # TODO: move to base controller? pubnub = Pubnub( publish_key=self.settings['pubnub.publish_key'], subscribe_key=self.settings['pubnub.subscribe_key'], ) return pubnub.publish(channel, event)
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 })
def push_cbk(sender, **kwargs): istance = kwargs.get('instance') if istance: print "Account balance: %s" % istance.balance pubnub = Pubnub( publish_key='pub-ed4e8fc6-b324-426c-8697-ec763129b026', subscribe_key='sub-31c9765c-c453-11e1-b76c-1b01c696dab3', ssl_on=True) info = pubnub.publish({ 'channel': istance.notif_channel, 'message': 'Current balance ' + unicode(istance.balance) }) print info
def send(channel, message, **kwargs): """ Site: http://www.pubnub.com/ API: https://www.mashape.com/pubnub/pubnub-network Desc: real-time browser notifications Installation and usage: pip install -U pubnub Tests for browser notification http://127.0.0.1:8000/browser_notification/ """ pubnub = Pubnub(publish_key=settings.PUBNUB_PUB_KEY, subscribe_key=settings.PUBNUB_SUB_KEY, secret_key=settings.PUBNUB_SEC_KEY, ssl_on=kwargs.pop('ssl_on', False), **kwargs) return pubnub.publish(channel=channel, message={"text": message})
def send(channel, message, **kwargs): """ Site: http://www.pubnub.com/ API: https://www.mashape.com/pubnub/pubnub-network Desc: real-time browser notifications Installation and usage: pip install -U pubnub Tests for browser notification http://127.0.0.1:8000/browser_notification/ """ pubnub = Pubnub( publish_key=settings.PUBNUB_PUB_KEY, subscribe_key=settings.PUBNUB_SUB_KEY, secret_key=settings.PUBNUB_SEC_KEY, ssl_on=kwargs.pop('ssl_on', False), **kwargs) return pubnub.publish(channel=channel, message={"text": message})
pubnub.history( { 'channel' : crazy, 'limit' : 10, 'callback' : history_complete }) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- def publish_complete(info): print(info) pubnub.publish({ 'channel' : crazy, 'message' : "Hello World", 'callback' : publish_complete }) ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) print('Disconnecting...') pubnub.unsubscribe({ 'channel' : crazy }) def done() : print('final connection, done :)') pubnub.unsubscribe({ 'channel' : crazy }) tornado.ioloop.IOLoop.instance().stop()
78, 79, 83, 83, 80, 80, 80, 80, 81, 75, 75, 76, 74, 77, 75, 79, 79, 82, 81, 79, 80, 80, 80, 80, 80, 83, 81, 84, 83, 80, 80, 82, 78, 77, 80, 80, 85, 84, 83, 86, 82, 82, 86, 86, 83, 83, 83, 82, 83, 79, 80, 80, 80, 80, 79, 73, 80, 81, 79, 74, 78, 80, 76, 75, 71, 71, 73, 71, 72, 73, 73, 73, 75, 75, 76, 76, 74, 70, 71, 69, 69, 70, 72, 72, 74, 72, 72, 73, 73, 71, 69, 69, 70, 69, 69, 69, 68, 68, 68, 69, 72, 72, 73, 72, 72, 72, 73, 73, 70, 70, 71, 71, 71, 71, 71, 72, 74, 74, 78, 77, 78, 79, 82, 82, 74, 74, 74, 73, 73, 73, 76, 76, 77, 77, 77, 77, 77, 74, 85, 85, 86, 85, 85, 85, 85, 86, 86, 87, 85, 85, 86, 85, 85, 91, 89, 89, 91, 91, 90, 89, 89, 88, 87, 87, 89, 89, 90, 86, 86, 86, 86, 86, 85, 85, 79, 82, 81, 81, 83, 81, 78, 79, 82, 82, 83, 83, 84, 84, 83, 83, 81, 81, 79, 79, 78, 78, 78, 78, 79, 79, 81, 81, 79, 79, 79, 79, 79, 76, 77, 79, 77, 77, 77, 76, 78, 78, 78, 78, 82, 83, 84, 81, 81, 81, 80, 80, 78, 75, 78, 78, 78, 78, 76, 77, 77, 82, 81, 80, 80, 80, 80, 75, 76, 76, 76, 77, 78, 78, 78, 76, 76, 76, 78, 77, 77, 74, 75, 75, 75, 75, 75, 73, 75, 75, 75, 74, 76, 76, 73, 73, 78, 78, 79, 80, 79, 79, 79, 78, 77, 77, 77, 77, 79, 79, 76, 75, 76, 79, 76, 76, 76, 76, 78, 78, 78, 79, 79, 82, 82, 76, 76, 76, 75, 75, 73, 73, 73, 73, 73, 73, 73, 70, 71, 71, 74, 74, 76, 75, 73, 72, 71, 71, 73, 72, 71, 72, 72, 72, 72, 76, 77, 77, 77, 77, 81, 81, 81, 84, 84, 84, 84, 81, 81, 81, 77, 77, 77, 81, 80, 82, 82, 79, 83, 83, 80, 76, 76, 77, 78, 77, 80, 80, 81, 81, 85, 85, 83, 78, 77, 77, 79, 79, 80, 79, 81, 81, 81, 81, 78, 78, 79, 80, 78, 78, 75, 72, 72, 74, 74, 75, 74, 74, 74, 81, 79, 78, 79, 81, 81, 83, 82, 80, 80, 80, 80, 88, 87, 86, 85, 86, 86, 83, 83, 84, 83, 79, 79, 79, 80, 80, 80, 81, 79, 79, 81, 81, 82, 78, 79, 74, 74, 79, 80, 80, 81, 81, 81, 85, 83 ] while True: for count in countlist: pubnub.publish(channel, count) time.sleep(0.3)
ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub( publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key,cipher_key=cipher_key, ssl_on=ssl_on ) #pubnub = Pubnub( publish_key, subscribe_key, secret_key, ssl_on ) crazy = 'hello_world' def publish_complete(info): print(info) ## Publish string pubnub.publish({ 'channel' : crazy, 'message' : 'Hello World!', 'callback' : publish_complete }) ## Publish list li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] pubnub.publish({ 'channel' : crazy, 'message' : li, 'callback' : publish_complete }) def done_cb(info): publish_complete(info) tornado.ioloop.IOLoop.instance().stop()
from Pubnub import Pubnub ## Initiate Class pubnub = Pubnub('demo', 'demo', None, False) ## Publish Example info = pubnub.publish({'channel': 'example-user-id-1234', 'message': 'alert'}) print(info)
class BasePubNub(object): secret_key = "sec-c-YjFhY2U3MWUtMDIzZS00MzUxLTkyMjgtMmI5ZDMwNGI4YzNj" pub_key = "pub-c-07bede4d-e0d6-4f19-bb9b-fb8414505f36" sub_key = "sub-c-d9e6107e-d34c-11e4-adb1-02ee2ddab7fe" channel = "base" str_force = '"query"' str_on = '"set_on"' str_off = '"set_off"' str_auto = '"set_auto"' def __init__(self, subscribe=True, logcb=None, valuecb=None, swap=False): self.channel_down = "%s_down" % self.channel self.channel_up = "%s_up" % self.channel if swap: self.channel_down, self.channel_up = self.channel_up, self.channel_down self.pubnub = Pubnub(publish_key=self.pub_key, subscribe_key=self.sub_key, secret_key=self.secret_key) if subscribe: self.pubnub.subscribe(channels=self.channel_up, callback=self._callback, error=self._error_cb) self.logcb = logcb self.valuecb = valuecb def logcb(self, text): pass def force(self): self.pubnub.publish(self.channel_down, self.str_force) def set_on(self): self.pubnub.publish(self.channel_down, self.str_on) def set_off(self): self.pubnub.publish(self.channel_down, self.str_off) def set_auto(self): self.pubnub.publish(self.channel_down, self.str_auto) def send_value(self, value): info = {"name": self.channel, "value": value} self.pubnub.publish(self.channel_down, json.dumps(info)) def _callback(self, message, channel): if self.logcb: self.logcb("ch [%s] msg [%s]" % (channel, message)) else: print "got called back" print "ch [%s]" % channel print "msg [%s]" % message try: if type(message) == str: try: message = json.loads(message) except: print "was not a good json" # m = json.loads(message) if "value" in message and self.valuecb: self.valuecb(self.channel, str(message["value"])) except ValueError, e: print "json failed" except Exception, e: print "nope, that didnt work" print traceback.format_exc()
def _setup_channel(self): key = node.NetworkKey('N:ANT+', self.netkey) self.antnode.setNetworkKey(0, key) self.channel = self.antnode.getFreeChannel() self.channel.name = 'C:HRM' self.channel.assign('N:ANT+', CHANNEL_TYPE_TWOWAY_RECEIVE) self.channel.setID(120, 0, 0) self.channel.setSearchTimeout(TIMEOUT_NEVER) self.channel.setPeriod(8070) self.channel.setFrequency(57) self.channel.open() def process(self, msg): global HR if isinstance(msg, message.ChannelBroadcastDataMessage): HR = str((format(ord(msg.payload[-1])))) SERIAL = '/dev/ttyUSB0' NETKEY = 'B9A521FBBD72C345'.decode('hex') with HRM(serial=SERIAL, netkey=NETKEY) as hrm: hrm.start() while True: try: pubnub.publish('hr_channel', HR) time.sleep(1) except KeyboardInterrupt: hrm.stop() sys.exit(0)
publish_key = 'pub-c-ea55afd0-74eb-4ed4-9f56-4cd96bb87b0a' subscribe_key = 'sub-c-55cf6ccc-4585-11e4-8772-02ee2ddab7fe' secret_key = 'demo' cipher_key = '' ssl_on = False pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) userFile = open('userFile') userData = userFile.read() name = userData.split(',')[0] rHR = userData.split(',')[1] phNum = userData.split(',')[2] usrNum = userData.split(',')[3] usrJson = userFileGen(name, rHR, phNum, usrNum) pubnub.publish('usrid_channel', usrJson) os.system('./googlet2s.sh User Name ' + name) os.system('./googlet2s.sh resting heart rate ' + rHR) print('User File Uploaded...')
print(messages) pubnub.history({'channel': crazy, 'limit': 10, 'callback': history_complete}) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- def publish_complete(info): print(info) pubnub.publish({ 'channel': crazy, 'message': "Hello World", 'callback': publish_complete }) ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) print('Disconnecting...') pubnub.unsubscribe({'channel': crazy}) def done(): print('final connection, done :)') pubnub.unsubscribe({'channel': crazy})
from Pubnub import Pubnub ## Initiate Class pubnub = Pubnub( 'demo', 'demo', None, False ) ## Publish Example info = pubnub.publish({ 'channel' : 'hello_world', 'message' : { 'some_text' : 'Hello my World' } }) print(info)
try: GPIO.add_event_detect(25, GPIO.FALLING, callback=button_callback, bouncetime=300) pubnub.subscribe(channels="text", callback=call, error=_error) while True: adc_value = (get_adc(adcChannel)) v = cal_voltage(adc_value) t = cal_temp(v) if t > 50 and is_warning == False: message = 'The room temperature is ' + str(int(t)) + ' C' pubnub.publish("my_channel", message, callback=_callback, error=_error) runMotor() is_warning = True if t < 40 and is_warning == True: message = 'Now it is fine. T: ' + str(int(t)) + ' C' pubnub.publish("my_channel", message, callback=_callback, error=_error) print('Temperature: ', "{0:.2f}".format(t), ' C') stop() is_warning = False display(adc_value, t)
from Pubnub import Pubnub import requests, time, json pubnub = Pubnub('pub-c-9a952874-0857-4976-8fd6-be2c969dc5bc', 'sub-c-ecc13c7c-48d9-11e3-b088-02ee2ddab7fe', None, True) def getPrice(): url = 'http://data.mtgox.com/api/2/BTCUSD/money/ticker' r = requests.get(url, headers={'Accept': 'application/json'}) return (json.loads(r.text)['data']['avg']['display_short'][1:]).replace( ",", "") #return r.json['data']['avg']['display_short'][1:] if __name__ == "__main__": while True: pubnub.publish({ "channel": "BETA00016", "message": { "btcPrice": getPrice() } }) time.sleep(3)
from Pubnub import Pubnub publish_key = "pub-c-c446036d-8070-4a3e-aa0e-ed9eb2d2a7f1" subscribe_key = "sub-c-f8f41034-3454-11e4-b3c3-02ee2ddab7fe" secret_key = "sec-c-ZDQ0MmRkNWYtN2IwMS00NzU2LWFiYzAtNDEzZGM1NTNkZDRk" cipher_key = "" ssl_on = False pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) channel = "semaforo" message = "{'amarelo': 'blink', 'verde': 'on', 'vermelho': 'off'}" print pubnub.publish(channel, message)
pubnub.history({'channel': crazy, 'limit': 10, 'callback': history_complete}) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- def publish_complete(info): print(info) pubnub.publish({ 'channel': crazy, 'message': { 'some_text': 'Hello World!' }, 'callback': publish_complete }) ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) pubnub.subscribe({'channel': crazy, 'callback': message_received}) ## -----------------------------------------------------------------------
pubnub.history({'channel': crazy, 'limit': 10, 'callback': history_complete}) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- def publish_complete(info): print(info) pubnub.publish({ 'channel': crazy, 'message': { 'one': 'Hello World! --> ɂ顶@#$%^&*()!', 'two': 'hello2' }, 'callback': publish_complete }) ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) print('Disconnecting...') pubnub.unsubscribe({'channel': crazy}) def done(): print('final connection, done :)')
from Pubnub import Pubnub ## Initiate Class pubnub = Pubnub( 'demo', 'demo', None, False ) ## Publish Example info = pubnub.publish({ 'channel' : 'example-user-id-1234', 'message' : 'alert' }) print(info)
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") out_message = {"sender": "bric", "body": output} pubnub.publish("demo_tutorial", out_message, callback=callback(out_message), error=callback(out_message)) print "entering idle..." signal.clear()
72, 73, 72, 72, 72, 73, 73, 70, 70, 71, 71, 71, 71, 71, 72, 74, 74, 78, 77, 78, 79, 82, 82, 74, 74, 74, 73, 73, 73, 76, 76, 77, 77, 77, 77, 77, 74, 85, 85, 86, 85, 85, 85, 85, 86, 86, 87, 85, 85, 86, 85, 85, 91, 89, 89, 91, 91, 90, 89, 89, 88, 87, 87, 89, 89, 90, 86, 86, 86, 86, 86, 85, 85, 79, 82, 81, 81, 83, 81, 78, 79, 82, 82, 83, 83, 84, 84, 83, 83, 81, 81, 79, 79, 78, 78, 78, 78, 79, 79, 81, 81, 79, 79, 79, 79, 79, 76, 77, 79, 77, 77, 77, 76, 78, 78, 78, 78, 82, 83, 84, 81, 81, 81, 80, 80, 78, 75, 78, 78, 78, 78, 76, 77, 77, 82, 81, 80, 80, 80, 80, 75, 76, 76, 76, 77, 78, 78, 78, 76, 76, 76, 78, 77, 77, 74, 75, 75, 75, 75, 75, 73, 75, 75, 75, 74, 76, 76, 73, 73, 78, 78, 79, 80, 79, 79, 79, 78, 77, 77, 77, 77, 79, 79, 76, 75, 76, 79, 76, 76, 76, 76, 78, 78, 78, 79, 79, 82, 82, 76, 76, 76, 75, 75, 73, 73, 73, 73, 73, 73, 73, 70, 71, 71, 74, 74, 76, 75, 73, 72, 71, 71, 73, 72, 71, 72, 72, 72, 72, 76, 77, 77, 77, 77, 81, 81, 81, 84, 84, 84, 84, 81, 81, 81, 77, 77, 77, 81, 80, 82, 82, 79, 83, 83, 80, 76, 76, 77, 78, 77, 80, 80, 81, 81, 85, 85, 83, 78, 77, 77, 79, 79, 80, 79, 81, 81, 81, 81, 78, 78, 79, 80, 78, 78, 75, 72, 72, 74, 74, 75, 74, 74, 74, 81, 79, 78, 79, 81, 81, 83, 82, 80, 80, 80, 80, 88, 87, 86, 85, 86, 86, 83, 83, 84, 83, 79, 79, 79, 80, 80, 80, 81, 79, 79, 81, 81, 82, 78, 79, 74, 74, 79, 80, 80, 81, 81, 81, 85, 83] while True: for count in countlist: pubnub.publish(channel, count) time.sleep(0.3)
crazy = 'demo' ## --------------------------------------------------------------------------- ## Unit Test Function ## --------------------------------------------------------------------------- def test( trial, name ) : if trial : print( 'PASS: '******'FAIL: ' + name ) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- publish_success = pubnub.publish({ 'channel' : crazy, 'message' : crazy }) test( publish_success[0] == 1, 'Publish First Message Success' ) ## ----------------------------------------------------------------------- ## History Example ## ----------------------------------------------------------------------- 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' )
key = node.NetworkKey('N:ANT+', self.netkey) self.antnode.setNetworkKey(0, key) self.channel = self.antnode.getFreeChannel() self.channel.name = 'C:HRM' self.channel.assign('N:ANT+', CHANNEL_TYPE_TWOWAY_RECEIVE) self.channel.setID(120, 0, 0) self.channel.setSearchTimeout(TIMEOUT_NEVER) self.channel.setPeriod(8070) self.channel.setFrequency(57) self.channel.open() def process(self, msg): global HR if isinstance(msg, message.ChannelBroadcastDataMessage): HR = str((format(ord(msg.payload[-1])))) SERIAL = '/dev/ttyUSB0' NETKEY = 'B9A521FBBD72C345'.decode('hex') with HRM(serial=SERIAL, netkey=NETKEY) as hrm: hrm.start() while True: try: pubnub.publish('hr_channel',HR) time.sleep(1) except KeyboardInterrupt: hrm.stop() sys.exit(0)
def connect_cb(): print 'Connect' def subscribe_result(response): print response pubnub.subscribe({ 'channel' : crazy, 'callback' : subscribe_result, 'connect' : connect_cb }) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- ''' def publish_complete(info): print(info) ## Publish string pubnub.publish({ 'channel' : crazy, 'message' : 'Hello World!', 'callback' : publish_complete }) ## Publish list li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] pubnub.publish({ 'channel' : crazy, 'message' : li,
print(messages) pubnub.history({"channel": crazy, "limit": 10, "callback": history_complete}) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- def publish_complete(info): print(info) pubnub.publish( { "channel": crazy, "message": {"one": "Hello World! --> ɂ顶@#$%^&*()!", "two": "hello2"}, "callback": publish_complete, } ) ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) print("Disconnecting...") pubnub.unsubscribe({"channel": crazy}) def done(): print("final connection, done :)") pubnub.unsubscribe({"channel": crazy})
from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) channel = 'hello_world' message = 'Hello World !!!' # Synchronous usage print pubnub.publish(channel, message) # Asynchronous usage def callback(message): print(message) pubnub.publish(channel, message, callback=callback, error=callback)
pubnub.history( { 'channel' : crazy, 'limit' : 10, 'callback' : history_complete }) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- def publish_complete(info): print(info) pubnub.publish({ 'channel' : crazy, 'message' : {'one': 'Hello World! --> ɂ顶@#$%^&*()!', 'two': 'hello2'}, 'callback' : publish_complete }) ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) print('Disconnecting...') pubnub.unsubscribe({ 'channel' : crazy }) def done() : print('final connection, done :)') pubnub.unsubscribe({ 'channel' : crazy }) reactor.stop()
publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or 'demo' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiat Class ## ----------------------------------------------------------------------- pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on ) crazy = 'hello_world' ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- def publish_complete(info): print(info) pubnub.publish({ 'channel' : crazy, 'message' : { 'some_text' : 'Hello World!' }, 'callback' : publish_complete }) ## ----------------------------------------------------------------------- ## IO Event Loop ## ----------------------------------------------------------------------- reactor.run()
from Pubnub import Pubnub import requests, time, json pubnub = Pubnub('pub-c-9a952874-0857-4976-8fd6-be2c969dc5bc', 'sub-c-ecc13c7c-48d9-11e3-b088-02ee2ddab7fe',None,True) def getPrice(): url = 'http://data.mtgox.com/api/2/BTCUSD/money/ticker' r = requests.get(url, headers={'Accept': 'application/json'}) return (json.loads(r.text)['data']['avg']['display_short'][1:]).replace(",","") #return r.json['data']['avg']['display_short'][1:] if __name__ == "__main__": while True: pubnub.publish({"channel":"BETA00016","message":{"btcPrice": getPrice()}}) time.sleep(3)
print('User file created...') return userFile publish_key = 'pub-c-ea55afd0-74eb-4ed4-9f56-4cd96bb87b0a' subscribe_key = 'sub-c-55cf6ccc-4585-11e4-8772-02ee2ddab7fe' secret_key = 'demo' cipher_key = '' ssl_on = False pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) userFile = open('userFile') userData = userFile.read() name = userData.split(',')[0] rHR = userData.split(',')[1] phNum = userData.split(',')[2] usrNum = userData.split(',')[3] usrJson = userFileGen(name,rHR,phNum,usrNum) pubnub.publish('usrid_channel', usrJson) os.system('./googlet2s.sh User Name ' + name ) os.system('./googlet2s.sh resting heart rate ' + rHR) print('User File Uploaded...')
import sys from Pubnub import Pubnub publish_key = 'pub-c-6c6b1294-7fdd-4f33-aec4-41217a6d0b6c' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'sub-c-cf0e18e6-bd43-11e4-861a-0619f8945a4f' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) channel = 'my_channel' message = len(sys.argv) > 1 and sys.argv[1] or 'Hello World !!!' # Synchronous usage print pubnub.publish(channel, message) # Asynchronous usage def callback(message): print(message) pubnub.publish(channel, message, callback=callback, error=callback)
from Pubnub import Pubnub ## Initiat Class pubnub = Pubnub( 'demo', 'demo', None, False ) ## Publish Example info = pubnub.publish({ 'channel' : 'hello_world', 'message' : { 'some_text' : 'Hello my World' } }) print(info)
## History Example ## ----------------------------------------------------------------------- def history_complete(messages): print(messages) pubnub.history({"channel": crazy, "limit": 10, "callback": history_complete}) ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- def publish_complete(info): print(info) pubnub.publish({"channel": crazy, "message": "Hello World", "callback": publish_complete}) ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) print("Disconnecting...") pubnub.unsubscribe({"channel": crazy}) def done(): print("final connection, done :)") pubnub.unsubscribe({"channel": crazy}) tornado.ioloop.IOLoop.instance().stop() def dumpster(message):