Пример #1
0
class RemotePubNub():

    def __init__(self, PUBNUB_PUBLISH_KEY="demo", PUBNUB_SUBSCRIBE_KEY="demo", queue=None):
        self.pubnub = Pubnub(publish_key=PUBNUB_PUBLISH_KEY, subscribe_key=PUBNUB_SUBSCRIBE_KEY)
        self.queue = queue

    def get_queue(self):
        return self.queue

    def publish(self, channel, message):
        self.pubnub.publish(channel, message)
        #logging.info("message published")

    def subscribe(self, channel):
        self.pubnub.subscribe(
            channel, callback=self.parse_command, error=self.sub_error,
            connect=self.sub_connect, disconnect=self.sub_disconnect)

    def parse_command(self, message, channel):
        if self.queue is not None:
            print message
            self.queue.put(message)

    def sub_error(message):
        logging.ERROR(message)

    def sub_connect(self, channel):
        message = 'Connected to: %s' % channel
        logging.info(message)

    def sub_disconnect(self, message):
        logging.info(message)
Пример #2
0
    def run(self, channel, latency, bufferSize):
        self.mutex = Lock()
        self.outqueuebuffers = {}
        self.outbuffers = {}
        self.senders = {}
        self.channels = None
        self.channel = channel
        self.buffer_size = bufferSize
        self.timestamp_buffer = [None] * self.buffer_size
        self.debug = False

        self.index = 0
        self.offset = None
        self.latency = latency
        self.setupDone = False
        self.channel_count = 0

        pubnub = Pubnub(
            "pub-c-e655613e-f776-4301-9f29-f71edbcd6559",
            "sub-c-2eafcf66-c636-11e3-8dcd-02ee2ddab7fe",
            "sec-c-ZjUwZDgzMTItYzE2Mi00ZGYyLTg2NGMtNmE5N2Q3MGI0MTli", False)

        self.m = MQTT()
        broker = config.mqtt['Broker']
        print("Connecting to broker: " + broker)
        self.m.connect(broker)

        while (True):
            pubnub.subscribe({
                'channel': self.channel,
                'callback': self.setData
            })
Пример #3
0
    def run(self, channel, latency, bufferSize):
        self.mutex = Lock()
        self.outqueuebuffers = {}
        self.outbuffers = {}
        self.senders = {}
        self.channels = None
        self.channel = channel
        self.buffer_size = bufferSize
        self.timestamp_buffer = [None] * self.buffer_size
        self.debug = False

        self.index = 0
        self.offset = None
        self.latency = latency
        self.setupDone = False
        self.channel_count = 0

        pubnub = Pubnub("pub-c-e655613e-f776-4301-9f29-f71edbcd6559",
                        "sub-c-2eafcf66-c636-11e3-8dcd-02ee2ddab7fe",
                        "sec-c-ZjUwZDgzMTItYzE2Mi00ZGYyLTg2NGMtNmE5N2Q3MGI0MTli",
                        False)

        self.m = MQTT()
        broker = config.mqtt['Broker'] 
        print("Connecting to broker: " + broker)
        self.m.connect(broker)
        
        while(True):
            pubnub.subscribe({
                'channel': self.channel,
                'callback': self.setData
                })              
Пример #4
0
def startStockPicker(server, port):

    global globalQueueRef

    #Step 1 - Initialize MongoDB & PubNub Connection
    mongoconn = pymongo.MongoClient(server, port)
    db = mongoconn.stockdb
    coll = db.stockcollection

    #Setup index on time to fetch the latest update
    coll.create_index([('time', DESCENDING)])

    #YOUR PUBNUB KEYS - Replace the publish_key and subscriber_key below with your own keys
    pubnub = Pubnub(publish_key="<your publish key>",
                    subscribe_key="<your subscribe key>")

    #Step 2 - Check and define the metadata ( index names )
    metaDataInit(coll)

    #Step 3 - Set the parameters , max periodicity , random range
    updateTime = 10  #Max ten seconds for every price update
    numOfItems = 4  #Four indices to manage

    random.seed()

    #Step 4 - Setup the Queue and ClientListener Thread
    clientQueue = Queue()
    clientListener = ClientListenerThread(server, port, clientQueue, pubnub)
    clientListener.start()

    globalQueueRef = clientQueue

    #Step 5 - Setup PubNub Subscription for client requests
    pubnub.subscribe("stockhistory", historyCallback, historyError)

    #Step 6 - Start the stock picking loop
    while True:

        #Step 6.1 - Wait for random time
        time.sleep(random.randint(1, updateTime))

        #Step 6.2 - Wake up and update the stock price for one of the index
        newPriceData = getUpdatedPrice(coll)

        #Step 6.3 - Update the new price in DB
        print "New Price Update " + str(newPriceData)
        coll.insert(newPriceData)

        #Step 6.4 - Publish over Pubnub , stockdata channel
        broadcastData = {
            'name': newPriceData['name'],
            'value': newPriceData['value'],
            'change': newPriceData['change'],
            'time': newPriceData['time'],
        }

        pubnub.publish('stockdata', json.dumps(broadcastData))
