示例#1
0
    def returnBorrower():
        flag = True
        #Last array any random name ...
        tiredArray = []
        #since its an knapsack object I cant treat it as an normal array
        for i in kArray:
            #Just to print the [0] index, which is the amount yield after loaning
            if flag:
                print(
                    "Broker will yield {} amount after borrower repay".format(
                        i))
                flag = False
            else:
                #Loops through all accepted simple interest amounts, corresponds to 1 request per borrower
                for j in i:
                    #array append in the following format
                    #	[username/borrower, entire loan request object [loan amount, years, interest rate]]
                    tiredArray.append([
                        finalLoanRequest[j][0], borrowerDict[
                            finalLoanRequest[j][0]][finalLoanRequest[j][1]]
                    ])

        #Publish Final event for borrower
        pubnub.publish().channel("Demo.1").message("Final").pn_async(show)
        #Publish array
        time.sleep(1)
        pubnub.publish().channel("Demo.1").message(tiredArray).pn_async(show)
示例#2
0
	def goAhead():
	#iteration = int(input("How many bet request do you want? "))
		#print(messages)
		constraints = messages[-1].split()
		iteration = 3
		for i in range(iteration):
			#for i in messages[-1]:
			#print(i)
			amount = int(input("Enter loan amount: "))
			while( (amount > int(constraints[0])) or (amount < 99)):
				print("Amount invalid")
				amount = int(input("Enter loan amount: "))

			year = int(input("Enter loan repay period in years: "))
			while((year > int(constraints[1])) or (year < 1)):
				print("Repay period in years invalid")
				year = int(input("Enter loan repay period in years: "))

			interestRate = int(input("Enter desired interest rate: "))
			while((interestRate > int(constraints[2])) or (interestRate < 1)):
				print("Interest rate invalid")
				interestRate = int(input("Enter desired interest rate: "))

			print("End of request\n")
			requestLoans.append([pnconfig.uuid,amount,year,interestRate])
			pubnub.publish().channel("Demo.2").message([requestLoans[i][0],requestLoans[i][1],requestLoans[i][2],requestLoans[i][3]]).pn_async(show)
		#End of Subscriber action
		pubnub.publish().channel("Demo.2").message("End").pn_async(show)
示例#3
0
 def message(self, pubnub, message):
     if message.message == 'ON':
     	lamp.on()
     	pubnub.publish().channel('ch1').message("lamp has been turned on").async(publish_callback)
     	sleep(3)
     elif message.message == 'OFF':
     	lamp.off()
     	pubnub.publish().channel('ch1').message("lamp has been turned off").async(publish_callback)
    def test_publish_encrypted_list_get(self):
        pubnub = PubNub(pnconf_enc)

        pubnub.publish() \
            .channel("ch1") \
            .message(["encrypted", "list"]) \
            .pn_async(self.callback)

        self.assert_success()
示例#5
0
    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
            print("GatewayAuth: Unexpectedly disconnected.")
            pubnub.publish().channel('gateway_auth').message({
                "Global_Message":
                "GatewayAuth: Unexpectedly disconnected."
            }). async (my_publish_callback)

        elif status.category == PNStatusCategory.PNConnectedCategory:
            print("GatewayAuth: Connected.")

        elif status.category == PNStatusCategory.PNReconnectedCategory:
            print("GatewayAuth: Reconnected.")
示例#6
0
    def message(self, pubnub, message):
#message handler for Lamp commands
        #Turn the lamp on if client receives the message “ON”
        if message.message == 'ON':
        lamp.on()
              #let your subscriber client know that the lamp has been turned off
        pubnub.publish().channel('ch1').message("lamp has been turned on").async(publish_callback)
        sleep(3)
        #Turn the lamp on if client receives the message “OFF”
        elif message.message == 'OFF':
        lamp.off()
              #let your subscriber client know that the lamp has been turned off
        pubnub.publish().channel('ch1').message("lamp has been turned off").async(publish_callback)
