def setup(hass, config): """Setup the Wink component.""" logger = logging.getLogger(__name__) if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger): return False import pywink from pubnub import Pubnub pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN]) global SUBSCRIPTION_HANDLER SUBSCRIPTION_HANDLER = Pubnub("N/A", pywink.get_subscription_key(), ssl_on=True) SUBSCRIPTION_HANDLER.set_heartbeat(120) # Load components for the devices in the Wink that we support for component_name, func_exists in ( ('light', pywink.get_bulbs), ('switch', lambda: pywink.get_switches or pywink.get_sirens or pywink.get_powerstrip_outlets), ('binary_sensor', pywink.get_sensors), ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays), ('lock', pywink.get_locks), ('rollershutter', pywink.get_shades), ('garage_door', pywink.get_garage_doors)): if func_exists(): discovery.load_platform(hass, component_name, DOMAIN, {}, config) return True
def setup(hass, config): """Setup the Wink component.""" import pywink user_agent = config[DOMAIN][CONF_USER_AGENT] if user_agent: pywink.set_user_agent(user_agent) from pubnub import Pubnub access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN) if access_token: pywink.set_bearer_token(access_token) else: email = config[DOMAIN][CONF_EMAIL] password = config[DOMAIN][CONF_PASSWORD] client_id = config[DOMAIN]['client_id'] client_secret = config[DOMAIN]['client_secret'] pywink.set_wink_credentials(email, password, client_id, client_secret) global SUBSCRIPTION_HANDLER SUBSCRIPTION_HANDLER = Pubnub( 'N/A', pywink.get_subscription_key(), ssl_on=True) SUBSCRIPTION_HANDLER.set_heartbeat(120) # Load components for the devices in Wink that we support for component in WINK_COMPONENTS: discovery.load_platform(hass, component, DOMAIN, {}, config) return True
class Pnub: def __init__(self, pkey, skey, channel): # Assign publisher key, subscriber key and channel1 self.pkey = pkey self.skey = skey self.channel = channel # Create pubnub object self.pubnub = Pubnub(publish_key = self.pkey, subscribe_key = self.skey) def callback(self, m): #print(m) pass def error(self, m): print("Pubnub error:", m) def publish(self, keys, values): lenght = len(keys) if(lenght != len(values)): print("Lists must be of same length!") return json_map = {} for i in range(0, lenght): json_map[keys[i]] = values[i] result = json.dumps(json_map) self.pubnub.publish(self.channel, result, callback = self.callback, error=self.error)
def send_message(app, message): app.logger.debug("Publish message {} to channel {}".format(message, PUBNUB_CHANNEL)) client = Pubnub(publish_key=app.config['PUBNUB_PUBLISH'], subscribe_key=app.config['PUBNUB_SUBSCRIBER']) return client.publish(channel=PUBNUB_CHANNEL, message=message)
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__(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 __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 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)
def sendNotification(notif, bikeNo): pubnub = Pubnub(publish_key="pub-c-c8508a4f-2f25-4934-b2d1-02b9872a3c20", subscribe_key="sub-c-425d0caa-1da9-11e6-b700-0619f8945a4f") def callback(message): print(message) message = "{\"Bike\":\"" + bikeNo + "\",\"State\":\"" + notif + "\"}" pubnub.publish('bikes_channel', message, callback=callback, error=callback)
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 send_to_channel(ch,name,obj): from pubnub import Pubnub pubnub = Pubnub(publish_key, subscribe_key) s=json.dumps(obj) dl='-_-_'+str(len(s)+1000000)[1:] s=s+dl logging.warning(str(len(s)-10)+" "+ str(len(urllib.quote(s.encode("utf-8")))+97)) #pana a 16000…;la 18000 da err page_num=name for i in xrange(0, len(s), 12000): pubnub.publish(ch, name+page_num+str(i+1000000)[1:]+s[i:i+12000], callback= _callback, error= _callback)
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=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
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)
def notify(msg): pubnub = Pubnub( publish_key=os.getenv('PUBLISH_KEY'), subscribe_key=os.getenv('SUBSCRIBE_KEY'), pooling=False ) channel = 'service_channel' # Synchronous usage print pubnub.publish(channel, msg)
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__(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 __init__(self): self.pubnub = Pubnub(publish_key=DatingCozmo.PUBLISH_KEY, subscribe_key=DatingCozmo.SUBSCRIBE_KEY) self.pubnub.subscribe(channels=DatingCozmo.SUBSCRIBE_CHANNEL, callback=self.on_message_received, error=self.error, connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect) cozmo.setup_basic_logging() cozmo.connect(self.run)
def main(): publish_key = os.environ['PUBNUB_PUBLISH_KEY'] subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY'] pubnub = Pubnub(publish_key, subscribe_key, ssl_on=False) try: cpu = system.SystemInfo() while True: pubnub.publish(channel="kiettv.raspberry.os", message=cpu.get_cpu_percent(), callback=None, error=callback) time.sleep(1) except KeyboardInterrupt: pubnub.unsubscribe(channel='kiettv.raspberry.os') exit(0)
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 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 ImagePublisher(object): def __init__(self): self.pubnub = Pubnub( publish_key=PUBNUB_PUBLISH_KEY, subscribe_key=PUBNUB_SUBSCRIBE_KEY, cipher_key='', ssl_on=False) def publish_frame(self, jpeg_frame): message = base64.b64encode(jpeg_frame) self.pubnub.publish(PUBLISH_CHANNEL, message)
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__(self): cozmo.conn.CozmoConnection.robot_factory = HorseShoeRobot cozmo.setup_basic_logging() self.pubnub = Pubnub(publish_key=HorseShoe.PUBLISH_KEY, subscribe_key=HorseShoe.SUBSCRIBE_KEY) self.pubnub.subscribe(channels=HorseShoe.SUBSCRIBE_CHANNEL, callback=self.on_message_received, error=self.error, connect=self.connect, reconnect=self.reconnect, disconnect=self.disconnect) self.init_game()
def _send_image_back_to_user(phone_num_or_email, watermark_image_url): if COMPANY_SETTINGS["web_flow"]: # TODO vars need renaming pubnub = Pubnub( publish_key=PUBNUB_PUBLISH_KEY, subscribe_key=PUBNUB_SUBSCRIBE_KEY, ) pubnub.publish(phone_num_or_email, watermark_image_url) elif COMPANY_SETTINGS["sms_photos"]: ImageTexter().text_image(phone_num_or_email, watermark_image_url) elif COMPANY_SETTINGS["email_photos"]: ImageEmailer().email_image(phone_num_or_email, watermark_image_url)
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)
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)
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 send_pubnub_clerk(doc, method): message = frappe.get_doc("Message", doc.name) pubnub = Pubnub(publish_key="pub-c-21663d8a-850d-4d99-adb3-3dda55a02abd", subscribe_key="sub-c-266bcbc0-9884-11e6-b146-0619f8945a4f") if message.destination_type == "Delivery Clerk": pubnub.publish(channel=message.destination, message={'type':message.type, 'message':message.message, 'order_id':message.order_id} ) elif message.destination_type == "Client": pubnub.publish(channel=message.destination, message={'type':message.type, 'message':message.message} ) pubnub.publish(channel='dashboard_updates', message={'type':message.type} )
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)
class MyPubnubConn(): def __init__(self, channel): self.conn = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, ssl_on=True, # cipherkey randomly generated for purposes of PoC, but it is too short and needs to be # securely stored. # cipher_key=cipher_key ) self.channel = channel self.subscribed = threading.Event() # server doesn't need to subscribe, only publish #self.conn.subscribe(channels=self.channel, callback=self.incoming_message, error=self.error_cb, # connect=self.connect_cb, reconnect=self.reconnect_cb, disconnect=self.disconnect_cb) def incoming_message(self, message, channel): pass #print(message) def error_cb(self, message): pass #print("\tERROR : " + str(message)) def connect_cb(self, message): self.subscribed.set() def reconnect_cb(self, message): self.subscribed.set() #print("\tRECONNECTED") def disconnect_cb(self, message): self.subscribed.clear() #print("\tDISCONNECTED") def send_cb(self, message): pass def discontinue(self): self.conn.unsubscribe(channel=self.channel) def publish(self, message): self.conn.publish(channel=self.channel, message=message, callback=self.send_cb, error=self.error_cb) def wait_until_ready(self): self.subscribed.wait() def print_status(self): print("\nCurrently connected to channel '%s'" % self.channel)
def init(): #uses Bradcom pin numbering scheme GPIO.setmode(GPIO.BCM) #remove all runtime warings in gpio GPIO.setwarnings(False) GPIO.setup(BULB, GPIO.OUT) #setting up bulb pin GPIO.setup(FAN, GPIO.OUT) #setting up fan pin GPIO.setup(TAP, GPIO.OUT) #setting up Tap pin GPIO.setup(MOTOR, GPIO.OUT) #setting up motor pin GPIO.setup(PIR, GPIO.IN) #setting up PIR pin GPIO.setup(WARNING, GPIO.OUT) #setting up PIR pin #connecting in active low so turn off GPIO.output(BULB, True) GPIO.output(FAN, True) GPIO.output(MOTOR, True) GPIO.output(TAP, True) GPIO.output(WARNING, True) #change default action of SIGCHLD signal.signal(signal.SIGCHLD, handler1) pubnub = Pubnub( publish_key='pub-xxxxxxxxxxxxxxxxxxxxxxxxxxxx', subscribe_key='sub-c-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') #initialize adc spi.adc_setup() return pubnub
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 do_init(self, command, opts): global pubnub global print_ok global print_error global print_ok_normal global print_error_normal global print_error_pretty global print_ok_pretty self.publish_key = opts.publish_key if opts.publish_key is not None else self.publish_key self.subscribe_key = opts.subscribe_key if opts.subscribe_key is not None else self.subscribe_key self.secret_key = opts.secret_key if opts.secret_key is not None else self.secret_key self.cipher_key = opts.cipher_key if opts.cipher_key is not None else self.cipher_key self.auth_key = opts.auth_key if opts.auth_key is not None else self.auth_key self.origin = opts.origin if opts.origin is not None else self.origin self.uuid = opts.uuid if opts.uuid is not None else self.uuid self.ssl = opts.ssl if opts.ssl is not None else self.ssl self.disable_pretty = opts.disable_pretty if opts.disable_pretty is not None else self.disable_pretty pubnub = Pubnub(self.publish_key, self.subscribe_key, self.secret_key, self.cipher_key, self.auth_key, self.ssl, self.origin, self.uuid) self.prompt = self.get_prompt() if opts.disable_pretty is True: print_ok = print_ok_normal print_error = print_error_normal else: print_ok = print_ok_pretty print_error = print_error_pretty
def test_publish_succeeds_with_good_message(self): """ Asserts that the publish API can send a valid input :return: """ myTestChannel = _util_add_salt("gzz_test_publish_good_message") myTestMessage = { 'user': '******', 'text': _util_add_salt("publishing a good message"), 'channel': myTestChannel, } referenceConn = Pubnub( publish_key=myPubnubConn.publish_key, subscribe_key=myPubnubConn.subscribe_key, ssl_on=True, ) wrapper = PubNubWrapper(referenceConn) wrapper.wait_for_subscribe(myTestChannel) response = self.client.post(reverse("chatserver:send"), myTestMessage) received_msg, received_channel = wrapper.get_previous_message() wrapper.terminate(myTestChannel) self.assertEquals(received_msg['text'], myTestMessage['text']) self.assertEquals(myTestChannel, received_channel)
def test_publish_works_with_bad_message(self): """ Technically, we should test this with every variant of possible bad message ... :return: """ myTestChannel = _util_add_salt("gzz_test_publish_bad_message") myExpectedChannel = myPubnubConn.default_channel myTestMessage = { 'user': '******', 'text': _util_add_salt("publishing a good message"), } referenceConn = Pubnub( publish_key=myPubnubConn.publish_key, subscribe_key=myPubnubConn.subscribe_key, ssl_on=True, ) wrapper = PubNubWrapper(referenceConn) wrapper.wait_for_subscribe(myTestChannel) wrapper.wait_for_subscribe(myExpectedChannel) response = self.client.post(reverse("chatserver:send"), myTestMessage) received_msg, received_channel = wrapper.get_previous_message() wrapper.terminate(myTestChannel) wrapper.terminate(myExpectedChannel) self.assertEquals("Did not receive message from user.", received_msg['text'])
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()
def test_conn_can_publish(self): """ Assert that the connection's publish command correctly publishes some message """ myTestChannel = _util_add_salt("gzz_test_conn_can_publish") myTestMessage = _util_add_salt("myConn can publish") sendConn = myPubnubConn.MyPubnubConn(channel=myTestChannel) referenceConn = Pubnub( publish_key=myPubnubConn.publish_key, subscribe_key=myPubnubConn.subscribe_key, ssl_on=True, ) referenceWrapper = PubNubWrapper(referenceConn) referenceWrapper.wait_for_subscribe(myTestChannel) sendConn.publish(myTestMessage) received_msg, received_channel = referenceWrapper.get_previous_message( ) referenceWrapper.terminate(myTestChannel) self.assertEquals(myTestMessage, received_msg) self.assertEquals(myTestChannel, received_channel)
def pubnub(self, subscribe_key, ssl_on=False, publish_key=''): if self._use_mock: return PubnubMock() else: return Pubnub(subscribe_key=subscribe_key, ssl_on=ssl_on, publish_key=publish_key)
def __init__(self): super().__init__() self._settings = OrderedDict(sorted(utils.init_settings().items(), key=lambda t: t[0])) self._history = utils.init_history() self._current_temperature = Decimal(0) self._temperature_range = (Decimal(0), Decimal(0)) self._on_rpi = utils.on_rpi() self._mode = utils.Mode.OFF self._state = utils.State.IDLE self.logger = getLogger('app.thermostat') self.temperature_offset = Decimal('0.8') # DEMO value, original Decimal('1.5') self.last_state_update = 0 self.cost_table = None # must init after thread starts self.pubnub = Pubnub( publish_key=config.PUBLISH_KEY, subscribe_key=config.SUBSCRIBE_KEY, uuid=config.THERMOSTAT_ID, ) self.weather_thread = weather.WeatherAPI( self._settings['temperature_unit'], self._settings['city'], self._settings['country_code'], ) # TODO: actively record user actions (input range, changes after prediction) self.history_thread = threading.Timer(600, self.set_history) self.history_thread.daemon = True self.locks = { 'settings': threading.Lock(), 'temperature_range': threading.Lock(), }
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 update(self, sessionToken, username): self.username = username self.sessionToken = sessionToken self.temperature = 0 self.humidity = 0 self.moisture = 0 self.light = 0 self.waterNow = False grovepi.pinMode(constants.LIGHT_PIN,"INPUT") grovepi.pinMode(constants.MOISTURE_PIN,"INPUT") grovepi.pinMode(constants.TEMP_HUMIDITY_PIN,"INPUT") grovepi.pinMode(constants.PUMP_RELAY_PIN,"OUTPUT") self.pubnub = Pubnub(publish_key=constants.PUBNUB_PUBLISH_KEY, subscribe_key=constants.PUBNUB_SUBSCRIBE_KEY, ssl_on = True) self.sendSensors = False while True: #keep trying until you have internet try: req = urllib2.Request(constants.ROOT_URL + 'active-plant') req.add_header('x-access-token', sessionToken) result = json.loads(urllib2.urlopen(req).read()) self.waterAmount = result["waterAmount"] self.harvest = len(result["harvests"]) self.moistureLimit = result["moistureLimit"] break except Exception as e: s = str(e)
def __init__(self, url, keepAlive = False, sendReceipts = False): super(Server, self).__init__() self.sendReceipts = sendReceipts self.keepAlive = keepAlive self.db = create_engine(url, echo=False, pool_size=10, pool_timeout=600,pool_recycle=300) self.Session = sessionmaker(bind=self.db) self.s = self.Session() self.job = None self.pubnub = Pubnub(os.environ['PUB_KEY'], os.environ['SUB_KEY'], None, False) self.timeout = int(os.getenv('TIMEOUT', 3600)) connectionManager = YowsupConnectionManager(self.timeout) connectionManager.setAutoPong(keepAlive) self.signalsInterface = connectionManager.getSignalsInterface() self.methodsInterface = connectionManager.getMethodsInterface() self.signalsInterface.registerListener("message_received", self.onMessageReceived) self.signalsInterface.registerListener("group_messageReceived", self.onGroupMessageReceived) self.signalsInterface.registerListener("image_received", self.onImageReceived) self.signalsInterface.registerListener("video_received", self.onVideoReceived) self.signalsInterface.registerListener("audio_received", self.onAudioReceived) self.signalsInterface.registerListener("vcard_received", self.onVCardReceived) self.signalsInterface.registerListener("location_received", self.onLocationReceived) self.signalsInterface.registerListener("receipt_messageSent", self.onReceiptMessageSent) self.signalsInterface.registerListener("receipt_messageDelivered", self.onReceiptMessageDelivered) self.signalsInterface.registerListener("auth_success", self.onAuthSuccess) self.signalsInterface.registerListener("auth_fail", self.onAuthFailed) self.signalsInterface.registerListener("disconnected", self.onDisconnected) self.signalsInterface.registerListener("contact_gotProfilePicture", self.onGotProfilePicture) self.signalsInterface.registerListener("profile_setStatusSuccess", self.onSetStatusSuccess) self.signalsInterface.registerListener("group_createSuccess", self.onGroupCreateSuccess) self.signalsInterface.registerListener("group_createFail", self.onGroupCreateFail) self.signalsInterface.registerListener("group_gotInfo", self.onGroupGotInfo) self.signalsInterface.registerListener("group_addParticipantsSuccess", self.onGroupAddParticipantsSuccess) self.signalsInterface.registerListener("group_removeParticipantsSuccess", self.onGroupRemoveParticipantsSuccess) self.signalsInterface.registerListener("group_imageReceived", self.onGroupImageReceived) self.signalsInterface.registerListener("group_subjectReceived", self.onGroupSubjectReceived) self.signalsInterface.registerListener("notification_removedFromGroup", self.onNotificationRemovedFromGroup) self.signalsInterface.registerListener("notification_groupParticipantAdded", self.onNotificationGroupParticipantAdded) self.signalsInterface.registerListener("group_gotParticipants", self.onGotGroupParticipants) self.signalsInterface.registerListener("media_uploadRequestSuccess", self.onUploadRequestSuccess) # self.signalsInterface.registerListener("media_uploadRequestFailed", self.onUploadRequestFailed) self.signalsInterface.registerListener("media_uploadRequestDuplicate", self.onUploadRequestDuplicate) self.signalsInterface.registerListener("presence_available", self.onPresenceAvailable) self.signalsInterface.registerListener("presence_unavailable", self.onPresenceUnavailable) self.cm = connectionManager self.url = os.environ['URL'] self.post_headers = {'Content-type': 'application/json', 'Accept': 'application/json'} self.done = False
def __init__(self, channel): self.conn = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, ssl_on=True, # cipherkey randomly generated for purposes of PoC, but it is too short and needs to be # securely stored. # cipher_key=cipher_key ) self.channel = channel self.subscribed = threading.Event()
def resetKeys(self): try: from pubnub import Pubnub self.pubnub = Pubnub( publish_key = str(self.pubEdit.text()), subscribe_key = str(self.subEdit.text())) except Exception as e: self.responseLabel.setText (e)
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 __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 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 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()
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)
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, pkey, skey, channel): # Assign publisher key, subscriber key and channel1 self.pkey = pkey self.skey = skey self.channel = channel # Create pubnub object self.pubnub = Pubnub(publish_key = self.pkey, subscribe_key = self.skey)
def __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()
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'], )