Пример #5
0
def main():

    resetAVR()
    print("Establishing Connections...")
    pubnub = Pubnub(publish_key   = 'pub-c-f83b8b34-5dbc-4502-ac34-5073f2382d96',
                subscribe_key = 'sub-c-34be47b2-f776-11e4-b559-0619f8945a4f',
                uuid = "pi")

    channel = 'leap2pi'
    GPIO.output(4, False)

    def _connect(m):
        print("Connected to PubNub!")
        GPIO.output(4, True)

    def _reconnect(m):
        print("Reconnected to PubNub!")
        GPIO.output(4, True)

    def _disconnect(m):
        print("Disconnected from PubNub!")
        GPIO.output(4, False)

    def _callback(m,n):
        left_byte = 0
        right_byte = 0
        # ==============================Left Hand==============================
        left_hand = m.get("left_hand",{})
        if left_hand != {}:
            left_byte = handleLeft(left_hand)
            #print(left_hand)

        # ==============================Right Hand=============================
        right_hand = m.get("right_hand",{})
        if right_hand != {}:
            right_byte= handleRight(right_hand)
            #print(right_hand)

        byte = left_byte | right_byte
        #print(byte)

        #====send i2c=====#
        try:
            bus.write_byte(0x47,byte)
        except IOError:
            print("Error!!!!")
            resetAVR()
            bus.write_byte(0x47,byte)
            

    #Catch and Print Error
    def _error(m):
        GPIO.output(4, False)
        print(m)
    
    #Subscribe to subchannel, set callback function to  _callback and set error fucntion to _error
    pubnub.subscribe(channels=channel, callback=_callback, error=_error, connect=_connect, reconnect=_reconnect, disconnect=_disconnect)
Пример #6
0
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))
Пример #7
0
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))
Пример #8
0
def main(USERNAME, PASSWORD, SENSOR_ID):

    lcd = Adafruit_CharLCD()
    lcd.clear()

    sessionToken, objectID = LoginUser(USERNAME, PASSWORD)

    pubnub = Pubnub(publish_key="pub-c-e6b9a1fd-eed2-441a-8622-a3ef7cc5853a",
                    subscribe_key="sub-c-7e14a542-b148-11e4-9beb-02ee2ddab7fe")

    channel = SENSOR_ID

    def _callback(message, channel):
        print("Message received from channel: ", message)
        data = {'status': None, 'targetTemperature': None}
        if message['airconStatus']:
            if message['airconStatus'] == 'on':
                print "Lets turn on air con now"
                lcd.clear()
                lcd.message("Aircon On!")
                logging.warning("Lets turn on air con now")
            else:
                print "lets turn off aircon now"
                lcd.clear()
                lcd.message("Aircon Off!\n  Have a good day!")
                logging.warning("Lets turn off air con now")
            data['status'] = message['airconStatus']
        if message['targetTemperature']:
            print "Lets turn aircon to : ", message['targetTemperature']

            lcd.clear()
            lcd.message("Setting temperature\n" +
                        "Temp={0:0.1f}*C".format(message['targetTemperature']))

            logging.warning("Lets turn aircon to : " +
                            str(message['targetTemperature']))
            data['targetTemperature'] = message['targetTemperature']

        if message[
                'switchOffLCD']:  #note that this might happen a few times because current logic is if last activity was more than 3 mins ago, we swtich off
            print "Lets switch off LCD"
            lcd.clear()
            logging.warning("switching off LCD")

        needToReLogin = SendDataToParse(data, objectID, sessionToken,
                                        SENSOR_ID)

    def _error(message):
        print("Error: ", message)
        logging.warning("Error: ", message)

    pubnub.subscribe(channel, callback=_callback, error=_error)
Пример #9
0
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)
Пример #10
0
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)
Пример #11
0
def init(func):
    global pubnub
    global pubnub_freeboard
    global message_cb

    try:
        message_cb = func
        log.info("pubnub SUBSCRIBE")
        pubnub = Pubnub(publish_key=PUB_KEY, subscribe_key=SUB_KEY, cipher_key=CHIPER_KEY, ssl_on=True)
        pubnub.subscribe(CHANNEL, callback=pubnub_message_cb, error=pubnub_error_cb, connect=pubnub_connect_cb, reconnect=pubnub_reconnect_cb, disconnect=pubnub_disconnect_cb)
        pubnub_freeboard = Pubnub(publish_key=PUB_KEY, subscribe_key=SUB_KEY, ssl_on=False)

        log.info("pubnub SUBSCRIBED")
    except:
        log.error("Error initializing pubnub...Cannot continue")
        raise SystemExit
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
        )
Пример #13
0
def main():
	print "started"
	global t
	t = threading.Timer(TEMPO, callback_timer)
	t.start()
	
	
	pubnub = Pubnub(
	    "pub-e10385fe-9f9f-46a4-b969-f3c8ba11ff59",  ## PUBLISH_KEY
	    "sub-f8f2ff3a-a176-11e1-bbc1-f151a023fb9a",  ## SUBSCRIBE_KEY
	    "sec-OGY5MTk3Y2QtMDY2OS00NThiLTlmZjItNWFkZGM3NDgxMmZi",
	    False
	)
	
	print("subscribing...")
	pubnub.subscribe({
	    'channel'  : 'fbhackaton_newquestion',
	    'callback' : receive 
	})
Пример #14
0
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
        })
Пример #15
0
class WatchRemote():
    """monitoring remote repository"""

    def __init__(self, pid, path, key ):
        self.pid = pid
        self.path = path
        self.pubnub = Pubnub( None, key, None, False )

    
    def receive(self,message) :
        notify('GitBox Download', 'receiving new and changed files in %s' % self.path)
        cmd = 'git push'
        process = subprocess.Popen(cmd.split(' '), cwd=self.path)
        process.communicate()
        return True

    def start(self):
        ## Initiat Class
        self.pubnub.subscribe({'channel'  : self.pid, 'callback' : self.receive })

    def stop(self):
        pass
Пример #16
0
    message['withdrawListSize'] = len(message['withdrawList'])
    message['totalCredit'] = message['credit'] + message['cash']
    if (message['userName'].isalpha()==False):
        message['userName'] = make_english_name(message['userName'])

    print(message)
    print_receipt_on(printer, message)
   

