class Logs(object): def __init__(self): self.config = Config() def init_pubnub(func): def wrapper(self, *args, **kwargs): if not hasattr(self, 'pubnub'): pubnub_key = self.config.get_pubnub_keys() self.pubnub = Pubnub(publish_key=pubnub_key['publish_key'], subscribe_key=pubnub_key['subscribe_key']) return func(self, *args, **kwargs) return wrapper @init_pubnub def subscribe(self, uuid, callback, error): channel = self.get_channel(uuid) self.pubnub.subscribe(channels=channel, callback=callback, error=error) @init_pubnub def history(self, uuid, callback, error): channel = self.get_channel(uuid) self.pubnub.history(channel=channel, callback=callback, error=error) def unsubscribe(self, uuid): if hasattr(self, 'pubnub'): channel = self.get_channel(uuid) self.pubnub.unsubscribe(channel=channel) @staticmethod def get_channel(uuid): return 'device-{uuid}-logs'.format(uuid=uuid)
def subcribe_devices_to_pub_nub(sub_key, channels): global log pubnub = Pubnub(publish_key="", subscribe_key=sub_key, ssl_on=True) def callback(message, channel): response = json.loads(message) sensor = Sensor.get_by_webid(response['uuid']) sensor.webid = response['uuid'] sensor.value = json.dumps(response['desired_state']) sensor.raw = json.dumps(response) sensor.friendly_id = json.dumps(response['name']).replace('"', '') sensor.state = "CONNECTED" if json.dumps( response['last_reading'] ['connection']) == 'true' else "DISCONNECTED" sensor.update() def error(message): log.log("Pubnub Error: " + message) def connect(message): log.log("Pubnub Connected: " + message) def reconnect(message): log.log("Pubnub Reconnected: " + message) def disconnect(message): log.log("Pubnub Disconnected: " + message) for channel in channels: pubnub.subscribe(channels=channel, callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect)
class PubNub: def __init__(self,pubkey,subkey): self.pubnub = Pubnub(publish_key=pubkey, subscribe_key=subkey) self.subchannel = 'core-ops' def subCallback(self,message,channel): print (message,channel) if (channel == self.subchannel): return message def error(self,message): print (message) def pubCallback(self,message): print (message) def pub(self,message,channel): try: self.pubnub.publish(channel, message, callback=self.pubCallback, error=self.pubCallback) except Exception as e: print (e) def sub(self,channel): try: self.pubnub.subscribe(channels=channel, callback=self.subCallback, error=self.error) except Exception as e: print (e)
class manageClients(Thread): test = os.environ pubnub_publish_key = os.environ['PUBNUB_PUBLISH_KEY'] pubnub_subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY'] mongodb_connection = None collection = None def __init__(self): Thread.__init__(self) mongodb_connection = ConnectionToDatabase() manageClients.deliveries_collection = mongodb_connection.getCollection( "temp_deliveries") self.pubnub_settings = Pubnub( publish_key=manageClients.pubnub_publish_key, subscribe_key=manageClients.pubnub_subscribe_key) # Rename to location channel self.pubnub_channel = "clients_channel" self.genericDAO = GenericDAO() self.manageSteeds = manageSteeds() def subscriber_callback(self, message, channel): print(message) # Inserer la demande de livraison faite par le client if (message["msg_code"] == "XX"): # inserer la demande de livraison dans une collection temporaire id_delivery = self.genericDAO.insertObject( manageClients.deliveries_collection, message) def subscriber_error(self, message): print("ERROR : " + message) def connect(self, message): print("CONNECTED TO LOCATION CHANNEL") def reconnect(self, message): print("RECONNECTED TO LOCATION CHANNEL") def disconnect(self, message): print("DISCONNECTED FROM LOCATION CHANNEL") def subscribe(self): # souscrire au channel self.pubnub_settings.subscribe(channels=self.pubnub_channel, callback=self.subscriber_callback, error=self.subscriber_error, connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect) def publish(self, message): self.pubnub_settings.publish(channel=self.pubnub_channel, message=message) def unsubscribe(self): # se desinscire du channel self.pubnub_settings.unsubscribe(self.pubnub_channel)
def init(): #Pubnub Key Initialization global pubnub pubnub = Pubnub(publish_key=pub_key,subscribe_key=sub_key) pubnub.subscribe(channels='parkingapp-resp', callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect) pubnub.subscribe(channels=g_carNumber, callback=caRcallback, error=caRcallback, connect=connect, reconnect=reconnect, disconnect=disconnect)
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'])
class manageGPSLocation(Thread) : test = os.environ pubnub_publish_key = os.environ['PUBNUB_PUBLISH_KEY'] pubnub_subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY'] mongodb_connection = None collection = None def __init__(self): Thread.__init__(self) mongodb_connection = ConnectionToDatabase() manageGPSLocation.collection = mongodb_connection.getCollection("steeds") self.pubnub_settings = Pubnub(publish_key=manageGPSLocation.pubnub_publish_key,subscribe_key=manageGPSLocation.pubnub_subscribe_key) # Rename to location channel self.pubnub_channel = "channel_test" self.genericDAO = GenericDAO() def subscriber_callback(self, message, channel): print(message) criteriaDict = {} criteriaDict["_id"]=message["_id"] updateDict = {} subUpdateDict = {} subUpdateDict["type"]="Point" subUpdateDict["coordinates"] = [message["lng"],message["lat"]] updateDict["location"]=subUpdateDict self.genericDAO.updateObjects(manageGPSLocation.collection, criteriaDict, updateDict) def subscriber_error(self, message): print("ERROR : "+message) def connect(self, message): print("CONNECTED TO LOCATION CHANNEL") def reconnect(self, message): print("RECONNECTED TO LOCATION CHANNEL") def disconnect(self, message): print("DISCONNECTED FROM LOCATION CHANNEL") def subscribe(self): # souscrire au channel self.pubnub_settings.subscribe(channels=self.pubnub_channel, callback=self.subscriber_callback, error=self.subscriber_error ,connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect) def publish(self, message): self.pubnub_settings.publish(channel=self.pubnub_channel, message=message) def unsubscribe(self): # se desinscire du channel self.pubnub_settings.unsubscribe(self.pubnub_channel)
def run(callback): pubnub = Pubnub( 'demo', 'sub-c-78806dd4-42a6-11e4-aed8-02ee2ddab7fe' ) pubnub.subscribe( channels='pubnub-twitter', callback= callback )
def init(): #initalize the pubnub keys and start subscribing global pubnub #Pubnub Initialization GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(LIGHT,GPIO.OUT) GPIO.output(LIGHT, False) pubnub = Pubnub(publish_key=pub_key,subscribe_key=sub_key) pubnub.subscribe(channels='alexaTrigger', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect)
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))
def init(): #Pubnub Key Initialization global pubnub pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key) pubnub.subscribe(channels='kitchenApp-resp', callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect)
def init(): #Pubnub Key Initialization global pubnub pubnub = Pubnub(publish_key=g_pub_key, subscribe_key=g_sub_key) pubnub.subscribe(channels='KA01M1234', callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect)
def pub_Init(): global pubnub try: pubnub = Pubnub(publish_key=pub_key,subscribe_key=sub_key) pubnub.subscribe(channels=statsresponsepubchannel, callback=callbackStats,error=error, connect=connect, reconnect=reconnect, disconnect=disconnect) pubnub.subscribe(channels=livepubchannel, callback=callbackLive,error=error, connect=connect, reconnect=reconnect, disconnect=disconnect) except Exception as e: print e
def pub_Init(): global pubnub try: pubnub = Pubnub(publish_key=pub_key,subscribe_key=sub_key) pubnub.subscribe(channels=subchannel, callback=callback,error=error, connect=connect, reconnect=reconnect, disconnect=disconnect) return True except Exception as pubException: print("The pubException is %s %s"%(pubException,type(pubException))) return False
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))
class manageClients(Thread) : test = os.environ pubnub_publish_key = os.environ['PUBNUB_PUBLISH_KEY'] pubnub_subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY'] mongodb_connection = None collection = None def __init__(self): Thread.__init__(self) mongodb_connection = ConnectionToDatabase() manageClients.deliveries_collection = mongodb_connection.getCollection("temp_deliveries") self.pubnub_settings = Pubnub(publish_key=manageClients.pubnub_publish_key,subscribe_key=manageClients.pubnub_subscribe_key) # Rename to location channel self.pubnub_channel = "clients_channel" self.genericDAO = GenericDAO() self.manageSteeds = manageSteeds() def subscriber_callback(self, message, channel): print(message) # Inserer la demande de livraison faite par le client if(message["msg_code"] == "XX") : # inserer la demande de livraison dans une collection temporaire id_delivery = self.genericDAO.insertObject(manageClients.deliveries_collection, message) def subscriber_error(self, message): print("ERROR : "+message) def connect(self, message): print("CONNECTED TO LOCATION CHANNEL") def reconnect(self, message): print("RECONNECTED TO LOCATION CHANNEL") def disconnect(self, message): print("DISCONNECTED FROM LOCATION CHANNEL") def subscribe(self): # souscrire au channel self.pubnub_settings.subscribe(channels=self.pubnub_channel, callback=self.subscriber_callback, error=self.subscriber_error ,connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect) def publish(self, message): self.pubnub_settings.publish(channel=self.pubnub_channel, message=message) def unsubscribe(self): # se desinscire du channel self.pubnub_settings.unsubscribe(self.pubnub_channel)
def init(): global pubnub GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(LIGHT, GPIO.OUT) GPIO.output(LIGHT, False) pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key) pubnub.subscribe(channels='alexaTrigger', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect)
class WorkspaceSensor: def __init__(self, setting_file_path): with open(setting_file_path) as f: self._setting = json.load(f, "utf-8") self._circuit = circuit.parse(self._setting["GPIO"]) self._current_status = self._circuit.get_status() self._on_resistance = Resistance(self._setting["on_resistance"], 1, self._update_status) self._off_resistance = Resistance(self._setting["off_resistance"], 0, self._update_status) self._pubnub = Pubnub(publish_key=self._setting["publish_key"], subscribe_key=self._setting["subscribe_key"]) self._pubnub.subscribe(channels='plzcast_' + self._setting["group"], callback=self._callback_plzcast, connect=self._callback_connect, reconnect=self._callback_connect) def run(self): while True: sensor_status = self._circuit.get_status() if (sensor_status == 1): self._on_resistance.load() self._off_resistance.clear() else: self._off_resistance.load() self._on_resistance.clear() time.sleep(self._setting["duration"]) def _send(self): message = json.dumps({ "floor": self._setting["floor"], "id": self._setting["id"], "name": self._setting["name"], "status": self._current_status }) self._pubnub.publish(channel='wkstatus_' + self._setting["group"], message=message) def _callback_plzcast(self, message, channel): self._send() def _callback_connect(self, message): self._send() def _update_status(self, new_status): if (new_status != self._current_status): self._current_status = new_status self._send()
class Pubnub_stream: def __init__(self): self.pubnub = Pubnub(publish_key=os.getenv('ANBAU_PUBLISH_KEY'), subscribe_key=os.getenv('ANBAU_SUBSCRIBE_KEY')) self.channel = "stats" self.message = "A message" self.pubnub.subscribe(self.channel, callback=callback) print('PubNub stream created!') def write(self, data): self.pubnub.publish(channel=self.channel, message=data)
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)
def init(): #Pubnub Initialization global pubnub pubnub = Pubnub(publish_key=PUB_KEY, subscribe_key=SUB_KEY) pubnub.subscribe(channels='vehicleIdentificanDevice-resp', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect) pubnub.subscribe(channels='vehicleIdentificanApp-req', callback=appcallback, error=appcallback, reconnect=reconnect, disconnect=disconnect)
def init(): #Pubnub Initialization global pubnub pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key) pubnub.subscribe(channels='parkingdevice-resp', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect) pubnub.subscribe(channels='parkingapp-req', callback=appcallback, error=appcallback, reconnect=reconnect, disconnect=disconnect)
class PiBusHub(object): def __init__(self): self.logger = logging.getLogger(__name__) if not hasattr(cfg, 'PUBNUB_CHANNEL_KEY'): self.logger.debug("PubNub[ChannelKey] not defined - PubNub support disabled") if not hasattr(cfg, 'PUBNUB_PUBLISH_KEY'): self.logger.debug("PubNub[PublishKey] not defined - PubNub support disabled") return if cfg.PUBNUB_PUBLISH_KEY == '': self.logger.debug("PubNub[PublishKey] not configured - PubNub support disabled") return if not hasattr(cfg, 'PUBNUB_SUBSCRIBE_KEY'): self.logger.debug("PubNub[SubscribeKey] not defined - PubNub support disabled") return self.logger.debug("PubNub registering: " +cfg.PUBNUB_PUBLISH_KEY + " : " + cfg.PUBNUB_SUBSCRIBE_KEY) self.pubnub = Pubnub(publish_key=cfg.PUBNUB_PUBLISH_KEY, subscribe_key=cfg.PUBNUB_SUBSCRIBE_KEY) if cfg.PUBNUB_SUBSCRIBE_KEY != '': self.logger.info("PubNub subscribing: " + cfg.PUBNUB_CHANNEL_KEY) self.pubnub.subscribe(channels=cfg.PUBNUB_CHANNEL_KEY, callback=self.callback, error=self.error, connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect) def callback(self, message, channel): print("CALLBACK: " + message +":" + channel) def error(message): print("ERROR : " + str(message)) def connect(self, channel): print("CONNECTED: " +channel) self.pubnub.publish(channel='Mongo', message='Hello from the PubNub Python SDK') def reconnect(message): print("RECONNECTED:" + message) def disconnect(message): print("DISCONNECTED:" + message) def publish(self, message): print("PUBLISH:" + message) self.pubnub.publish(channel=cfg.PUBNUB_CHANNEL_KEY, message=message)
def init(): #initalize the pubnub keys and start subscribing global pubnub #Pubnub Initialization gpio.setmode(gpio.BOARD) gpio.setwarnings(False) gpio.setup(fan1, gpio.OUT) gpio.setup(fan2, gpio.OUT) gpio.output(fan1, False) gpio.output(fan2, False) pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key) pubnub.subscribe(channels='alexaTrigger', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect)
class CloudPubNub(CloudServiceBase): """ PubNub cloud service connector """ def __init__(self, publish_key, subscribe_key, strategy=None): """ :param publish_key: Publish key :type publish_key: str. :param subscribe_key: Subscribe key :type subscribe_key: str :param strategy: Strategy object to send data to cloud. :type strategy: StrategyBase. """ super(CloudPubNub, self).__init__(strategy=strategy) self.name = 'pubnub' self.pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key) self.pubnub.subscribe(channels="iot_data", callback=self._callback_subscribe, error=self._error) @staticmethod def _callback_subscribe(message, channel): """ Callback method for subscribe. """ logging.info('PubNub reads: {}'.format(message)) @staticmethod def _error(message): """ Error method for subscribe. """ logging.error('PubNub: {}'.format(message)) @staticmethod def _callback_publish(message): """ Callback method for publish. """ logging.info('PubNub: {}'.format(message)) def _send_data(self, data, device_name): self.pubnub.publish("iot_data", data, callback=self._callback_publish, error=self._callback_publish)
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'])
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()
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()
class dashjazz(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': channel, 'message': message}) def connect(self, channel, receiver): # Listening for messages on the channel self.pubnub.subscribe({'channel': channel, 'callback': receiver})
def connectPubnub(): global pn_connected, pn try: # Setup pubnub channel pn = Pubnub(publish_key=pn_publish_key, subscribe_key=pn_subscribe_key) # Setup pubunb listener pn.subscribe(channels=pn_channel, callback=onPubnubMessage) # Flag initialized print "Connected to Pubnub channel:", pn_channel pn_connected = True except Exception, e: print "Unable to connect to Pubnub, retrying..." time.sleep(5) connectPubnub()
class ActionListener(object): def __init__(self, camera_streamer): self.camera_streamer = camera_streamer self.pubnub = Pubnub( publish_key=PUBNUB_PUBLISH_KEY, subscribe_key=PUBNUB_SUBSCRIBE_KEY, cipher_key='', ssl_on=False ) self.pubnub.subscribe(LISTEN_CHANNEL, self.callback) def callback(self, message, channel): # TODO update variable names, not necessary a phone numebr here if message['command'] == Constants.CMD_TAKE_PICTURE: phone_number = message['value'] self.camera_streamer.amend_phone_number(phone_number)
class WorkspaceSensor: def __init__(self,setting_file_path): with open(setting_file_path) as f: self._setting = json.load(f,"utf-8") self._circuit = circuit.parse(self._setting["GPIO"]) self._current_status = self._circuit.get_status() self._on_resistance = Resistance(self._setting["on_resistance"],1,self._update_status) self._off_resistance = Resistance(self._setting["off_resistance"],0,self._update_status) self._pubnub = Pubnub(publish_key=self._setting["publish_key"], subscribe_key=self._setting["subscribe_key"]) self._pubnub.subscribe(channels='plzcast_' + self._setting["group"], callback=self._callback_plzcast,connect=self._callback_connect, reconnect=self._callback_connect) def run(self): while True: sensor_status = self._circuit.get_status() if(sensor_status == 1): self._on_resistance.load() self._off_resistance.clear() else: self._off_resistance.load() self._on_resistance.clear() time.sleep(self._setting["duration"]) def _send(self): message=json.dumps({ "floor":self._setting["floor"], "id":self._setting["id"], "name":self._setting["name"], "status":self._current_status }) self._pubnub.publish(channel='wkstatus_' + self._setting["group"],message=message) def _callback_plzcast(self,message,channel): self._send() def _callback_connect(self,message): self._send() def _update_status(self,new_status): if(new_status != self._current_status): self._current_status = new_status self._send()
class ServoCommandListener(object): def __init__(self, servo_controller): self.servo_controller = servo_controller self.pubnub = Pubnub( publish_key=PUBNUB_PUBLISH_KEY, subscribe_key=PUBNUB_SUBSCRIBE_KEY, cipher_key='', ssl_on=False ) self.pubnub.subscribe(LISTEN_CHANNEL, self.callback) def callback(self, message, channel): # not the best code for sure... self.servo_controller.action_from_strings( message['command'], message['value'], )
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 Net: def callback(self, message): print(message) def __init__(self, channel = "Channel-ux8kwdv1u"): self.channel = channel self.pubnub = Pubnub(publish_key=PUB_KEY, subscribe_key=SUB_KEY) def subscribe(self, callback): self.pubnub.subscribe(channels=self.channel, callback=callback, error=self.callback) def unsubscribe(self): self.pubnub.unsubscribe(channel=self.channel) def publish(self, message): self.pubnub.publish(channel=self.channel, message=message, callback=self.callback, error=self.callback)
def init(): # Pubnub Key Initialization global pubnub pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key) pubnub.subscribe( channels="parkingapp-resp", callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect, ) pubnub.subscribe( channels=g_carNumber, callback=caRcallback, error=caRcallback, connect=connect, reconnect=reconnect, disconnect=disconnect, )
def init(): #Pubnub Initialization global pubnub pubnub = Pubnub(publish_key=PUB_KEY,subscribe_key=SUB_KEY) pubnub.subscribe(channels='parkingdevice-resp', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect) pubnub.subscribe(channels='parkingapp-req', callback=appcallback, error=appcallback, reconnect=reconnect, disconnect=disconnect) pubnub.subscribe(channels='parkingrfid-resp', callback=rfidCallback, error=rfidCallback, reconnect=reconnect, disconnect=disconnect)
def __init__(self, wink): """Initialize the Wink device.""" from pubnub import Pubnub self.wink = wink self._battery = self.wink.battery_level if (SUBSCRIPTION_HANDLER is not None and self.wink.pubnub_channel is not None): self.sub_key = self.wink.pubnub_key self.sub_channel = self.wink.pubnub_channel if self.sub_channel in CHANNELS: pubnub = Pubnub(subscribe_key=self.sub_key, publish_key="N/A") pubnub.subscribe(channels=self.sub_channel, callback=self._pubnub_update, error=self._pubnub_error) else: CHANNELS.append(self.sub_channel) SUBSCRIPTION_HANDLER.subscribe(channels=self.sub_channel, callback=self._pubnub_update, error=self._pubnub_error) else: self.sub_key = None self.sub_channel = None
def init(): #initalize the pubnub keys and start subscribing #Pubnub Initialization global pubnub pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key) pubnub.subscribe(channels='automation', callback=callback, error=callback, reconnect=reconnect, disconnect=disconnect) #GPIO Initialization GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(N64RST, GPIO.OUT) GPIO.output(N64RST, True) GPIO.setup(N6412, GPIO.OUT) GPIO.output(N6412, True) GPIO.setup(N6433, GPIO.OUT) GPIO.output(N6433, True) GPIO.setup(STRIP, GPIO.OUT) GPIO.output(STRIP, True)
def startAutomation(): # print ("**************************") # print ("*TRITONSPARK TEST CONSOLE*") # print ("**************************") global pubnub pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key) pubnub.subscribe(channels='parkingapp-resp', callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect) parking_lots = 6 r_park_time = randint(5, 10) r_parking_lot_num = '%03d' % randint(1, 6) r_parking_status = randint(0, 1) # run_command = raw_input().split(' ') print "Sleeping for : ", r_park_time, " secs\n" if (r_parking_status == 1): pubnub.publish(channel='parkingapp-req', message={ "requester": "APP", "lotNumber": str(r_parking_lot_num), "requestType": 2, "requestValue": g_carNumber }) time.sleep(2) else: pubnub.publish(channel='parkingapp-req', message={ "requester": "APP", "lotNumber": str(r_parking_lot_num), "requestType": 3, "requestValue": g_carNumber }) time.sleep(2)
def post(self): """ User sends gold and route info to server. Request uid - user_id cid - channel_id data - message """ data = json.loads(self.request.body) uid = data['uid'] print uid cid = data['cid'] print cid ucg = data['current_gold'] print "The user's current gold is " + ucg r = data['route'] print "The route is: " + r pointsList = r.split(";") ndb.GeoPoint() rid = uid + "-" + cid route = Route(route_id=rid, list_of_points=[]) for i in range(len(pointsList)): lng = pointsList[i].split()[0] lat = pointsList[i].split()[1] route.list_of_points.append(ndb.GeoPoint(lng, lat)) route.put() usid = uid + "-" + cid user_session = UserSession(user_session_id=usid, base_point="", drop_off_point="", user_current_gold=ucg, route_id=rid) user_session.put() # session = Session.query(Session.channel_id == cid).get() pubnub = Pubnub(publish_key=PUBLISH_KEY, subscribe_key=SUBSCRIBE_KEY, ssl_on=False, uuid=str(uid)) pubnub.subscribe(cid, callback) pubnub.publish(cid, uid + " has selected a route") response = {'user-session-id': usid} self.response.out.write(json.dumps(response))
def main(): argParse = ArgumentParser(description="Digital Homestead CSV Logger creates CSV files of the Walk Over Weigher Data") argParse.add_argument("--config",metavar="<config>", dest="config", default="config.json", action="store", help="The location of the config JSON file. default: config.json") argParse.add_argument("--input",metavar="<input>", dest="input", action="store", help="Read data from a json file instead of pubnub.") args = argParse.parse_args() if not os.path.exists(args.config): print 'Configuration file: ' + args.config + " Does not exists." print argParse.print_help() sys.exit(1) configuration = None with open(args.config, "rb") as data: configuration = AttrDict(json.load(data)) configuration.pubnub = AttrDict(configuration.pubnub) configuration.accept = AttrDict(configuration.accept) logging.basicConfig(format=configuration.log_format, level=logging.INFO, filename=configuration.log_file) logger = logging.getLogger("Main") logger.info("Starting...") hdlr = logging.StreamHandler(sys.stderr) hdlr.setFormatter(logging.Formatter(configuration.log_format)) hdlr.setLevel(logging.NOTSET) logging.root.addHandler(hdlr) _handler = create_handler(configuration) if args.input is None: pubnub = Pubnub(publish_key=configuration.pubnub.publish_key, subscribe_key=configuration.pubnub.subscribe_key) pubnub.subscribe(channels=configuration.pubnub.channels, callback=_handler) else: json_data = "" with open(args.input, "rb") as data: json_data = data.read() for json_line in json_data.split('\n'): _handler(json.loads(json_line), configuration.pubnub.channels[0])
class dashjazz(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' : channel, 'message' : message}) def connect(self, channel, receiver): # Listening for messages on the channel self.pubnub.subscribe({ 'channel' : channel, 'callback' : receiver })
class MessageChannel: command_key = 'command' def __init__(self, channel): self.channel = channel publish_key = 'pub-c-8e8bd077-64a9-4b5a-a5dd-a75a1c1118e2' subscribe_key = 'sub-c-81d66b4c-4432-11e6-85a4-0619f8945a4f' 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(self, message, channel): print('received: {0}'.format(message)) def error(self, message): print('error: {0}'.formmat(message)) def connect(self, message): print('connect: {0}'.format(message)) def reconnect(self, message): print('reconnect: {0}'.format(message)) def disconnect(self, message): print('disconnect: {0}'.format(message))
for msg in messages: pubnub.publish(channel="msg_channel", message=msg) # # callback when connected to the PubHub network # def on_reconnect(message): print ("RECONNECTED") # # callback whtn disconnected from the PubHub network def on_disconnect(message): print ("DISCONNECTED") if __name__ == "__main__": # # get keys from the environment variable # pub_key=os.environ['PUB_KEY'] sub_key=os.environ['SUB_KEY'] # # initate the Pubnub instance # subsistute your publish_key and subscribe_key here, if you want more security. But demo should wor pubnub = Pubnub(publish_key=pub_key, subscribe_key=sub_key) # # subscribe to a channel and invoke the appropriate callback when a message arrives on that # channel # pubnub.subscribe(channels="json_channel", callback=sub_callback, error=on_error, connect=on_connect_json, reconnect=on_reconnect, disconnect=on_disconnect) pubnub.start()
def error(message): print("ERROR : " + str(message)) def connect_abc(message): print("CONNECTED " + str(message)) def connect_d(message): print("CONNECTED " + str(message)) pubnub.unsubscribe(channel='d') def reconnect(message): print("RECONNECTED " + str(message)) def disconnect(message): print("DISCONNECTED " + str(message)) print pubnub.channel_group_add_channel(channel_group='abc', channel="b") pubnub.subscribe_group(channel_groups='abc', callback=callback_abc, error=error, connect=connect_abc, reconnect=reconnect, disconnect=disconnect) pubnub.subscribe(channels='d', callback=callback_d, error=error, connect=connect_d, reconnect=reconnect, disconnect=disconnect) pubnub.start()
class Logs(object): """ This class implements functions that allow processing logs from device. This class is implemented using pubnub python sdk. For more details about pubnub, please visit: https://www.pubnub.com/docs/python/pubnub-python-sdk """ def __init__(self): self.config = Config() def _init_pubnub(func): @wraps(func) def wrapper(self, *args, **kwargs): if not hasattr(self, 'pubnub'): pubnub_key = self.config.get_all()['pubnub'] self.pubnub = Pubnub(publish_key=pubnub_key['publish_key'], subscribe_key=pubnub_key['subscribe_key']) return func(self, *args, **kwargs) return wrapper @_init_pubnub def subscribe(self, uuid, callback, error): """ This function allows subscribing to device logs. Testing Args: uuid (str): device uuid. callback (function): this callback is called on receiving a message from the channel. error (function): this callback is called on an error event. For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#subscribe Examples: >>> def callback(message, channel): ... print(message) >>> def error(message): ... print('Error:'+ str(message)) >>> Logs.subscribe(uuid=uuid, callback=callback, error=error) """ channel = self.get_channel(uuid) self.pubnub.subscribe(channels=channel, callback=callback, error=error) @_init_pubnub def history(self, uuid, callback, error): """ This function allows fetching historical device logs. Args: uuid (str): device uuid. callback (function): this callback is called on receiving a message from the channel. error (function): this callback is called on an error event. For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#history Examples: >>> def callback(message): ... print(message) >>> def error(message): ... print('Error:'+ str(message)) Logs.history(uuid=uuid, callback=callback, error=error) """ channel = self.get_channel(uuid) self.pubnub.history(channel=channel, callback=callback, error=error) def unsubscribe(self, uuid): """ This function allows unsubscribing to device logs. Args: uuid (str): device uuid. """ if hasattr(self, 'pubnub'): channel = self.get_channel(uuid) self.pubnub.unsubscribe(channel=channel) @staticmethod def get_channel(uuid): """ This function returns pubnub channel for a specific device. Args: uuid (str): device uuid. Returns: str: device channel. """ return 'device-{uuid}-logs'.format(uuid=uuid)
ALL = [RED, YELLOW, GREEN] GPIO.setup(RED, GPIO.OUT) GPIO.setup(YELLOW, GPIO.OUT) GPIO.setup(GREEN, GPIO.OUT) GPIO.output(ALL, False) mode = "auto" # Set up PubNub pubnub = Pubnub(publish_key=credentials.PUBNUB_PUBLISH_KEY, subscribe_key=credentials.PUBNUB_SUBSCRIBE_KEY, uuid='LIGHT') def _callback(message, channel): if message['text'] == "RED": GPIO.output(ALL, False) GPIO.output(RED, True) if message['text'] == "GREEN": GPIO.output(ALL, False) GPIO.output(GREEN, True) if message['text'] == "YELLOW": GPIO.output(ALL, False) GPIO.output(YELLOW, True) if message['text'] == "OFF": GPIO.output(ALL, False) def _error(message): print(message) pubnub.subscribe(channels="traffic_light", callback=_callback, error=_error) while True: pass
def main(): #------------------------------------------------------------------- # ZEROmq #------------------------------------------------------------------- print("Connecting to Data Service…") sys.stdout.flush() context = zmq.Context() # Socket to talk to server socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:5555") print("Connected....") #------------------------------------------------------------------- # PUBNUB #------------------------------------------------------------------- pubnub = Pubnub(publish_key="pub-c-7d62813d-6e07-4b09-b009-98dc15011db4", subscribe_key="sub-c-9931e424-aad5-11e6-af18-02ee2ddab7fe") def callback(message, channel): print(message) #pubnub.time(callback=_callback) def error(message): print("ERROR : " + str(message)) def connect(message): print("CONNECTED") #print pubnub.publish(channel='prueba', message='Hello from the PubNub Python SDK') def reconnect(message): print("RECONNECTED") def disconnect(message): print("DISCONNECTED") pubnub.subscribe(channels='pruebaa', callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect) #------------------------------------------------------------------- # Comienzo #------------------------------------------------------------------- while (True): # ---------------------------------------- # ZERO mq # ---------------------------------------- #print("\r\nSending request …") socket.send("Requesting... ") # Get the reply. message = socket.recv() #print("Time %s" % message, end='\r') print(message) time.sleep(1) # ---------------------------------------- # PUBNUB # ---------------------------------------- pubnub.subscribe(channels='prueba', callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect) pubnub.publish(channel='prueba', message=message) #time.sleep(3) return 0
def sockpuppet(channel, url, vote): phantom_cmd = "phantomjs " + channel + ".js '" + url + "' " + vote + " " #print phantom_cmd #uncomment for debugging sleep(randint(60,7200)) # tell the bot to randomly wait for 1m to 2h as a naive spam filter bypass os.system(phantom_cmd) # lazy way to do this def callback(message, channel): print('[' + channel + ']: Incoming task ' + str(message)) url = (message['url']) vote = (message['vote']) thread.start_new_thread(sockpuppet,(channel, url, vote)) def error(message): print("ERROR : " + str(message)) def connect(message): print("CONNECTED") def reconnect(message): print("RECONNECTED") def disconnect(message): print("DISCONNECTED") pubnub.subscribe(channels=modules_enabled, callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect) print 'Gathering incoming requests'
epd.display(image) epd.update() def callback(message, channel): # print(message) if GPIO.input(21) == GPIO.HIGH: demo(epd, message) print(len(message)) def error(message): print("ERROR : " + str(message)) def connect(message): print("CONNECTED") def reconnect(message): print("RECONNECTED") def disconnect(message): print("DISCONNECTED") pubnub.subscribe( channels=channel, callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect )
def init(): #Pubnub Key Initialization global pubnub pubnub = Pubnub(publish_key=g_pub_key,subscribe_key=g_sub_key) pubnub.subscribe(channels='KA01M1234', callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect)
class Logs(object): """ This class implements functions that allow processing logs from device. This class is implemented using pubnub python sdk. For more details about pubnub, please visit: https://www.pubnub.com/docs/python/pubnub-python-sdk """ def __init__(self): self.config = Config() def _init_pubnub(func): @wraps(func) def wrapper(self, *args, **kwargs): if not hasattr(self, 'pubnub'): pubnub_key = self.config.get_all()['pubnub'] self.pubnub = Pubnub( publish_key=pubnub_key['publish_key'], subscribe_key=pubnub_key['subscribe_key'] ) return func(self, *args, **kwargs) return wrapper @_init_pubnub def subscribe(self, uuid, callback, error): """ This function allows subscribing to device logs. Testing Args: uuid (str): device uuid. callback (function): this callback is called on receiving a message from the channel. error (function): this callback is called on an error event. For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#subscribe Examples: >>> def callback(message, channel): ... print(message) >>> def error(message): ... print('Error:'+ str(message)) >>> Logs.subscribe(uuid=uuid, callback=callback, error=error) """ channel = self.get_channel(uuid) self.pubnub.subscribe(channels=channel, callback=callback, error=error) @_init_pubnub def history(self, uuid, callback, error): """ This function allows fetching historical device logs. Args: uuid (str): device uuid. callback (function): this callback is called on receiving a message from the channel. error (function): this callback is called on an error event. For more details about callbacks in pubnub subscribe, visit here: https://www.pubnub.com/docs/python/api-reference#history Examples: >>> def callback(message): ... print(message) >>> def error(message): ... print('Error:'+ str(message)) Logs.history(uuid=uuid, callback=callback, error=error) """ channel = self.get_channel(uuid) self.pubnub.history(channel=channel, callback=callback, error=error) def unsubscribe(self, uuid): """ This function allows unsubscribing to device logs. Args: uuid (str): device uuid. """ if hasattr(self, 'pubnub'): channel = self.get_channel(uuid) self.pubnub.unsubscribe(channel=channel) @staticmethod def get_channel(uuid): """ This function returns pubnub channel for a specific device. Args: uuid (str): device uuid. Returns: str: device channel. """ return 'device-{uuid}-logs'.format(uuid=uuid)