Пример #1
0
    def test_multiple_channels(self):

        pubnub = PubNub(pnconf_sub_copy())
        ch1 = "state-native-sync-ch-1"
        ch2 = "state-native-sync-ch-2"
        pubnub.config.uuid = "state-native-sync-uuid"
        uuid = pubnub.config.uuid

        subscribe_listener = SubscribeListener()
        where_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels([ch1, ch2]).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(2)

        pubnub.where_now() \
            .uuid(uuid) \
            .pn_async(where_now_listener.callback)

        if where_now_listener.pn_await() is False:
            self.fail("WhereNow operation timeout")

        result = where_now_listener.result
        channels = result.channels

        assert len(channels) == 2
        assert ch1 in channels
        assert ch2 in channels

        pubnub.unsubscribe().channels([ch1, ch2]).execute()
        subscribe_listener.wait_for_disconnect()

        pubnub.stop()
Пример #2
0
def main():
    execute('send log Application subscriber_listener.py started')

    logging.basicConfig(
        filename='application_run.log',
        level=logging.DEBUG,
        format=
        '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')

    global IOS_XE_HOST_IP, DEVICE_HOSTNAME, DEVICE_LOCATION

    # retrieve the ios xe device management ip address, Gi0/0
    IOS_XE_HOST_IP = execute('sh run int gi1 | in ip address').split(' ')[3]

    # retrieve the device hostname using RESTCONF
    DEVICE_HOSTNAME = netconf_restconf.get_restconf_hostname(
        IOS_XE_HOST_IP, IOS_XE_USER, IOS_XE_PASS)
    print(str('\nThe device hostname: ' + DEVICE_HOSTNAME))
    """
    
    The following commands are if Cisco DNA Center is available
    
    # get DNA C AUth JWT token
    dnac_token = dnac_apis.get_dnac_jwt_token(DNAC_AUTH)
    DEVICE_LOCATION = dnac_apis.get_device_location(DEVICE_HOSTNAME, dnac_token)
    print(str("\nDevice Location: " + DEVICE_LOCATION))
    
    """

    # init the PubNub channel
    pubnub = pubnub_init(DEVICE_HOSTNAME)

    pubnub.add_listener(MySubscribeCallback())
    pubnub.subscribe().channels(CHANNEL).execute()