def connected():
    print('Connected')

## -----------------------------------------------------------------------
## Main
## -----------------------------------------------------------------------
pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on)

pubnub.subscribe({
    'channel' : channel_name,
    'connect' : connected,
    'callback' : message_received
})

## -----------------------------------------------------------------------
## IO Event Loop
## -----------------------------------------------------------------------
try:
    pubnub.start()
except:
    pass
Пример #17
0
def speed():  # Speeds up the motor
    wiringpi.pwmWrite(18, 900)


adcChannel = 1
spi = spidev.SpiDev()
spi.open(0, 0)

is_warning = False

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
Пример #18
0
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()
Пример #19
0
def main():

    resetAVR()
    print("Establishing Connections...")
    pubnub = Pubnub(publish_key='pub-c-f83b8b34-5dbc-4502-ac34-5073f2382d96',
                    subscribe_key='sub-c-34be47b2-f776-11e4-b559-0619f8945a4f',
                    uuid="pi")

    channel = 'leap2pi'
    GPIO.output(4, False)

    def checkValue(value):
        if (value < SERVO_MIN):
            value = SERVO_MIN
        elif (value > SERVO_MAX):
            value = SERVO_MAX
        return value

    def invertValue(value):
        value = checkValue(value)
        return SERVO_MAX - value + SERVO_MIN

    def _connect(m):
        print("Connected to PubNub!")
        GPIO.output(4, True)

    def _reconnect(m):
        print("Reconnected to PubNub!")
        GPIO.output(4, True)

    def _disconnect(m):
        print("Disconnected from PubNub!")
        GPIO.output(4, False)

    def _callback(m, n):
        left_byte = 0
        right_byte = 0
        yaw = 0
        pitch = 0
        byte = 0

        # Handle message
        left_hand = m.get("left_hand", {})
        right_hand = m.get("right_hand", {})

        if (servo_mode == MIRROR):
            # Leap Motion: Left hand, Servos: Stage Left
            if left_hand != {}:
                yaw = left_hand["left_yaw"]
                yaw = checkValue(yaw)
                pitch = left_hand["left_pitch"]
                pitch = checkValue(pitch)
                left_byte = left_hand["left_byte"]
                pwm.setPWM(0, 0, yaw)
                pwm.setPWM(1, 1, pitch)
            # Leap Motion: Left hand, Servos: Stage Right
            if right_hand != {}:
                yaw = right_hand["right_yaw"]
                yaw = checkValue(yaw)
                pitch = right_hand["right_pitch"]
                pitch = checkValue(pitch)
                right_byte = right_hand["right_byte"] >> 4
                pwm.setPWM(2, 2, yaw)
                pwm.setPWM(3, 3, pitch)

            byte = left_byte | (right_byte << 4)

        elif (servo_mode == CLONE):
            # Leap Motion: Left hand, Servos: Stage Right
            if left_hand != {}:
                yaw = left_hand["left_yaw"]
                yaw = invertValue(yaw)
                pitch = left_hand["left_pitch"]
                pitch = invertValue(pitch)
                left_byte = left_hand["left_byte"]
                pwm.setPWM(2, 2, yaw)
                pwm.setPWM(3, 3, pitch)
            # Leap Motion: Left hand, Servos: Stage Left
            if right_hand != {}:
                yaw = right_hand["right_yaw"]
                yaw = invertValue(yaw)
                pitch = right_hand["right_pitch"]
                pitch = invertValue(pitch)
                right_byte = right_hand["right_byte"] >> 4
                pwm.setPWM(0, 0, yaw)
                pwm.setPWM(1, 1, pitch)

            byte = (left_byte << 4) | right_byte

        else:
            byte = -1

        #====send i2c=====#
        if (byte >= 0):
            try:
                bus.write_byte(0x47, byte)
            except IOError:
                print("Error!!!!")
                resetAVR()
                bus.write_byte(0x47, byte)

    #Catch and Print Error
    def _error(m):
        GPIO.output(4, False)
        print(m)

    #Subscribe to subchannel, set callback function to  _callback and set error fucntion to _error
    pubnub.subscribe(channels=channel,
                     callback=_callback,
                     error=_error,
                     connect=_connect,
                     reconnect=_reconnect,
                     disconnect=_disconnect)

    # Loop here forever
    while True:
        # Check for switch position
        time.sleep(1)
        if (GPIO.input(16) == False):
            servo_mode = CLONE
        elif (GPIO.input(20) == False):
            servo_mode = MIRROR
        else:
            servo_mode = DISABLED
def init():
	global pubnub
	pubnub = Pubnub(publish_key="demo", subscribe_key="demo")
	pubnub.subscribe(channels=pubnub_responsechannel, callback=_callback, error=_error)