示例#7
0
    def test_encrypted(self):
        ch = "history-native-sync-ch"
        pubnub = PubNub(pnconf_enc_copy())
        pubnub.config.uuid = "history-native-sync-uuid"

        for i in range(COUNT):
            envelope = pubnub.publish().channel(ch).message("hey-%s" %
                                                            i).sync()
            assert isinstance(envelope.result, PNPublishResult)
            assert envelope.result.timetoken > 0

        time.sleep(5)

        envelope = pubnub.history().channel(ch).count(COUNT).sync()

        assert isinstance(envelope.result, PNHistoryResult)
        assert envelope.result.start_timetoken > 0
        assert envelope.result.end_timetoken > 0
        assert len(envelope.result.messages) == 5

        assert envelope.result.messages[0].entry == 'hey-0'
        assert envelope.result.messages[1].entry == 'hey-1'
        assert envelope.result.messages[2].entry == 'hey-2'
        assert envelope.result.messages[3].entry == 'hey-3'
        assert envelope.result.messages[4].entry == 'hey-4'
示例#8
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')
示例#9
0
def publish_nonhead():
    import time
    time.sleep(30)
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    publish_key1 = 'pub-c-7a797a24-388e-411c-b848-9bd170919784'
    subscribe_key1 = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = subscribe_key1
    pnconfig.publish_key = publish_key1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    from pubnub.exceptions import PubNubException
    try:

        envelope = pubnub.publish().channel("Channel-706fxzjkv").message(
            Drive(KEY)).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
    except PubNubException as e:
        print e
示例#10
0
def publish_nonhead():
    import time
    time.sleep(30)
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    k1 = 'pub-c-e4dca0d8-c948-42e9-a080-3a84922d77c4'
    k2 = 'sub-c-ff76b412-17b2-11e8-bb84-266dd58d78d1'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = k2
    pnconfig.publish_key = k1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-n3jbvzcv1").message(
            '%s' % d).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
    except PubNubException as e:
        print e
def publish_nonhead():
    import time
    time.sleep(30)
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    k1 = 'pub-c-529ac86d-f8bc-4094-9196-1fe0652ebc4f'
    k2 = 'sub-c-5dec13b4-1c6f-11e8-9e0d-86843e43dc8b'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = k2
    pnconfig.publish_key = k1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-82ldwdilv").message(
            d).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)
    except PubNubException as e:
        print e
示例#12
0
def publish_callback(channel, msg):

    try:
        envelope = pubnub.publish().channel(channel).message(msg).sync()
        print("Publish TimeToken: %d" % envelope.result.timetoken)
    except PubNubException as e:
        handle_exception(e)
def publish(no):
    import pubnub
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    k1 = 'pub-c-529ac86d-f8bc-4094-9196-1fe0652ebc4f'
    k2 = 'sub-c-5dec13b4-1c6f-11e8-9e0d-86843e43dc8b'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = k2
    pnconfig.publish_key = k1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    s = 3 * no
    print s
    time.sleep(s)

    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-82ldwdilv").message(
            d).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)

        app_process = os.getpid()
        app_process = str(app_process)
        import subprocess
        import ctypes

        class disable_file_system_redirection:
            _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
            _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

            def __enter__(self):
                self.old_value = ctypes.c_long()
                self.success = self._disable(ctypes.byref(self.old_value))

            def __exit__(self, type, value, traceback):
                if self.success:
                    self._revert(self.old_value)

        time.sleep(5)
        reportfolder = os.path.join(os.environ['ProgramData'], "new.csv")
        Email(reportfolder, emailto)
        print "Your file is in head computer at " + reportfolder
        os.remove(reportfolder)

        with disable_file_system_redirection():
            process = subprocess.Popen(['taskkill', '/F', '/PID', app_process],
                                       shell=True,
                                       stdout=subprocess.PIPE)
            result = process.communicate()[0]
            print(result)
    except PubNubException as e:
        print e
 def status(self, pubnub, status):
     if status.category == PNStatusCategory.PNConnectedCategory:
         asyncio.ensure_future(
             pubnub.publish().channel("awesomeChannel").message({
                 'fieldA':
                 'awesome',
                 'fieldB':
                 10
             }).future())