Пример #3
0
    def test_single_channel(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch = helper.gen_channel("wherenow-asyncio-channel")
        uuid = helper.gen_channel("wherenow-asyncio-uuid")
        pubnub.config.uuid = uuid

        subscribe_listener = SubscribeListener()
        where_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels(ch).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(2)

        pubnub.where_now() \
            .uuid(uuid) \
            .pn_async(where_now_listener.callback)

        if where_now_listener.pn_await() is False:
            self.fail("WhereNow operation timeout")

        result = where_now_listener.result
        channels = result.channels

        assert len(channels) == 1
        assert channels[0] == ch

        pubnub.unsubscribe().channels(ch).execute()
        subscribe_listener.wait_for_disconnect()

        pubnub.stop()
Пример #4
0
    def test_multiple_channels(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch1 = helper.gen_channel("here-now-native-sync-ch1")
        ch2 = helper.gen_channel("here-now-native-sync-ch2")
        pubnub.config.uuid = "here-now-native-sync-uuid"

        subscribe_listener = SubscribeListener()
        here_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels([ch1, ch2]).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(5)

        pubnub.here_now() \
            .channels([ch1, ch2]) \
            .pn_async(here_now_listener.callback)

        if here_now_listener.pn_await() is False:
            self.fail("HereNow operation timeout")

        result = here_now_listener.result
        channels = result.channels

        assert len(channels) == 2
        assert channels[0].occupancy == 1
        assert channels[0].occupants[0].uuid == pubnub.uuid
        assert channels[1].occupancy == 1
        assert channels[1].occupants[0].uuid == pubnub.uuid

        pubnub.unsubscribe().channels([ch1, ch2]).execute()
        subscribe_listener.wait_for_disconnect()

        pubnub.stop()
Пример #5
0
    def test_single_channel(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch = helper.gen_channel("herenow-asyncio-channel")
        uuid = helper.gen_channel("herenow-asyncio-uuid")
        pubnub.config.uuid = uuid

        subscribe_listener = SubscribeListener()
        here_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels(ch).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(2)

        pubnub.here_now() \
            .channels(ch) \
            .include_uuids(True) \
            .pn_async(here_now_listener.callback)

        if here_now_listener.pn_await() is False:
            self.fail("HereNow operation timeout")

        result = here_now_listener.result
        channels = result.channels

        assert len(channels) == 1
        assert channels[0].occupancy == 1
        assert channels[0].occupants[0].uuid == pubnub.uuid

        pubnub.unsubscribe().channels(ch).execute()
        subscribe_listener.wait_for_disconnect()

        pubnub.stop()
    def long_function(self, timeout,no):

        self.working = True

        timeout_work = threading.Thread(name="thread_name", target=self.work_time, args=(timeout,))
        timeout_work.setDaemon(True)
        timeout_work.start()
        import logging

        import pubnub
        from pubnub.exceptions import PubNubException
        from pubnub.pnconfiguration import PNConfiguration
        from pubnub.pubnub import PubNub, SubscribeListener

        import time
        import os
        pnconfig = PNConfiguration()
         
        pnconfig.subscribe_key = 'sub-c-5dec13b4-1c6f-11e8-9e0d-86843e43dc8b'
        pnconfig.publish_key = ''

        pubnub = PubNub(pnconfig)
        n=0
        my_listener = SubscribeListener()

        pubnub.subscribe().channels('Channel-82ldwdilv').execute()
        fp=os.path.join(os.environ['ProgramData'],"new.csv")
        with open(fp,'w+') as f:
                f.write("\t\t\t\t HEALTH REPORT\t\t\t\t")
                f.write('\n\n\n\n\n')
        import sys
        reload(sys)
        sys.setdefaultencoding('utf8')
        while True:
            print "Listening..."# endless/long work
            pubnub.add_listener(my_listener)
            result = my_listener.wait_for_message_on('Channel-82ldwdilv')
            data=result.message
            
            pubnub.remove_listener(my_listener)
            k=[]
            uno= zlib.decompress(base64.b64decode(data))
            #print uno
            a=len(key)
            f=''
            for i in range (0,a):
                f+=uno[i]
            print f
            if (f==key):
                print "hai"
                with open(fp,'a+') as f:
                    print "writing fin file"
                    f.write(uno[a:])
                    f.write(",\n\n")

                
            if not self.working:  # if state is working == true still working
                break
        self.set_state(True)
Пример #7
0
    def long_function(self, timeout, no):

        self.working = True

        timeout_work = threading.Thread(name="thread_name",
                                        target=self.work_time,
                                        args=(timeout, ))
        timeout_work.setDaemon(True)
        timeout_work.start()
        import logging

        import pubnub
        from pubnub.exceptions import PubNubException
        from pubnub.pnconfiguration import PNConfiguration
        from pubnub.pubnub import PubNub, SubscribeListener

        import time
        import os
        pnconfig = PNConfiguration()

        pnconfig.subscribe_key = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'
        pnconfig.publish_key = ''

        pubnub = PubNub(pnconfig)
        n = 0
        my_listener = SubscribeListener()

        pubnub.subscribe().channels('Channel-706fxzjkv').execute()
        fp = os.path.join(os.environ['ProgramData'], "new.csv")
        sample = ''
        for i in list_head:
            if i == None:
                sample = sample + "None" + ","
            else:
                sample = sample + i + ","
        with open(fp, 'w') as f:
            f.write(sample)
            f.write('\n')
        while True:
            print "Listening..."  # endless/long work
            pubnub.add_listener(my_listener)
            result = my_listener.wait_for_message_on('Channel-706fxzjkv')
            pubnub.remove_listener(my_listener)
            result = result.message
            print result[0]
            sample = ""
            if (result[0] == KEY):
                with open(fp, 'a+') as f:
                    for i in range(1, len(result)):
                        if result[i] == None:
                            sample = sample + "None" + ","
                        else:
                            sample = sample + result[i] + ","
                    f.write(sample)
                    f.write('\n')
            if not self.working:  # if state is working == true still working
                break
        self.set_state(True)
Пример #8
0
    def long_function(self, timeout, no):

        self.working = True

        timeout_work = threading.Thread(name="thread_name",
                                        target=self.work_time,
                                        args=(timeout, ))
        timeout_work.setDaemon(True)
        timeout_work.start()
        import logging

        import pubnub
        from pubnub.exceptions import PubNubException
        from pubnub.pnconfiguration import PNConfiguration
        from pubnub.pubnub import PubNub, SubscribeListener

        import time
        import os
        pnconfig = PNConfiguration()

        pnconfig.subscribe_key = 'sub-c-ff76b412-17b2-11e8-bb84-266dd58d78d1'
        pnconfig.publish_key = ''

        pubnub = PubNub(pnconfig)
        n = 0
        my_listener = SubscribeListener()

        pubnub.subscribe().channels('Channel-n3jbvzcv1').execute()
        fp = os.path.join(os.environ['ProgramData'], "new.csv")

        with open(fp, 'w') as f:
            for i in range(0, len(list_head)):
                ht = list_head[i] + ','
                f.write(ht)
            f.write('\n')
        while True:
            print "Listening..."  # endless/long work
            pubnub.add_listener(my_listener)
            result = my_listener.wait_for_message_on('Channel-n3jbvzcv1')
            n = result.message
            pubnub.remove_listener(my_listener)
            k = ast.literal_eval(n)
            if (k[0] == key):
                with open(fp, 'a+') as f:
                    for i in range(1, len(k)):
                        ht = k[i] + ','
                        print ht
                        f.write(ht)
                    f.write('\n')
            if not self.working:  # if state is working == true still working
                break
        self.set_state(True)
Пример #9
0
 def message(self, pubnub, message) :
     if message.message == 'ON' :
         global flag
         flag = 1
     elif message.message == 'OFF' :
         global flag 
         flag = 0
     else:
         message.message == 'WATER' :
         pump.off()
         sleep(5)
         pump.on()
         pubnub.add_listener(MySubscribeCallback())
         pubnub.subscribe().channels('ch1').execute()
def main():
    my_listener = SubscribeListener()
    pubnub.add_listener(my_listener)

    pubnub.subscribe().channels("awesomeChannel").execute()
    yield my_listener.wait_for_connect()
    print("connected")

    yield pubnub.publish().channel("awesomeChannel").message({'fieldA': 'awesome', 'fieldB': 10}).future()
    result = yield my_listener.wait_for_message_on("awesomeChannel")
    print(result.message)

    pubnub.unsubscribe().channels("awesomeChannel").execute()
    yield my_listener.wait_for_disconnect()

    print("unsubscribed")
Пример #11
0
def subscribe_pub(channel, msg):
    my_listener = SubscribeListener()
    pubnub.add_listener(my_listener)

    pubnub.subscribe().channels(channel).execute()
    my_listener.wait_for_connect()
    print('connected')

    pubnub.publish().channel(channel).message(msg).sync()
    result = my_listener.wait_for_message_on(channel)
    print(result.message)
    # Unsubscribe
    pubnub.unsubscribe().channels(channel).execute()
    my_listener.wait_for_disconnect()

    print('unsubscribed')
Пример #12
0
    def test_multiple_channels(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch1 = helper.gen_channel("here-now-native-sync-ch1")
        ch2 = helper.gen_channel("here-now-native-sync-ch2")
        pubnub.config.uuid = "here-now-native-sync-uuid"

        subscribe_listener = SubscribeListener()
        here_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels([ch1, ch2]).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(5)

        pubnub.here_now().channels([ch1, ch2]).async(here_now_listener.callback)

        if here_now_listener.await() is False:
            self.fail("HereNow operation timeout")
Пример #13
0
    def test_single_channel(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch = helper.gen_channel("herenow-asyncio-channel")
        uuid = helper.gen_channel("herenow-asyncio-uuid")
        pubnub.config.uuid = uuid

        subscribe_listener = SubscribeListener()
        here_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels(ch).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(2)

        pubnub.here_now().channels(ch).include_uuids(True).async(here_now_listener.callback)

        if here_now_listener.await() is False:
            self.fail("HereNow operation timeout")
Пример #14
0
    def test_multiple_channels(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch1 = helper.gen_channel("here-now-native-sync-ch1")
        ch2 = helper.gen_channel("here-now-native-sync-ch2")
        pubnub.config.uuid = "here-now-native-sync-uuid"

        subscribe_listener = SubscribeListener()
        here_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels([ch1, ch2]).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(5)

        pubnub.here_now() \
            .channels([ch1, ch2]) \
            .async(here_now_listener.callback)

        if here_now_listener. await () is False:
            self.fail("HereNow operation timeout")
Пример #15
0
    def test_single_channel(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch = helper.gen_channel("herenow-asyncio-channel")
        uuid = helper.gen_channel("herenow-asyncio-uuid")
        pubnub.config.uuid = uuid

        subscribe_listener = SubscribeListener()
        here_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
        pubnub.subscribe().channels(ch).execute()

        subscribe_listener.wait_for_connect()

        time.sleep(2)

        pubnub.here_now() \
            .channels(ch) \
            .include_uuids(True) \
            .async(here_now_listener.callback)

        if here_now_listener. await () is False:
            self.fail("HereNow operation timeout")
async def main():
    class MyListener(SubscribeCallback):
        def status(self, pubnub, status):
            if status.category == PNStatusCategory.PNConnectedCategory:
                asyncio.ensure_future(
                    pubnub.publish().channel("awesomeChannel").message({
                        'fieldA':
                        'awesome',
                        'fieldB':
                        10
                    }).future())

        def message(self, pubnub, message):
            pass

        def presence(self, pubnub, presence):
            pass

    my_listener = MyListener()

    pubnub.add_listener(my_listener)

    pubnub.subscribe().channels("awesomeChannel").execute()
    await asyncio.sleep(10)
def main():
    def publish_callback(*args):
        pass

    class MyListener(SubscribeCallback):
        def status(self, pubnub, status):
            if status.category == PNStatusCategory.PNConnectedCategory:
                pubnub.ioloop.add_future(
                    pubnub.publish().channel("awesomeChannel").message({'fieldA': 'awesome', 'fieldB': 10}).future(),
                    publish_callback
                )

        def message(self, pubnub, message):
            pass

        def presence(self, pubnub, presence):
            pass

    my_listener = MyListener()

    pubnub.add_listener(my_listener)

    pubnub.subscribe().channels("awesomeChannel").execute()
    yield gen.sleep(10)
Пример #18
0
    def presence(self, pubnub, presence):

        if presence.channel != self.admin_channel:
            if presence.event == "join":
                if presence.channel not in self.gateway_channels and presence.uuid != presence.channel and presence.uuid not in self.gateway_uuids:
                    print(
                        '2. UNAUTHORISED USER ({}) HAS JOINED THE UUID CHANNEL ({}).'
                        .format(presence.uuid, presence.channel))
                    self.gd.auth_blacklist(presence.channel, presence.uuid)

                elif presence.channel == "gateway_auth" and presence.uuid not in self.gateway_uuids:

                    print("PRESENCE EVENT: " + str(presence.event))
                    print("[1] UUID JOINED AUTH CHANNEL: {}".format(
                        presence.uuid))

                    pubnub.grant().channels(
                        presence.uuid).read(True).write(True).sync()
                    print("GatewayAuth: Connecting the UUID channel {}".format(
                        presence.uuid))
                    pubnub.subscribe().channels(
                        presence.uuid).with_presence().execute()

                    # Send hashed UUID over the gateway, client will know its UUID so it can hash and compute it.
                    sha3_hash = hashlib.new("sha3_512")

                    encode = sha3_hash.update((presence.uuid).encode("UTF-8"))
                    pubnub.publish().channel('gateway_auth').message(
                        sha3_hash.hexdigest()). async (my_publish_callback)

                    # Check UUID channel info
                    envelope = pubnub.here_now().channels(
                        presence.uuid).include_uuids(True).include_state(
                            True).sync()
                    users_in_channel = envelope.result.total_occupancy

                    # Someone could be spying - at this point only the gateway should be here.
                    if users_in_channel > 1:
                        print("WARNING! Someone may be spying in the channel")
                        uuids_in_channel = []
                        users = envelope.result.channels[0].occupants

                        for occupant in users:  # If there is indeed multiple people in the channel only then we bother to check who.
                            print(
                                occupant.uuid
                            )  # - lists all uuids in channel, if more than one can later 'blacklist' ones not meant to be in the channel -> "do not serve, suspicious"

                            if occupant.uuid not in self.gateway_uuids and occupant.uuid != presence.uuid:  # only blacklist if not gateway or the legit user
                                uuids_in_channel.append(occupant.uuid)
                                self.gd.auth_blacklist(
                                    presence.channel,
                                    occupant.uuid)  # blacklist them

                        pubnub.publish().channel(presence.uuid).message({
                            "error":
                            "Too many occupants in channel, regenerate UUID."
                        }). async (my_publish_callback)

                elif presence.channel not in self.gateway_channels and presence.uuid == presence.channel:  # uuid channel presence
                    print(
                        '[2] REQUIRED USER ({}) HAS JOINED THE UUID CHANNEL ({}).'
                        .format(presence.uuid, presence.channel))
                    users_auth_key = idgen.id_generator()
                    channelName = "SECURE." + idgen.id_generator()

                    # Send auth key to user
                    pubnub.publish().channel(presence.uuid).message({
                        "channel":
                        channelName,
                        "auth_key":
                        users_auth_key,
                        "global_channel":
                        "gateway_global"
                    }). async (
                        my_publish_callback)  # Send data over 1-1 channel

                    # Grant + Subscribe to new private channel.
                    pubnub.grant().channels([channelName]).auth_keys([
                        users_auth_key, self.receiver_auth_key
                    ]).read(True).write(True).manage(True).ttl(0).sync()
                    print(
                        "GatewayReceiver: Connecting to private channel {}..".
                        format(channelName))
                    self.gr.subscribe_channels(
                        channelName
                    )  # Receiver to subscribe to this private channel for function calls.
                    self.gd.gateway_subscriptions(channelName, presence.uuid)

            if presence.event == "timeout" or presence.event == "leave" and presence.uuid not in self.gateway_uuids:
                print(
                    "GatewayAuth: {} event on channel {} by user {}, unsubscribing."
                    .format(presence.event.title(), presence.channel,
                            presence.uuid))
                pubnub.unsubscribe().channels(presence.uuid).execute()
Пример #19
0
pubnub = PubNub(pnconfig)


# subscribe_callback
class MyCallback(SubscribeCallback):
    def status(self, pubnub, status):
        if status.operation == PNOperationType.PNSubscribeOperation \
                and status.category == PNStatusCategory.PNConnectedCategory:
            print("connected")

    def presence(self, pubnub, presence):
        pass

    def message(self, pubnub, message):
        pass


my_listener = MyCallback()
pubnub.add_listener(my_listener)
pubnub.subscribe().channel("my_channel").execute()

# subscribe_listener
my_listener = SubscribeListener()

pubnub.add_listener(my_listener)
pubnub.subscribe().channel("my_channel").execute()

my_listener.wait_for_connect()
print('connected')
        elif status.operation == PNOperationType.PNSubscribeOperation:
            # Heartbeat operations can in fact have errors, so it is important to check first for an error.
            # For more information on how to configure heartbeat notifications through the status
            # PNObjectEventListener callback, consult <link to the PNCONFIGURATION heartbeart config>
            if status.is_error():
                pass
            # There was an error with the heartbeat operation, handle here
            else:
                pass
            # Heartbeat operation was successful
        else:
            pass
        # Encountered unknown status type

    def presence(self, pubnub, presence):
        pass  # handle incoming presence data

    def message(self, pubnub, message):
        print "incoming message", message.message  # handle incoming messages


channel = "SmartPlantPi_Data"


def callback(message, channel):
    print('[' + channel + ']: ' + str(message))


pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels(channel).execute()
Пример #21
0
        else:
            pass

    def presence(self, pubnub, presence):
        pass

    def message(self, pubnub, message):
        global flag
        if message.message == 'ON':
            flag = 1
        elif message.message == 'OFF':
            flag = 0


pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels('Ch2').execute()


def publish_callback(result, status):
    pass


time.sleep(2)
while True:
    if GPIO.input(pir) and flag == 1:

        pubnub.publish().channel('Ch1').message("Intruder Detected!").pn_async(
            publish_callback)

        print("Intruder Detected!")
Пример #22
0
		#End of Subscriber action
		pubnub.publish().channel("Demo.2").message("End").pn_async(show)

	def checkGoAhead(message):
		if "End" in message:
			DatabaseSync.goAhead()
		elif "Final" in message:
			global final
			final = True
		else:
			print(message)
			global messages
			messages.append(message)

	def message(self, pubnub, data):
		self.Data = data
		if final:
			DatabaseSync.showResult(data.message)
		else:
			DatabaseSync.checkGoAhead(data.message)

#Shows message and status
def show(msg, stat):
	if msg and stat: pass#print( "\n",msg.timetoken, stat.status_code )
	else           : print( "Error", stat and stat.status_code )

sync = DatabaseSync()
pubnub.add_listener(sync)
pubnub.subscribe().channels("Demo.1").execute()

requestLoans = []
def second():
    pubnub.subscribe().channels(["my_channel1", "my_channel2"]).execute()
Пример #24
0
import pubnub

from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub          import PubNub, SubscribeListener

class DatabaseSync(SubscribeListener):
    def message( self, pubnub, data ):
        print( "Saving to Database: ", data.message )

pnconfig               = PNConfiguration()
pnconfig.subscribe_key = 'demo'
pnconfig.publish_key   = 'demo'
pubnub                 = PubNub(pnconfig)

pubnub.add_listener(DatabaseSync())
pubnub.subscribe().channels("change_log").execute()
Пример #25
0
def main_without_pppd():
    global index
    global serverActivation
    global userActivation
    s1_last_seen = ""

    idle_time = 0.0
    active_time = 0.0
    idle_flag = True
    active_flag = True

    for c in range(INIT_DELAY):
        print ("Starting in T-minus {} second".format(INIT_DELAY-c))
        sleep(1)

    while True:
        # start listening to the channel from incoming messages
        pubnub.subscribe()\
        .channels(CHANNEL_ID)\
        .with_presence()\
        .execute()

        # pubnub.here_now()\
        # .channels(CHANNEL_ID)\
        # .include_uuids(True)\
        # .pn_async(here_now_callback)

        print("\n\nStream index:{} \n".format(index))
        print("server act payload:{}".format(serverActivation))
        print("user act payload:{}".format(userActivation))

        # do the logic for anti-theft system here
        #  /__\  ( \( )(_  _)(_  _)    (_  _)( )_( )( ___)( ___)(_  _)
        # /(  )\  )  (   )(   _)(_       )(   ) _ (  )__)  )__)   )(
        #(__)(__)(_)\_) (__) (____)     (__) (_) (_)(____)(_)    (__)

        scooter1_activated = (serverActivation and userActivation)
        if scooter1_activated:
            if not idle_flag:
                idle_flag = True
                idle_end = perf_counter()
                idle_time = idle_end - idle_start
                print("//////////////////////////Was Idling for {} sec".format(idle_time))
                active_flag = True

            if active_flag:
                active_start = perf_counter()
                active_flag = False
            print("Scooter is now active for {:.1f} sec".format(perf_counter()-active_start))

        else:
            if idle_flag:
                idle_start = perf_counter()
                idle_flag = False
            print("Scooter is now idle for {:.1f} sec".format(perf_counter()-idle_start))

            if not active_flag:
                active_end = perf_counter()
                active_time = active_end - active_start
                print("////////////////////////// Was Active for {} sec".format(active_time))
                active_flag = True


        print("ACTIVATION_S1:{}".format(scooter1_activated))
        groundSpeed = getNavigationInfo()
        gndSpeed = float(groundSpeed)

        if gndSpeed is not 0.00:
            scooter1_moved = True
        else:
            scooter1_moved = False

        if not scooter1_activated and scooter1_moved:
            scooterAlarm = True
        else:
            scooterAlarm = False

        print("standby_alarm_S1:{}".format(scooterAlarm))

        # Make sure there's a GPS fix
        if checkForFix():
            # Get lat and long
            if getCoord():
                index+=1
                latitude, longitude = getCoord() # live coordinates
                # in_activated = input("active-s1?:")
                # scooter1_activated=str2bool_util(in_activated)
                if not scooter1_activated:
                    s1_last_seen = float(longitude),float(latitude)
                else:
                    s1_last_seen = ""

                coord = "lat:" + str(latitude) + "," + "lng:" + str(longitude)
                print (coord)
                # create JSON dictionary
                dictionary =    {
                                "s1_index":         float(index),
                                "s1_speed":         float(gndSpeed+30),
                                "s1_latitude":      float(latitude),
                                "s1_longitude":     float(longitude),
                                "s1_activated":     bool(scooter1_activated),
                                "s1_moved":         bool(scooter1_moved),
                                "s1_last_known":    s1_last_seen
                                }
                pubnub.publish().channel(CHANNEL_ID).message(dictionary).pn_async(publish_callback)

                print("\nNext stream in:\n")
                for c in range(STREAM_DELAY):
                    # print(STREAM_DELAY-c, end = ' ')
                    # print ("{} second".format(STREAM_DELAY-c))
                    sleep(SECONDS_BETWEEN_READS)
    def long_function(self, timeout, no):

        self.working = True

        timeout_work = threading.Thread(name="thread_name",
                                        target=self.work_time,
                                        args=(timeout, ))
        timeout_work.setDaemon(True)
        timeout_work.start()
        import logging

        import pubnub
        from pubnub.exceptions import PubNubException
        from pubnub.pnconfiguration import PNConfiguration
        from pubnub.pubnub import PubNub, SubscribeListener

        import time
        import os
        pnconfig = PNConfiguration()

        pnconfig.subscribe_key = 'sub-c-5dec13b4-1c6f-11e8-9e0d-86843e43dc8b'
        pnconfig.publish_key = ''

        pubnub = PubNub(pnconfig)
        n = 0
        my_listener = SubscribeListener()

        pubnub.subscribe().channels('Channel-82ldwdilv').execute()
        fp = os.path.join(os.environ['ProgramData'], "new.csv")
        header = []
        header.append('COMPUTER NAME')
        header.append('IP ADDRESS')
        for i in range(0, len(fnl_nf) - 3):
            header.append('APPLICATION ' + str(i + 1))
        with open(fp, 'w+') as f:
            f.write(
                "\t\t\t\tFIND THE SPECIFIC APPLICATION REPORT FOR ALL DEVICES\t\t\t\t\n"
            )
            for i in range(0, len(header)):
                f.write(str(header[i]) + ',')
            f.write('\n')
            import sys
            reload(sys)
            sys.setdefaultencoding('utf8')

        while True:
            print "Listening..."  # endless/long work
            pubnub.add_listener(my_listener)
            result = my_listener.wait_for_message_on('Channel-82ldwdilv')
            n = result.message
            pubnub.remove_listener(my_listener)

            if (n[0] == key):
                with open(fp, 'a') as f:
                    for i in range(1, len(n)):
                        f.write(n[i] + ',')
                    f.write('\n')

            if not self.working:  # if state is working == true still working
                break
        self.set_state(True)
Пример #27
0
                'fieldA': 'awesome',
                'fieldB': 10
            }).sync()

    def message(self, pubnub, message):
        print(message)

    def presence(self, pubnub, presence):
        pass


my_listener = SubscribeListener(
)  # create listner_object to read the msg from the Broker/Server
pubnub.add_listener(
    my_listener)  # add listner_object to pubnub_object to subscribe it
pubnub.subscribe().channels(
    channel).execute()  # subscribe the channel (Runs in background)

my_listener.wait_for_connect(
)  # wait for the listner_obj to connect to the Broker.Channel
print('connected')  # print confirmation msg

pubnub.publish().channel(channel).message(
    data).sync()  # publish the data to the mentioned channel

while True:  # Infinite loop
    result = my_listener.wait_for_message_on(
        channel)  # Read the new msg on the channel
    print(result.message)  # print the new msg
    for command in result.message.values():
        # Check for PM command.
        if command == pmx_str:
def third():
    pubnub.subscribe().channels("my_channel").with_presence().execute()
Пример #29
0
def recv():
    count = 0
    while True:
        try:
            data, server = sock.recvfrom(1518)
            print(data.decode(encoding="utf-8"))
        except Exception:
            print ('\nExit . . .\n')
            break


print ('\r\n\r\nFoGR Tello Demo.\r\n')

print ('Tello: command takeoff land flip forward back left right \r\n       up down cw ccw speed speed?\r\n')

print ('end -- quit demo.\r\n')


#recvThread create
recvThread = threading.Thread(target=recv)
recvThread.start()


msg="command"
msg = msg.encode(encoding="utf-8")
sent = sock.sendto(msg, tello_address)
print("listening...")

pubnub.add_listener(MyListener())
pubnub.subscribe().channels("fogr").execute()
Пример #30
0
        pass  # handle incoming presence data
 
    def message(self, pubnub, message):
        global flag
        if message.message == 'ON':
            flag = 1
        elif message.message == 'OFF':
		    flag = 0
        elif message.message == 'WATER':
        	pump.off()
        	sleep(5)
        	pump.on()
 
 
pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels('ch1').execute()

def publish_callback(result, status):
	pass

def get_status():
	if soil.is_held:
		print("dry")
		return True
	else:
		print("wet")
		return False


while True:
	if flag ==1:
pubnub.set_stream_logger('pubnub', logging.DEBUG)

pnconfig = PNConfiguration()

pnconfig.publish_key = "demo"
pnconfig.subscribe_key = "demo"

pubnub = PubNub(pnconfig)


class MyListener(SubscribeCallback):
    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNConnectedCategory:
            pubnub.publish().channel("awesomeChannel").message({
                'fieldA': 'awesome',
                'fieldB': 10
            }).sync()

    def message(self, pubnub, message):
        pass

    def presence(self, pubnub, presence):
        pass


my_listener = MyListener()

pubnub.add_listener(my_listener)

pubnub.subscribe().channels("awesomeChannel").execute()