Пример #21
0
def main():

    resetAVR()
    print("Establishing Connections...")
    pubnub = Pubnub(publish_key   = 'pub-c-f83b8b34-5dbc-4502-ac34-5073f2382d96',
                subscribe_key = 'sub-c-34be47b2-f776-11e4-b559-0619f8945a4f',
                uuid = "pi")

    channel = 'leap2pi'
    GPIO.output(4, False)

    def checkValue(value):
        if (value < SERVO_MIN):
            value = SERVO_MIN
        elif(value > SERVO_MAX):
            value = SERVO_MAX
        return value

    def invertValue(value):
        value = checkValue(value)
        return SERVO_MAX - value + SERVO_MIN

    def _connect(m):
        print("Connected to PubNub!")
        GPIO.output(4, True)

    def _reconnect(m):
        print("Reconnected to PubNub!")
        GPIO.output(4, True)

    def _disconnect(m):
        print("Disconnected from PubNub!")
        GPIO.output(4, False)

    def _callback(m,n):
        left_byte = 0
        right_byte = 0
        yaw = 0
        pitch = 0
        byte = 0

        # Handle message
        left_hand = m.get("left_hand",{})
        right_hand = m.get("right_hand",{})

        if (servo_mode == MIRROR):
            # Leap Motion: Left hand, Servos: Stage Left
            if left_hand != {}:
                yaw = left_hand["left_yaw"]
                yaw = checkValue(yaw)
                pitch = left_hand["left_pitch"]
                pitch = checkValue(pitch)
                left_byte = left_hand["left_byte"]
                pwm.setPWM(0, 0, yaw)
                pwm.setPWM(1, 1, pitch)
            # Leap Motion: Left hand, Servos: Stage Right
            if right_hand != {}:
                yaw = right_hand["right_yaw"]
                yaw = checkValue(yaw)
                pitch = right_hand["right_pitch"]
                pitch = checkValue(pitch)
                right_byte = right_hand["right_byte"] >> 4
                pwm.setPWM(2, 2, yaw)
                pwm.setPWM(3, 3, pitch)

            byte = left_byte | (right_byte << 4)

        elif (servo_mode == CLONE):
            # Leap Motion: Left hand, Servos: Stage Right
            if left_hand != {}:
                yaw = left_hand["left_yaw"]
                yaw = invertValue(yaw)
                pitch = left_hand["left_pitch"]
                pitch = invertValue(pitch)
                left_byte = left_hand["left_byte"]
                pwm.setPWM(2, 2, yaw)
                pwm.setPWM(3, 3, pitch)
            # Leap Motion: Left hand, Servos: Stage Left
            if right_hand != {}:
                yaw = right_hand["right_yaw"]
                yaw = invertValue(yaw)
                pitch = right_hand["right_pitch"]
                pitch = invertValue(pitch)
                right_byte = right_hand["right_byte"] >> 4
                pwm.setPWM(0, 0, yaw)
                pwm.setPWM(1, 1, pitch)

            byte = (left_byte << 4) | right_byte

        else:
            byte = -1

        #====send i2c=====#
        if (byte >= 0):
            try:
                bus.write_byte(0x47,byte)
            except IOError:
                print("Error!!!!")
                resetAVR()
                bus.write_byte(0x47,byte)
            

    #Catch and Print Error
    def _error(m):
        GPIO.output(4, False)
        print(m)
    
    #Subscribe to subchannel, set callback function to  _callback and set error fucntion to _error
    pubnub.subscribe(channels=channel, callback=_callback, error=_error, connect=_connect, reconnect=_reconnect, disconnect=_disconnect)

    # Loop here forever
    while True:
        # Check for switch position
        time.sleep(1)
        if(GPIO.input(16) == False):
            servo_mode = CLONE
        elif (GPIO.input(20) == False):
            servo_mode = MIRROR
        else:
            servo_mode = DISABLED
Пример #22
0
       ""
    ) % {
        'max'                  : trips['max'],
        'avg'                  : trips['avg'],
        'publishes'            : analytics['publishes'],
        'received'             : analytics['received'],
        'successful_publishes' : analytics['successful_publishes'],
        'failed_publishes'     : analytics['failed_publishes'],
        'failed_deliveries'    : analytics['failed_deliveries'],
        'publishes'            : analytics['publishes'],
        'deliverability'       : analytics['deliverability'],
        'queued'               : analytics['queued']
    } )
    pubnub.timeout( show_status, 1 )

def connected():
    show_status()
    pubnub.timeout( send, 1 )

print( "Connected: %s\n" % origin )
pubnub.subscribe({
    'channel'  : channel,
    'connect'  : connected,
    'callback' : received
})

## -----------------------------------------------------------------------
## IO Event Loop
## -----------------------------------------------------------------------
pubnub.start()
Пример #23
0
## -----------------------------------------------------------------------
history = pubnub.history({
    'channel' : crazy,
    'limit'   : 1
})
test(
    history[0].encode('utf-8') == crazy,
    'History Message: ' + history[0]
)
test( len(history) == 1, 'History Message Count' )

## -----------------------------------------------------------------------
## PubNub Server Time Example
## -----------------------------------------------------------------------
timestamp = pubnub.time()
test( timestamp > 0, 'PubNub Server Time: ' + str(timestamp) )

## -----------------------------------------------------------------------
## Subscribe Example
## -----------------------------------------------------------------------
def receive(message) :
    print(message)
    return True

pubnub.subscribe({
    'channel'  : crazy,
    'callback' : receive 
})


Пример #24
0
    global node_state
    global next_call
    try:
        get_state()
        print datetime.datetime.now(), "publish", node_state[node_type]
        pubnub.publish(node_type, node_state[node_type])
        select_active()
    except:
        print "unknown error"

    next_call = next_call + 10
    threading.Timer(next_call - time.time(), state_publish).start()


## -----------------------------------------------------------------------
## Initiate Pubnub State
## -----------------------------------------------------------------------
publish_key = config["pubnub_auth"]["publish_key"]
subscribe_key = config["pubnub_auth"]["subscribe_key"]
secret_key = config["pubnub_auth"]["secret_key"]
cipher_key = config["pubnub_auth"]["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
)

pubnub.subscribe(node_type_other, callback=callback, error=error)

next_call = (int(time.time() / 10)) * 10 + 5
state_publish()
Пример #25
0
ser = serial.Serial('COM4', 9600)