示例#15
0
def publish(no):
    import pubnub
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    k1 = 'pub-c-e4dca0d8-c948-42e9-a080-3a84922d77c4'
    k2 = 'sub-c-ff76b412-17b2-11e8-bb84-266dd58d78d1'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = k2
    pnconfig.publish_key = k1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    s = 3 * no
    print s
    time.sleep(s)

    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-n3jbvzcv1").message(
            '%s' % d).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)

        app_process = os.getpid()
        app_process = str(app_process)
        import subprocess
        import ctypes

        class disable_file_system_redirection:
            _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
            _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

            def __enter__(self):
                self.old_value = ctypes.c_long()
                self.success = self._disable(ctypes.byref(self.old_value))

            def __exit__(self, type, value, traceback):
                if self.success:
                    self._revert(self.old_value)

        time.sleep(5)
        reportfolder = os.path.join(os.environ['ProgramData'], "new.csv")
        print "Your file is in head computer at " + reportfolder

        with disable_file_system_redirection():
            process = subprocess.Popen(['taskkill', '/F', '/PID', app_process],
                                       shell=True,
                                       stdout=subprocess.PIPE)
            result = process.communicate()[0]
            print(result)
    except PubNubException as e:
        print e
示例#16
0
def publish(no):
    import pubnub
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    publish_key1 = 'pub-c-7a797a24-388e-411c-b848-9bd170919784'
    subscribe_key1 = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = subscribe_key1
    pnconfig.publish_key = publish_key1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    s = 3 * no
    time.sleep(s)

    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-706fxzjkv").message(
            Drive(KEY)).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)

        app_process = os.getpid()
        app_process = str(app_process)
        import subprocess
        import ctypes

        class disable_file_system_redirection:
            _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
            _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

            def __enter__(self):
                self.old_value = ctypes.c_long()
                self.success = self._disable(ctypes.byref(self.old_value))

            def __exit__(self, type, value, traceback):
                if self.success:
                    self._revert(self.old_value)

        time.sleep(5)
        reportfolder = os.path.join(os.environ['ProgramData'], "new.csv")
        Email(reportfolder, emailto)
        print "Your file is in head computer at " + reportfolder
        with disable_file_system_redirection():
            process = subprocess.Popen(['taskkill', '/F', '/PID', app_process],
                                       shell=True,
                                       stdout=subprocess.PIPE)
            result = process.communicate()[0]
            print(result)
    except PubNubException as e:
        print e
def main(gps_queue):

    # PunNub Instance

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = "sub-c-5f7c7648-c99c-11e9-ac59-7e2323a85324"
    pnconfig.publish_key = "pub-c-af13eaae-73e7-4c64-a7e8-4ec6c0dc13d1"
    pnconfig.ssl = False
    pubnub = PubNub(pnconfig)

    while (True):
        msg = gps_queue.get()  # Will block until message is recieved

        latitude = msg.data[0]  # data is an array
        longitude = msg.data[1]
        timestamp = msg.data[2]

        if latitude and longitude is not None:
            dictionary = {"latitude": latitude, "longitude": longitude}
            pubnub.publish().channel('blue').message(dictionary).pn_async(
                publish_callback)
def publish(no):
    import pubnub
    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    from pubnub.callbacks import SubscribeCallback

    from pubnub.pnconfiguration import PNConfiguration
    from pubnub.pubnub import PubNub
    publish_key1 = 'pub-c-7a797a24-388e-411c-b848-9bd170919784'
    subscribe_key1 = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d'

    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = subscribe_key1
    pnconfig.publish_key = publish_key1
    pnconfig.ssl = True

    pubnub = PubNub(pnconfig)
    import time
    s = 3 * no
    time.sleep(s)

    from pubnub.exceptions import PubNubException
    try:
        envelope = pubnub.publish().channel("Channel-706fxzjkv").message(
            INSTALLED(KEY)).sync()
        print("publish timetoken: %d" % envelope.result.timetoken)

        app_process = os.getpid()
        app_process = str(app_process)
        import subprocess
        import ctypes

        class disable_file_system_redirection:
            _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
            _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

            def __enter__(self):
                self.old_value = ctypes.c_long()
                self.success = self._disable(ctypes.byref(self.old_value))

            def __exit__(self, type, value, traceback):
                if self.success:
                    self._revert(self.old_value)

        time.sleep(5)
        with disable_file_system_redirection():
            CMD = 'taskkill /F /PID %s' % app_process
            print CMD
            process = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE)
            result = process.communicate()[0]
            print(result)
    except PubNubException as e:
        print e