pubnub = Pubnub(publish_key="pub-c-6a3d5bbe-652b-49a2-bca1-ccb6db8bb50d", subscribe_key="sub-c-5fa82184-f7ba-11e4-8fd2-02ee2ddab7fe")

def _callback(message, channel):
    if message["sender"] == "browser":
        print(message['setSystemStatus'])
        signal.set()
        #time.sleep(2)
        out_message = {"sender": "bric", "body": "status update"}
        pubnub.publish("demo_tutorial", out_message, callback=callback, error=callback)

def _error(message):
    print("error")

pubnub.subscribe(channels="demo_tutorial", callback=_callback, error=_error)

def callback(message):
    print("callback place holder")

while True:
    if not signal.is_set():
        s = ser.readline()
        out_message = {"sender": "bric", "body": s}
        pubnub.publish("demo_tutorial", out_message, callback=callback(out_message), error=callback(out_message))
        time.sleep(1)
    elif signal.is_set():
        print "status configuration"
        time.sleep(2)
        output = subprocess.check_output('ipconfig')
        print("Programming Arduino...done")
Пример #26
0
## -----------------------------------------------------------------------
## 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 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
})
Пример #27
0
            result = json.loads(connection.getresponse().read())
            print "Photo Uploaded!"
        except:
            connection.close()
            connection = httplib.HTTPSConnection('api.parse.com', 443)
            connection.connect()
            print "Error Uploading."
        pubnub.publish(channel, imgFile)
        lock.release()
    else:   # Not a person
        print "False"
    os.remove(imgFile)
    sys.exit(0) 

try:
    pubnub.subscribe(channels=subchannel, callback=_kill, error=_error) ## Change to callback
   
    while True:
        previous_state = current_state
        current_state = GPIO.input(sensor)
        if current_state != previous_state:
            new_state = "HIGH" if current_state else "LOW"
            if current_state:     # Motion is Detected
                lock.acquire()
                cam.start_preview() # Comment in future
                cam.preview_fullscreen = False
                cam.preview_window = (10,10, 320,240)
                print('Motion Detected')
                
                for i in range(imgCount):
                    curTime = (time.strftime("%I:%M:%S")) + ".jpg"
Пример #28
0
from Pubnub import Pubnub

## Initiat Class
pubnub = Pubnub( 'demo', 'demo', None, False )

## Subscribe Example
def receive(message) :
    print(message)
    return True

print("Listening for messages...")
pubnub.subscribe({
    'channel'  : 'hello_world',
    'callback' : receive 
})


Пример #29
0
test(history[0].encode('utf-8') == crazy, 'History Message: ' + history[0])
test(len(history) == 1, 'History Message Count')

## -----------------------------------------------------------------------
## PubNub Server Time Example
## -----------------------------------------------------------------------
timestamp = pubnub.time()
test(timestamp > 0, 'PubNub Server Time: ' + str(timestamp))

## -----------------------------------------------------------------------
## Channel Analytics Example
## -----------------------------------------------------------------------
analytics = pubnub.analytics({
    'channel': 'channel-name-here',  ## Leave blank for all channels
    'limit': 100,  ## aggregation range
    'ago': 0,  ## minutes ago to look backward
    'duratoin': 100  ## minutes offset
})
test(analytics.has_key('results'), 'PubNub Channel Analytics')


## -----------------------------------------------------------------------
## Subscribe Example
## -----------------------------------------------------------------------
def receive(message):
    print(message)
    return True


pubnub.subscribe({'channel': crazy, 'callback': receive})
Пример #30
0
    try:
        get_state()
        print datetime.datetime.now(), 'publish', node_state[node_type]
        pubnub.publish(node_type, node_state[node_type])
        select_active()
    except:
        print "unknown error"

    next_call = next_call + 10
    threading.Timer(next_call - time.time(), state_publish).start()


## -----------------------------------------------------------------------
## Initiate Pubnub State
## -----------------------------------------------------------------------
publish_key = config["pubnub_auth"]["publish_key"]
subscribe_key = config["pubnub_auth"]["subscribe_key"]
secret_key = config["pubnub_auth"]["secret_key"]
cipher_key = config["pubnub_auth"]["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)

pubnub.subscribe(node_type_other, callback=callback, error=error)

next_call = (int(time.time() / 10)) * 10 + 5
state_publish()
Пример #31
0
loopcount = 0

pubnub = Pubnub(publish_key='pub-c-9710b97d-1b82-4e19-8508-ef27b1bf9fde', subscribe_key='sub-c-18528260-3ca5-11e8-a433-9e6b275e7b64')
channel = 'Rangefinder'

GPIO.setmode(GPIO.BCM)
TRIG = 20
ECHO = 26

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

GPIO.output(TRIG,False)
time.sleep(2)

pubnub.subscribe(channel, callback=callback, error=callback)
def callback(m, channel):
        if m['getDistance'] == 'on'
	while True:
                GPIO.output(TRIG,True)
                time.sleep(0.00001)
                GPIO.output(TRIG,False)
	pulse_start = time.time()
	while GPIO.input(ECHO)==0:
		pulse_start = time.time()
	while GPIO.input(ECHO)==1:
		pulse_end = time.time()
	pulse_duration = pulse_end - pulse_start
	distance = round(distance, 2)
	loopcount=+=1
	message =  {"Distance": distance}
Пример #32
0

def message_received(message):
    message["withdrawListSize"] = len(message["withdrawList"])
    message["totalCredit"] = message["credit"] + message["cash"]
    if message["userName"].isalpha() == False:
        message["userName"] = make_english_name(message["userName"])

    print(message)
    print_receipt_on(printer, message)


def connected():
    print("Connected")


## -----------------------------------------------------------------------
## Main
## -----------------------------------------------------------------------
pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on)

pubnub.subscribe({"channel": channel_name, "connect": connected, "callback": message_received})

## -----------------------------------------------------------------------
## IO Event Loop
## -----------------------------------------------------------------------
try:
    pubnub.start()
except:
    pass
Пример #33
0

## -----------------------------------------------------------------------
## function about pubnub
## -----------------------------------------------------------------------
# Asynchronous usage
def callback(message, channel):
    print datetime.datetime.now(), 'receive', message


def error(message):
    print("ERROR : " + str(message))


## -----------------------------------------------------------------------
## Initiate Pubnub State
## -----------------------------------------------------------------------
publish_key = config["pubnub_auth"]["publish_key"]
subscribe_key = config["pubnub_auth"]["subscribe_key"]
secret_key = config["pubnub_auth"]["secret_key"]
cipher_key = config["pubnub_auth"]["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)

pubnub.subscribe("blockchain_list_blocks", callback=callback, error=error)
pubnub.subscribe("blockchain_list_delegate", callback=callback, error=error)
Пример #34
0
    try:
        result = json.loads(connection.getresponse().read())
        print result
    except:
        print "Error Uploading."
    pubnub.publish(channel,curTime)
    os.remove(curTime)


def _error(m):
        print(m)

# def is_person(image):
#     det = Detector(image)
#     return len(det.face()) or len(det.upper_body()) or len(det.pedestrian())

try:
    cam.start_preview()
    cam.preview_fullscreen = False
    cam.preview_window = (10,10, 320,240)

    pubnub.subscribe(channels=channel2, callback=_callback, error=_error)
    # Listening for messages on the channel
    while True:
        time.sleep(10)

    

except KeyboardInterrupt:
  cam.stop_preview()
  sys.exit(0)
Пример #35
0
import threading
from Pubnub import Pubnub
from gntp import notifier
from datetime import datetime
from pnsettings import publish_key as p, subscribe_key as s

channel = 'notify'

pubnub = Pubnub(publish_key=p, subscribe_key=s)

def receive_message(data, channel):
  ts = datetime.fromtimestamp(float(data['timestamp']))
  notifier.mini(ts.strftime('%H:%M:%S: ' + data['message']))


pubnub.subscribe(channel, callback=receive_message)

import signal, sys

def kill_all_threads():
    for thread in threading.enumerate():
        if thread.isAlive():
            thread._Thread__stop()

def cleanup(signal=None, frame=None):
    print "\nCleaning up."
    kill_all_threads()
    sys.exit(0)

signal.signal(signal.SIGINT, cleanup)
Пример #36
0
            trips['avg'] = (trips['avg'] + trips[last_trip]) / 2

    ## Increment Trip Counter
    trips[current_trip] = trips[current_trip] + 1

    ## Update Max
    if trips[current_trip] > trips['max']:
        trips['max'] = trips[current_trip]

    print(message)

    pubnub.publish({
        'channel':
        crazy,
        'message':
        current_trip + " Trip: " + str(trips[current_trip]) + " MAX: " +
        str(trips['max']) + "/sec " + " AVG: " + str(trips['avg']) + "/sec"
    })


pubnub.subscribe({
    'channel': crazy,
    'connect': connected,
    'callback': received
})

## -----------------------------------------------------------------------
## IO Event Loop
## -----------------------------------------------------------------------
pubnub.start()
Пример #37
0
class App():
    
    def readKeys(self):
        myvars = {}
        with open("keys") as myfile:
            for line in myfile:
                name, var = line.partition("=")[::2]
                myvars[name.strip()] = "".join(var.split())


        self.publish_key = myvars["publish_key"]
        self.subscribe_key = myvars["subscribe_key"]
        self.secret_key = myvars["secret_key"]


    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/eke.pid'
        self.channel_sub = 'hello_world'
        self.pidfile_timeout = 5

        self.df = pd.DataFrame(columns = ['temp'])

        self.publish_key = ''
        self.subscribe_key = ''
        self.secret_key = ''
        self.cipher_key = ''
        self.ssl_on = False

        self.readKeys()

        self.pubnub = Pubnub(publish_key=self.publish_key, 
                             subscribe_key=self.subscribe_key,
                             secret_key=self.secret_key, 
                             cipher_key=self.cipher_key, 
                             ssl_on=self.ssl_on)

    def anomaly(self, message):
        logger.info(message)
        pass

    # Asynchronous usage
    def callback(self, message, channel):
        # load stuff into LS or DBScan
        anomalymodel = LS.LSAnomaly(rho=1, sigma=.5)
        try:
            s = message
            logger.info(float(s['temp']))
            self.df.loc[self.df.values.size] = float(s['temp'])

            if self.df.values.size > 10:
                if np.std(self.df['temp'].values) < 1.1:
                    logger.info("std less than 1.1 for this set")

                s = pd.Series(self.df['temp'])
                s = s.reshape(s.shape[0],1)

                anomalymodel.fit(s)
                anomalymodel.predict(s)
                self.df['outcome'] = anomalymodel.predict(s)

                ano = self.df[self.df['outcome'] != 0]

                print ano
                print self.df

                for i in ano.index:
                    print ano.ix[i]

                self.df = pd.DataFrame(columns = ['temp'])

                return

        except TypeError:
            pass

    def error(self, message):
        print("ERROR : " + str(message))


    def connect(self, message):
        print("CONNECTED")


    def reconnect(self, message):
        print("RECONNECTED")


    def disconnect(self, message):
        print("DISCONNECTED")

    def run(self):

        logger.info("Eke server started!")

        
        self.pubnub.subscribe(self.channel_sub, 
                              callback=self.callback, 
                              error=self.callback,
                              connect=self.connect, 
                              reconnect=self.reconnect, 
                              disconnect=self.disconnect
                              )
Пример #38
0
                glow = False
                respstring = 'off'
            else:
                glow = True
                respstring = 'on'

            GPIO.output(16, glow)

            respmsg = {"resp": respstring}
            pubnub.publish(pubnubChannelName, respmsg)


#PubNub Channel Subscribe Callback
def gpioError(msg):
    print 'Error :' + msg


if __name__ == '__main__':

    GPIO.setup(16, GPIO.OUT)

    pubnub.subscribe(pubnubChannelName, gpioCallback, gpioError)

    while True:

        time.sleep(5000)

        if (GPIO.gpio_function(16)):
            #All is over
            break
Пример #39
0
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()
Пример #40
0
        })
    try:
        result = json.loads(connection.getresponse().read())
        print result
    except:
        print "Error Uploading."
    pubnub.publish(channel, curTime)
    os.remove(curTime)