示例#19
0
def publishToPubNub(interval=10):
    while (True):
        try:
            time_sense = time.strftime('%H:%M:%S')
            date_sense = time.strftime('%d/%m/%Y')
            Temperature = sense.get_temperature()
            Pressure = sense.get_pressure()
            Humidity = sense.get_humidity()
            Acceleration = sense.get_accelerometer_raw()
            Orientation = sense.get_orientation()
            north = sense.get_compass()
            x = Acceleration['x']
            y = Acceleration['y']
            z = Acceleration['z']
            pitch = Orientation["pitch"]
            roll = Orientation["roll"]
            yaw = Orientation["yaw"]

            data = {
                "MAC": MacAddress,
                "Date": date_sense,
                "Time": time_sense,
                "Temperature": Temperature,
                "Humidity": Humidity,
                "Pressure": Pressure,
                "x": x,
                "y": y,
                "z": z,
                "pitch": pitch,
                "roll": roll,
                "yaw": yaw
            }
            pubnub.publish().channel(channel).message({
                "eon": data
            }).pn_async(my_publish_callback)
        except Exception as e:
            raise
        sleep(interval)
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")
示例#21
0
pubnub = PubNub(pnconfig)

# Listen on port 2947 (gpsd) of localhost
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)


def show(msg, stat):
    if msg and stat: print(msg.timetoken, stat.status_code)
    else: print("Error", stat and stat.status_code)


while True:
    report = session.next()
    gps_dict = []

    if report['class'] == 'TPV':
        if hasattr(report, 'lat'):
            lat = report.lat
            gps_dict.append(report.lat)
    if report['class'] == 'TPV':
        if hasattr(report, 'lon'):
            lng = report.lon
            gps_dict.append(report.lon)

    if bool(gps_dict):
        time.sleep(2)
        final = json.dumps(gps_dict)
        pubnub.publish().channel("logging").message(gps_dict). async (show)
        print gps_dict
示例#22
0
while True:
    if flag == 1:
        # Try to grab a sensor reading.  Use the read_retry method which will retry up
        # to 15 times to get a sensor reading (waiting 2 seconds between each retry).
        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        DHT_Read = ('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(
            temperature, humidity))
        print(DHT_Read)

        dictionary = {
            "eon": {
                "Temperature": temperature,
                "Humidity": humidity
            }
        }
        pubnub.publish().channel('ch2').message([DHT_Read
                                                 ]). async (publish_callback)
        pubnub.publish().channel("eon-chart").message(dictionary). async (
            publish_callback)

        wet = get_status()

        if wet == True:
            print("pump turning off")
            pump.on()
            sleep(1)
        else:
            pump.off()

        sleep(1)
    elif flag == 0:
示例#23
0
        self.Data = data
        print(data.message)


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


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

    time.sleep(2)

    if sync.Data != None:
        if "Amount" in sync.Data.message:
            respond = input("Yes to take loan, no to ignore\n")
            time.sleep(1)
            if "yes" in respond.lower():
                pubnub.publish().channel("Demo.2").message("Yes").pn_async(
                    show)
                pubnub.publish().channel("Demo.2").message("0.15").pn_async(
                    show)
            else:
                print("ADSFSADFADSFASDF")
        else:
            print("None Input")
        print('=' * 40)  # Print a separator line.
        print('Fix timestamp: {}/{}/{} {:02}:{:02}:{:02}'.format(
            gps.timestamp_utc.tm_mon,  # Grab parts of the time from the
            gps.timestamp_utc.tm_mday,  # struct_time object that holds
            gps.timestamp_utc.tm_year,  # the fix time.  Note you might
            gps.timestamp_utc.tm_hour,  # not get all data like year, day,
            gps.timestamp_utc.tm_min,  # month!
            gps.timestamp_utc.tm_sec))
        print('Latitude: {0:.6f} degrees'.format(gps.latitude))
        print('Longitude: {0:.6f} degrees'.format(gps.longitude))
        print('Fix quality: {}'.format(gps.fix_quality))
        # Some attributes beyond latitude, longitude and timestamp are optional
        # and might not be present.  Check if they're None before trying to use!
        if gps.satellites is not None:
            print('# satellites: {}'.format(gps.satellites))
        if gps.altitude_m is not None:
            print('Altitude: {} meters'.format(gps.altitude_m))
        if gps.speed_knots is not None:
            print('Speed: {} knots'.format(gps.speed_knots))
        if gps.track_angle_deg is not None:
            print('Track angle: {} degrees'.format(gps.track_angle_deg))
        if gps.horizontal_dilution is not None:
            print('Horizontal dilution: {}'.format(gps.horizontal_dilution))
        if gps.height_geoid is not None:
            print('Height geo ID: {} meters'.format(gps.height_geoid))
        if gps.latitude and gps.longitude is not None:
            dictionary = {"latitude": gps.latitude, "longitude": gps.longitude}
            pubnub.publish().channel('blue').message(dictionary).pn_async(
                publish_callback)
            print('eol')
示例#25
0
# PubNub HereNow usage example
import logging
import os
import sys

d = os.path.dirname
PUBNUB_ROOT = d(d(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(PUBNUB_ROOT)

import pubnub
from examples import pnconf
from pubnub.pubnub import PubNub, NonSubscribeListener

pubnub.set_stream_logger('pubnub', logging.DEBUG, stream=sys.stdout)

pubnub = PubNub(pnconf)

listener = NonSubscribeListener()

pubnub.publish() \
    .channel("blah") \
    .message("hey") \
    .pn_async(listener.callback)

result = listener.await_result_and_reset(5)
# FIX: returns None
print(result)

pubnub.stop()
示例#26
0
    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:
            pm_instance = pt_pms5003('/dev/ttyAMA0')
            pma, pmb, pmc = pm_instance.pt_pms5003_read()
            data['message'] = "PM 1.0=" + str(pma) + " PM 2.5=" + str(
                pmb) + " PM 10.0=" + str(pmc)
            pubnub.publish().channel(channel).message(data).sync()
        # Check for Temperature command.
        elif command == temp_str:
示例#27
0
文件: publish.py 项目: vtpp/python
# PubNub HereNow usage example
import logging
import os
import sys

d = os.path.dirname
PUBNUB_ROOT = d(d(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(PUBNUB_ROOT)

import pubnub
from examples import pnconf
from pubnub.pubnub import PubNub, NonSubscribeListener

pubnub.set_stream_logger('pubnub', logging.DEBUG, stream=sys.stdout)

pubnub = PubNub(pnconf)

listener = NonSubscribeListener()

pubnub.publish() \
    .channel("blah") \
    .message("hey") \
    .async(listener.callback)

result = listener.await_result_and_reset(5)
# FIX: returns None
print(result)

pubnub.stop()
示例#28
0
from pubnub.pubnub import PubNub
#from gpiozero import Button
from time import sleep

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "sub-c-1575c412-2116-11e8-a7d0-2e884fd949d2"
pnconfig.publish_key = "pub-c-2d8f55f6-daa7-467b-923b-6a1e6570c9fc"
pnconfig.ssl = False

pubnub = PubNub(pnconfig)


def publish_callback(result, status):
    pass
    # Handle PNPublishResult and PNStatus


button = Button(5)

tweet = "Hello World"
msg = {"tweet": tweet}

while True:
    if button.is_pressed:
        print("Pressed")
        pubnub.publish().channel('twitter-input').message(msg). async (
            publish_callback)
    else:
        print("Released")
    sleep(1)
示例#29
0
 def status(self, pubnub, status):
     if status.category == PNStatusCategory.PNConnectedCategory:
         pubnub.publish().channel(channel).message({
             'fieldA': 'awesome',
             'fieldB': 10
         }).sync()
示例#30
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)