def _error(m):
    print(m)


# def is_person(image):
#     det = Detector(image)
#     return len(det.face()) or len(det.upper_body()) or len(det.pedestrian())

try:
    cam.start_preview()
    cam.preview_fullscreen = False
    cam.preview_window = (10, 10, 320, 240)

    pubnub.subscribe(channels=channel2, callback=_callback, error=_error)
    # Listening for messages on the channel
    while True:
        time.sleep(10)

except KeyboardInterrupt:
    cam.stop_preview()
    sys.exit(0)
Пример #41
0
    trips[current_trip] = trips[current_trip] + 1

    ## Update Max
    if trips[current_trip] > trips["max"]:
        trips["max"] = trips[current_trip]

    print(message)

    pubnub.publish(
        {
            "channel": crazy,
            "message": current_trip
            + " Trip: "
            + str(trips[current_trip])
            + " MAX: "
            + str(trips["max"])
            + "/sec "
            + " AVG: "
            + str(trips["avg"])
            + "/sec",
        }
    )


pubnub.subscribe({"channel": crazy, "connect": connected, "callback": received})

## -----------------------------------------------------------------------
## IO Event Loop
## -----------------------------------------------------------------------
tornado.ioloop.IOLoop.instance().start()
Пример #42
0
# speed 0 - 100
def setSpeed(speed):
    if speed > 100:
        speed = 100
    elif speed < 0:
        speed = 0

    speedByte = MIN_SPEED_BYTE + (FAST_SPEED_BYTE -
                                  MIN_SPEED_BYTE) * speed / 100

    # Forward
    output = speedByte << 2
    output += 0x01

    i2c.write_byte_data(ADDRESS, 0, output)


def subscribeCallback(message, channel):
    print('received, ' + channel + ':' + str(message))

    if channel == CHANNEL_C_CONTROL:
        speed = message['speed']
        setSpeed(speed)


def subscribeError(message):
    print(str(message))


pubnub.subscribe(SUBSCRIBE_CHANNELS, subscribeCallback, subscribeError)
class PubnubChanListenerFactory():
    
    logging.info('PubnubChannelFactory()')

    def __init__(self, 
                 publish_key, 
                 subscribe_key, 
                 secret_key = False, 
                 ssl_on = False,
                 channelName = '',
                 callbackMethod = False
                 ):
        
        self.__publish_key       = publish_key
        self.__subscribe_key     = subscribe_key
        self.__secret_key        = secret_key
        self.__ssl_on            = ssl_on
        self.__channelName       = channelName
        self.__callbackMethod    = callbackMethod if callbackMethod else self.__undefinedCallbackListener
        
        self.__initThreadedListener()
        
        
        '''
        #**
        #* PubnubChannelFactory
        #*
        #* Init PubnubChannelFactory
        #*
        #* @param string publish_key required key to send messages.
        #* @param string subscribe_key required key to receive messages.
        #* @param string secret_key required key to sign messages.
        #* @param boolean ssl_on required for 2048 bit encrypted messages.
        #* @param string origin PUBNUB Server Origin.
        #**

        ## Initiat Class
        pubnubConn = PubnubChannelFactory( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', Bool, 'CHANNEL-NAME', callbackMethod )

        '''
    
    def __undefinedCallbackListener(self, message):
        logging.warn('message received, but NO CALLBACK DEFINED',  message)
    
    
    def __initThreadedListener(self):
        logging.info('__initThreadedListener')
        
        # call BLOCKING subscribe method in a separate thread
        args = {'channel': self.__channelName, 
                'callback': self.__receiveComm,
                'publish_key': self.__publish_key,
                'subscribe_key': self.__subscribe_key,
                'secret_key': self.__secret_key,
                'ssl_on': self.__ssl_on
                }
        # Channel listening is BLOCKING so we are instantiating in another thread
        self.t = background_thread.BackgroundThread(target=self.__doSubscribe, kwargs=args)
        self.t.daemon = True
        self.t.start()
        
        # Type 2
#         self.tid = background_thread.start_new_background_thread(target=self.__doSubscribe, kwargs=args)
        
    def __doSubscribe(self, **kwargs):
        self.pubnubConnecor = Pubnub(kwargs['publish_key'], 
                                     kwargs['subscribe_key'], 
                                     kwargs['secret_key'], 
                                     kwargs['ssl_on']
                                     )
        
        if len( kwargs['channel'] ) > 0:
            logging.info('subscribing to channel ({})'.format(kwargs['channel']))
        
            self.pubnubConnecor.subscribe({
                'channel'  : kwargs['channel'],
                'callback' : kwargs['callback']
                })
            
        else:
            logging.info('no channel defined, listening will not begin until one is assigned via switchChannel')
            return False
    
    def switchChannel(self, newChannel):
        self.__channelName = newChannel;
        # kill thread, init new channel
     
    def __receiveComm(self, message):
        self.__callbackMethod(message)
        return True
    
    '''
    The pending BLOCKING request in the pubnub subscribe method
    can keep the thread alive when GAE is trying to shut it down
    so we just reset the callback so the message is not received twice
    '''
    def destroy(self):
        print('destroy', self, 'setting callback to ignored internal method')
        self.__callbackMethod = self.__undefinedCallbackListener
        
        
        
Пример #44
0
from Pubnub import Pubnub

## Initiat Class
pubnub = Pubnub('demo', 'demo', None, False)


## Subscribe Example
def receive(message):
    print(message)
    return True


print("Listening for messages...")
pubnub.subscribe({'channel': 'hello_world', 'callback': receive})
Пример #45
0
class PubnubDataConnection(threading.Thread):
    "A connection to a PubNub data hub running on its own thread."

    def __init__(self, callback, credentials):
        """
        Opens a PubNub connection with a callback and a credentials dict.

        :param callback: A callable to be called with two arguments:
            message_content and channel_name.
        :type callback: A function or object implementing the ``__call__`` method.
        :param credentials: A set of key/value pairs to be passed to PubNub.
        :type credentials: dict
        """

        super(PubnubDataConnection, self).__init__()
        self._stop_event = threading.Event()
        self.callback = callback
        self.credentials = credentials
        self.channel = credentials['channel']

        self.hub = Pubnub(publish_key=credentials.get('publishKey', None),
                          subscribe_key=credentials.get('subscribeKey', None),
                          cipher_key=credentials.get('cipherKey', None),
                          auth_key=credentials.get('authKey', None),
                          secret_key=None,
                          ssl_on=True)

        if PY2 and "daemon" in Pubnub.__init__.func_code.co_varnames:
            self.hub.daemon = True
        elif PY3 and "daemon" in Pubnub.__init__.__code__.co_varnames:
            self.hub.daemon = True

        self.setDaemon(True)

    def run(self):
        """Thread method, called implicitly after starting the thread."""

        self.subscribe(self.channel, self.callback)
        while not self._stop_event.is_set():
            time.sleep(1)

    def stop(self):
        """Mark the connection/thread for being stopped."""

        self._stop_event.set()
        self.unsubscribe(self.channel)

    def subscribe(self, channel_name, callback):
        """
        Subscribes a callable to a channel with the given name.

        :param channel_name: The channel name.
        :type channel_name: string
        :param callback: The callable to be called with two arguments:
            message_content and channel_name.
        :type callback: A function or object implementing the ``__call__`` method.
        """

        self.hub.subscribe(channel_name, callback)

    def unsubscribe(self, channel_name):
        """
        Unsubscribes from a channel with given name.

        :param channel_name: the channel name
        :type channel_name: string
        """

        self.hub.unsubscribe(channel_name)
Пример #46
0
## -----------------------------------------------------------------------
## 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})

## -----------------------------------------------------------------------
## IO Event Loop
## -----------------------------------------------------------------------
tornado.ioloop.IOLoop.instance().start()
Пример #47
0
## -----------------------------------------------------------------------
pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key,
                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on)

channel = 'a'


# Asynchronous usage
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")


pubnub.subscribe(channel, callback=callback, error=callback,
                 connect=connect, reconnect=reconnect, disconnect=disconnect)
				glow = True
				respstring = 'on'

			GPIO.output(16, glow)

			respmsg = {"resp" : respstring }
			pubnub.publish(pubnubChannelName, respmsg)


#PubNub Channel Subscribe Callback
def gpioError(msg):
	print 'Error :' + msg




if __name__ == '__main__':

	GPIO.setup(16, GPIO.OUT)

	pubnub.subscribe(pubnubChannelName, gpioCallback, gpioError)

	while True:

		time.sleep(5000)

		if(GPIO.gpio_function(16)):
			#All is over
			break

Пример #49
0
ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False

## -----------------------------------------------------------------------
## Initiate Pubnub State
## -----------------------------------------------------------------------
pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on )
crazy  = 'hello_world'

## -----------------------------------------------------------------------
## Subscribe Example
## -----------------------------------------------------------------------
def message_received(message):
    print(message)

def connected() :
    pubnub.publish({
        'channel' : crazy,
        'message' : { 'Info' : 'Connected!' }
    })

pubnub.subscribe({
    'channel'  : crazy,
    'connect'  : connected,
    'callback' : message_received
})

## -----------------------------------------------------------------------
## IO Event Loop
## -----------------------------------------------------------------------
reactor.run()
Пример #50
0
pubnub = Pubnub(PUBLISH_KEY, SUBSCRIBE_KEY)
i2c = smbus.SMBus(1)

# speed 0 - 100
def setSpeed(speed):
    if speed > 100:
        speed = 100
    elif speed < 0:
        speed = 0

    speedByte = MIN_SPEED_BYTE + (FAST_SPEED_BYTE - MIN_SPEED_BYTE) * speed / 100

    # Forward
    output = speedByte << 2;
    output += 0x01

    i2c.write_byte_data(ADDRESS, 0, output)

def subscribeCallback(message, channel):
    print('received, ' + channel + ':' + str(message))

    if channel == CHANNEL_C_CONTROL:
        speed = message['speed']
        setSpeed(speed)

def subscribeError(message):
    print(str(message))

pubnub.subscribe(SUBSCRIBE_CHANNELS, subscribeCallback, subscribeError)