コード例 #1
0
def send_to_is(bucket_name, bucket_key, access_key, weather):
    try:
        streamer = Streamer(bucket_name, bucket_key, access_key)

        # Temperature
        temp = weather.get_temperature(unit='fahrenheit').get('temp')
        streamer.log('Temperature (F)', temp)

        # Cloud coverage
        cloud = str(weather.get_clouds()) + '%'
        streamer.log('Cloud Coverage', cloud)

        # Detailed status
        detail_status = weather.get_detailed_status()
        streamer.log('Detailed Status', detail_status)

        # Humidity
        humidity = str(weather.get_humidity()) + '%'
        streamer.log('Humidity', humidity)

        # Visibility distance
        visibility_distance = weather.get_visibility_distance()
        streamer.log('Visibility Distance (m)', visibility_distance)

        # Wind speed
        wind_speed = weather.get_wind().get('speed')
        streamer.log('Wind Speed (m/s)', wind_speed)

        # Wind degree
        wind_degree = weather.get_wind().get('deg')
        streamer.log('Wind Degree', wind_degree)

    finally:
        streamer.close()
コード例 #2
0
def post_data_to_initialstate(field_name, sensor_value):
    streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=IS_ACCESS_KEY)

    # send some data
    streamer.log(field_name, sensor_value)

    # flush and close the stream
    streamer.close()
コード例 #3
0
ファイル: Feyre.py プロジェクト: iancaragol/Feyre
async def send_data():
    stream_data = deepcopy(data.statsDict)
    stream_data['user_count'] = len(data.userSet)
    stream_data['server_count'] = len(bot.guilds)
    stream_data['total_command_count'] = await bot.cogs.get('StatsCog').get_total_helper(data.statsDict)

    streamer = Streamer(bucket_name="Feyre", bucket_key=bucket_key, access_key=access_key, buffer_size=200)
    streamer.log_object(stream_data)

    streamer.flush()
    streamer.close()
コード例 #4
0
ファイル: coffee_scale.py プロジェクト: evanwill/weigherBot
    def logToInitialState(self):
        utcnow = datetime.utcnow()
        bucketKey = "{0} - coffee_scale_data".format(self.environment)

        streamer = Streamer(bucket_name="{0} - Coffee Scale Data".format(self.environment), 
                bucket_key=bucketKey, access_key=self.initialStateKey)

        if self.potIsLifted():
            streamer.log("Coffee Pot Lifted", True)
        streamer.log("Coffee Weight", self._currentWeight)
        streamer.close()
コード例 #5
0
def main():
    streamer = Streamer(bucket_name=args.bucket, access_key=apiKey)

    try:
        while True:
            resultLines = read_temp_raw(args.sensor)
            save_result(args.sensor, resultLines, streamer)
            print(INFO,"Cycle finished, sleeping %ss" %(args.delay))
            time.sleep(args.delay)
    except KeyboardInterrupt:
        streamer.close()
コード例 #6
0
def send_value(t):
    # Streamer constructor, this will create a bucket called Python Stream Example
    # you'll be able to see this name in your list of logs on initialstate.com
    # your access_key is a secret and is specific to you, don't share it!
    streamer = Streamer(bucket_name="Temperature Perros-Guirec",
                        bucket_key="VFSWQRTVFX56",
                        access_key="TpxF1xIFECwXn4XuGsGYvHHAhLY1kJHU")
    streamer.log("temp", t)
    streamer.log("temperature Perros-Guirec", t)
    # Once you're finished, close the stream to properly dispose
    streamer.close()

    return
コード例 #7
0
def main():
    streamer = Streamer(bucket_name=args.bucket,
                        access_key=apiKey,
                        bucket_key=args.bucket_key)

    try:
        while True:
            resultLines = read_temp_raw(args.sensor)
            save_result(args.sensor, resultLines, streamer)
            print(INFO, "Cycle finished, sleeping %ss" % (args.delay))
            time.sleep(args.delay)
    except KeyboardInterrupt:
        streamer.close()
コード例 #8
0
    def logToInitialState(self):
        utcnow = datetime.utcnow()
        bucketKey = "{0} - coffee_scale_data".format(self.environment)

        streamer = Streamer(bucket_name="{0} - Coffee Scale Data".format(
            self.environment),
                            bucket_key=bucketKey,
                            access_key=self.initialStateKey)

        if self.potIsLifted():
            streamer.log("Coffee Pot Lifted", True)
        streamer.log("Coffee Weight", self._currentWeight)
        streamer.close()
コード例 #9
0
ファイル: reading.py プロジェクト: 2bitoperations/raspi-sump
def initialstate_stream_reading(reading):
    if "initialstate.enabled" not in configs or configs[
            "initialstate.enabled"] != 1:
        return

    try:
        from ISStreamer.Streamer import Streamer
        streamer = Streamer(bucket_name=configs["initialstate.bucket_name"],
                            bucket_key=configs["initialstate.bucket_key"],
                            access_key=configs["initialstate.access_key"])
        streamer.log(key=configs["initialstate.item_key"], value=reading)
        streamer.flush()
        streamer.close()
        log.log_restarts("sent initialstate reading")
    except Exception as ex:
        log.log_errors("problem streaming reading to initialstate!")
コード例 #10
0
class InitialStateLogObject(TerminatorBlock):
    """ Initial State block for logging objects
    """

    version = VersionProperty("1.0.0")
    access_key = StringProperty(title='Access Key',
                                default='[[INITIAL_STATE_ACCESS_KEY]]')
    bucket_name = StringProperty(title='Bucket Name', default='New Bucket')
    bucket_key = StringProperty(title='Bucket Key', default='')
    object = Property(title='Object', default='{{ $.to_dict() }}')
    buffer_size = IntProperty(title='Buffer Size', default=10)

    def __init__(self):
        super().__init__()
        self._streamer = None

    def configure(self, context):
        super().configure(context)
        try:
            kwargs = {'access_key': self.access_key()}
            if self.bucket_name():
                kwargs['bucket_name'] = self.bucket_name()
            if self.bucket_key():
                kwargs['bucket_key'] = self.bucket_key()
            if self.buffer_size():
                kwargs['buffer_size'] = self.buffer_size()
            self._streamer = Streamer(**kwargs)
        except Exception as e:
            self.logger.error("Failed to create streamer: {}".format(e))
            raise e

    def process_signals(self, signals):
        for s in signals:
            try:
                self._streamer.log_object(self.object(s))
            except Exception as e:
                self.logger.warning("Failed to log object: {}".format(e))
        self._streamer.flush()

    def stop(self):
        super().stop()
        self._streamer.close()
コード例 #11
0
def main(argv):
	bucket = ''
	access_key = ''
	try:
		opts, args = getopt.getopt(argv,"hb:k:",["bucket_name=", "access_key="])
	except getopt.GetoptError:
		print('example_command_line.py -b <bucket_name> -k <access_key>')

	for opt, arg in opts:
		if opt == '-h':
			print('example_command_line.py -b <bucket_name> -k <access_key>')
		elif opt in ("-b", "--bucket_name"):
			bucket = arg
		elif opt in ("-k", "--access_key"):
			access_key = arg


	streamer = Streamer(bucket_name=bucket, access_key=access_key)

	try:
		while 1:
			log = ''
			try:
				if (sys.version_info < (2,7,0)):
				    sys.stderr.write("You need at least python 2.7.0 to use the ISStreamer")
				    exit(1)
				elif (sys.version_info >= (3,0)):
				    log = input()
				else:
				    log = raw_input()
			except EOFError:
				break
			parts = log.split(',')

			if len(parts) == 2:
				streamer.log(parts[0].strip(), parts[1].strip())
			else:
				print("format should be \"key, value\"")

	except KeyboardInterrupt:
		streamer.close()
コード例 #12
0
def main():
   sensor = W1ThermSensor()

   pool_streamer = Streamer( bucket_name="Pool Temperature", access_key="PFphNne4eMOAMQ6EiIW5DT0BNWEIunAT", bucket_key="RPSVL4LX8S7H")
   pi_streamer = Streamer( bucket_name="Pi Temperature", access_key="PFphNne4eMOAMQ6EiIW5DT0BNWEIunAT", bucket_key="8YXAKKXW348W")

   try:
      while True:
         pi_temp = read_pi_temp()
         send_data_to_InitialState( "Onboard Pi Temperature", pi_temp, pi_streamer )
         print( "Pi onboard temperature is %.2f" % ( pi_temp ) )

         temp_in_fahrenheit = sensor.get_temperature( W1ThermSensor.DEGREES_F )
         send_data_to_InitialState( "Pool Temperature Sensor", temp_in_fahrenheit, pool_streamer )
         print( "Sensor %s has temperature %.2f" % ( sensor.id, temp_in_fahrenheit ) )

         time.sleep( delay )

   except KeyboardInterrupt:
      pool_streamer.close()
      pi_streamer.close()
コード例 #13
0
def main(argv):
    bucket = ""
    access_key = ""
    try:
        opts, args = getopt.getopt(argv, "hb:k:", ["bucket_name=", "access_key="])
    except getopt.GetoptError:
        print("example_command_line.py -b <bucket_name> -k <access_key>")

    for opt, arg in opts:
        if opt == "-h":
            print("example_command_line.py -b <bucket_name> -k <access_key>")
        elif opt in ("-b", "--bucket_name"):
            bucket = arg
        elif opt in ("-k", "--access_key"):
            access_key = arg

    streamer = Streamer(bucket_name=bucket, access_key=access_key)

    try:
        while 1:
            log = ""
            try:
                if sys.version_info < (2, 7, 0):
                    sys.stderr.write("You need at least python 2.7.0 to use the ISStreamer")
                    exit(1)
                elif sys.version_info >= (3, 0):
                    log = input()
                else:
                    log = raw_input()
            except EOFError:
                break
            parts = log.split(",")

            if len(parts) == 2:
                streamer.log(parts[0].strip(), parts[1].strip())
            else:
                print('format should be "key, value"')

    except KeyboardInterrupt:
        streamer.close()
コード例 #14
0
# ##########################################
# This script is an example
# of how to hit the stream limit
# on a free account, who's cap is set 
# prorated for when then plan is selected.
# ###########################################

from math import ceil
import time, calendar, datetime
from ISStreamer.Streamer import Streamer

now = datetime.datetime.now()
days_in_month = calendar.monthrange(now.year, now.month)[1]
days_left_in_month = float(days_in_month - now.day)
unrounded_prorate = (days_left_in_month / days_in_month)
# roudn the proration up and multiply it by the current free tier allowance
estimated_cap = int((ceil(unrounded_prorate*100) / 100.0) * 25000)

print("Estimated Cap: {}".format(estimated_cap))

stream = Streamer(bucket_name="Testing Cap", bucket_key="cap_testing", buffer_size=100, ini_file_location="./isstreamer.ini", debug_level=2)

for x in range(1, estimated_cap):
	# throttle every 100 events
	if (x%100 == 0):
		time.sleep(1)

	stream.log("event", x)

stream.close()
コード例 #15
0
ファイル: temp_logging.py プロジェクト: mliebski/Sensors
sys.stderr = MyLogger(logger, logging.ERROR)
CHECK_FREQ = 60 #check temp every 60 secs


while True:



        if DEBUG:

                string1 = 'PIs internal temperature is: '
                string2 = float(open('/sys/class/thermal/thermal_zone0/temp').read())
                string2 = string2/1000
                string2 = str(string2)
                string3 = ' Degrees Celsius'
                endstring = string1 +  string2 + string3
               logger.info(endstring)
                slogger.log("PI Internal Temp: ", string2)
                slogger.close()
                URLString = 'https://whatever it will be for you.hanatrial.ondemand.com/iotscenario/?action=addsensorvalue&sensorid=1&unit=Celsius&sensorvalue=' + string2 +'&sensorvaluemultiplier=1&sensorvaluecalibration=0'
#               print(URLString) (I use that for debugging purpose)
                urllib2.urlopen(URLString).read()



        else:

                break

        time.sleep(CHECK_FREQ)
コード例 #16
0
def main():
    city = input(
        "Enter the name of the City you require the Weather Conditions of:")
    address = "https://www.google.com/search?rlz=1C1HLDY_enUS874US874&ei=dengXeHcE8qd5wKj4aDIAw&q=" + city + "+coordinates&oq=" + city + "+&gs_l=psy-ab.3.0.0i67i70i251j0j0i67l3j0i131j0i67l3j0i131.10435.11689..12656...0.1..0.165.881.4j4......0....1..gws-wiz.......0i71j0i273.KfscqkpHNeY"
    web_page = requests.get(address)
    soup = BeautifulSoup(web_page.content,
                         "html.parser")  #Scraping Content from Google Search
    coords_class = soup.find_all(class_="BNeawe iBp4i AP7Wnd")
    required_coords = coords_class[0].find_all(
        class_="BNeawe iBp4i AP7Wnd"
    )  #Getting coords in a particular class in scraped data
    latitudes_longitude = []
    str_coords = str(required_coords)
    t = str_coords.replace(">", " ")
    t = t.replace("<", " ")
    t = t.replace(",", " ")
    t = t.replace("°", "")
    T = t.split(" ")
    latitudes_longitude.append(T[5])
    latitudes_longitude.append(T[6])
    latitudes_longitude.append(T[8])
    latitudes_longitude.append(T[9])
    coords = ""
    if (latitudes_longitude[1] == "S"):
        latitudes_longitude[0] = str(-1.0 * float(
            latitudes_longitude[0]))  #Converting Latitude to standard notation
    if (latitudes_longitude[3] == "W"):
        latitudes_longitude[2] = str(-1.0 * float(
            latitudes_longitude[2]))  #converting Longitude to standar notation
    coords = latitudes_longitude[0] + "," + latitudes_longitude[
        2]  #Adding Latitudes and Longitudes of a place in "coords" variable
    coords
    global GPS_COORDS
    GPS_COORDS = coords
    global DARKSKY_API_KEY

    DARKSKY_API_KEY = "c0974690b3b66a08fe5ea57c4926f420"  #Storing API key in DarkSky_API_KEY variable
    BUCKET_NAME = ":partly_sunny: " + city + " Weather"  #Storing Bucket Name
    BUCKET_KEY = "T57BL7K39XAX"  #Storing Buckey Key for Streamer Dashboard
    ACCESS_KEY = "ist_uOnFF2jMhg7iwAu9R5HqFVAVeTZoQk-q"  #Storing Access Key of Streamer Dashboard

    curr_conditions = get_current_conditions()
    if (
            'currently' not in curr_conditions
    ):  # Checking for connectivity to API and printing if connection is invalid
        print(
            "Error! Dark Sky API call failed, check your GPS coordinates and make sure your Dark Sky API key is valid!\n"
        )
        print(curr_conditions)
        exit()
    else:
        streamer = Streamer(bucket_name=BUCKET_NAME,
                            bucket_key=BUCKET_KEY,
                            access_key=ACCESS_KEY)  #Accessing the Streamer
    while True:
        curr_conditions = get_current_conditions()
        if ('currently' not in curr_conditions):
            print(
                "Error! Dark Sky API call failed. Skipping a reading then continuing ...\n"
            )  #Again checking connectivity
        else:
            streamer.log(":house: Location",
                         GPS_COORDS)  #Streaming the Location on the Dashboard
            webbrowser.open(
                'https://go.init.st/jp3ahqe'
            )  #Command to automatically open up default webbrowser

            #Streaming the Humidity on the Dashboard
            if 'humidity' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['humidity']):
                streamer.log(":droplet: Humidity(%)",
                             curr_conditions['currently']['humidity'] * 100)

            #Streaming the Temperature on the Dashboard
            if 'temperature' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['temperature']):
                streamer.log("Temperature",
                             curr_conditions['currently']['temperature'])

            #Streaming the Apparent Temperature on the Dashboard
            if 'apparentTemperature' in curr_conditions[
                    'currently'] and isFloat(
                        curr_conditions['currently']['apparentTemperature']):
                streamer.log(
                    "Apparent Temperature",
                    curr_conditions['currently']['apparentTemperature'])

            #Streaming the DewPoint on the Dashboard
            if 'dewPoint' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['dewPoint']):
                streamer.log("Dewpoint",
                             curr_conditions['currently']['dewPoint'])

            #Streaming the WindSpeed on the Dashboard
            if 'windSpeed' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['windSpeed']):
                streamer.log(":dash: Wind Speed",
                             curr_conditions['currently']['windSpeed'])

            #Streaming the Wind_Gust on the Dashboard
            if 'windGust' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['windGust']):
                streamer.log(":dash: Wind Gust",
                             curr_conditions['currently']['windGust'])

            #Streaming the Wind Direction on the Dashboard
            if 'windBearing' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['windBearing']):
                streamer.log(
                    ":dash: Wind Direction",
                    wind_dir_icon(curr_conditions['currently']['windBearing']))

            #Streaming the Pressure Condition on the Dashboard
            if 'pressure' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['pressure']):
                streamer.log("Pressure",
                             curr_conditions['currently']['pressure'])

            #Streaming the Precipitation Intensity on the Dashboard
            if 'precipIntensity' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['precipIntensity']):
                streamer.log(":umbrella: Precipitation Intensity",
                             curr_conditions['currently']['precipIntensity'])

            #Streaming the Precipitation Probability on the Dashboard
            if 'precipProbability' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['precipProbability']):
                streamer.log(
                    ":umbrella: Precipitation Probabiity(%)",
                    curr_conditions['currently']['precipProbability'] * 100)

            #Streaming the Cloud Cover on the Dashboard
            if 'cloudCover' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['cloudCover']):
                streamer.log(":cloud: Cloud Cover(%)",
                             curr_conditions['currently']['cloudCover'] * 100)

            #Streaming the Ultraviolet Index on the Dashboard
            if 'uvIndex' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['uvIndex']):
                streamer.log(":sunny: UV Index:",
                             curr_conditions['currently']['uvIndex'])

            #Streaming the Visibility on the Dashboard
            if 'visibility' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['visibility']):
                streamer.log(":sunny: Visibility:",
                             curr_conditions['currently']['visibility'])

            #Streaming the Ozone Level on the Dashboard
            if 'ozone' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['ozone']):
                streamer.log(":sunny: Ozone Level:",
                             curr_conditions['currently']['ozone'])

            #Streaming the Weather Summary on the Dashboard
            if 'summary' in curr_conditions['currently']:
                streamer.log(":cloud: Weather Summary",
                             curr_conditions['currently']['summary'])

            #Streaming the Forecast Message for today on the Dashboard
            if 'hourly' in curr_conditions:
                streamer.log("Today's Forecast",
                             curr_conditions['hourly']['summary'])

            #Streaming the Moon Phase and Weather Condition Icon on the Dashboard
            if 'daily' in curr_conditions:
                if 'data' in curr_conditions['daily']:
                    if 'moonPhase' in curr_conditions['daily']['data'][0]:
                        moon_phase = curr_conditions['daily']['data'][0][
                            'moonPhase']
                        streamer.log(":crescent_moon: Moon Phase",
                                     moon_icon(moon_phase))
                        streamer.log(
                            ":cloud: Weather Conditions",
                            weather_status_icon(
                                curr_conditions['currently']['icon'],
                                moon_phase))

            streamer.flush()  #Refreshing the Stream
            streamer.close()  #Closing the Stream
        break
コード例 #17
0
def identify(image):
    faceId1 = detect(image)
    body = str({'faceIds': faceId1, 'personGroupId': 'contacts'})

    #Line added to push to Initial State
    streamer = Streamer(bucket_name="TRAKR",
                        bucket_key="VandyHacks",
                        access_key="02JRVjhxxM9eIwKrvXN44TWnzUotO0aZ")
    try:
        conn = http.client.HTTPSConnection('api.projectoxford.ai')
        conn.request("POST", "/face/v1.0/identify?", body, jsonHeaders)
        response = conn.getresponse()
        data = response.read().decode('utf-8')
        data = json.loads(data)

        #Code for tracking counter from a local file
        f = open("counter.txt", "r")
        counter = int(f.read())
        f.close()
        arrNames = []
        for key in data:
            if key == 'error':
                pass
            elif len(key['candidates']) == 0:
                alert("+12674750425", "+12674607556",
                      "Someone unknown is by the door.\n", image)

                #Code added to push to Initial State
                streamer.log("Name:", "Unknown")
                streamer.log("Status:", "Awaiting")
                streamer.log("Recognized:", ":thumbsdown:")
                streamer.log("People at home :house:", counter)
            else:
                pId = key['candidates'][0]['personId']
                conn.request(
                    "GET",
                    "/face/v1.0/persongroups/contacts/persons/{}?".format(pId),
                    "{null}", jsonHeaders)
                response = conn.getresponse()
                data = response.read().decode('utf-8')
                data = json.loads(data)
                arrNames.append(data['name'])
                print(data['name'])
                streamer.log("Name:", data['name'])
                streamer.log("Status:", "Inside")
                streamer.log("Recognized:", ":thumbsup:")
                now = datetime.now()
                today7am = now.replace(hour=7,
                                       minute=0,
                                       second=0,
                                       microsecond=0)
                today8pm = now.replace(hour=20,
                                       minute=0,
                                       second=0,
                                       microsecond=0)
                if now > today8pm or now < today7am:
                    streamer.log("Time of entry :crescent_moon:",
                                 datetime.now().strftime("%H:%M:%S"))
                else:
                    streamer.log("Time of entry :sunny:",
                                 datetime.now().strftime("%H:%M:%S"))
                counter = counter + 1
                streamer.log("People at home :house:", counter)
        if len(arrNames) == 1:
            conn.request(
                "POST",
                "/face/v1.0/persongroups/contacts/persons/{}/persistedFaces?".
                format(pId), convert_to_bin(image), headers)
            train()
        if len(arrNames) > 0:
            welcome(arrNames)
        conn.close()
        f2 = open("counter.txt", "w")
        f2.write(str(counter))
        f2.close()
        streamer.close()
    except Exception as e:
        print(e)
        print("[identifyErrno {0}] {1}".format(e.errno, e.strerror))
コード例 #18
0
import time

# Streamer constructor, this will create a bucket called Python Stream Example
# you'll be able to see this name in your list of logs on initialstate.com
# your access_key is a secret and is specific to you, don't share it!
streamer = Streamer(bucket_name="Sofie.py",
                    bucket_key="Sofie",
                    access_key="ist_kh_4Iv3IJuAd4mH82Km0H0yHD5CU9QJh")

# example data logging

for num in range(1, 20):
    time.sleep(0.1)
    if num % 1 == 0:
        streamer.log("Number", "2")
    if num % 2 == 0:
        streamer.log("Naam", "Sofie")
    if num % 3 == 0:
        streamer.log("Energie", "40")
    if num % 4 == 0:
        streamer.log("myNumber", "51.16257, 4.99084")

## This is just an example, try something of your own!
##   ideas:
##     - solve world hunger, one bug fix at a time
##     - create the worlds first widget
##     - build an army of bug-free robot kittens

# Once you're finished, close the stream to properly dispose
streamer.close()
コード例 #19
0
ファイル: app.py プロジェクト: petyuska/python_appender
from ISStreamer.Streamer import Streamer
import time

streamer = Streamer(bucket_name="test", debug_level=2)


def stress_test_loop(i, num):
    while i > 0:
        streamer.log("iterations_left_{n}".format(n=num), i)
        time.sleep(0.2)
        i = i - 1


stress_test_loop(50, 1)

streamer.close()
コード例 #20
0
        uartlist[3] = int(uartlist[3])
        uartlist[4] = int(uartlist[4])
        uartlist[5] = int(uartlist[5])
        for i in range(1,3):
            temperature = convert_to_temperature((uartlist[i+3]))
            vwc = convert_to_vwc((uartlist[i+1]), temperature)
            uartlist[i+1] = vwc
            uartlist[i+3] = temperature

        rssi.log(uartlist[1])
        shallowtemp.log(uartlist[2])
        shallowvwc.log(uartlist[3])
        deeptemp.log(uartlist[4])
        deepvwc.log(uartlist[5])

        rssi.close()
        shallowtemp.close()
        shallowvwc.close()
        deeptemp.close()
        deepvwc.close()

    i=0
    for x in gv.hubnames:
        if ((uartlist[0] == x[1]) and (len(uartlist)==6)):
            if (len(gv.hubnames[i]))==3:
                gv.hubnames[i].extend(uartlist[2:6])
            elif (len(gv.hubnames[i]))==7:
                for j in range(3,7):
                    ((gv.hubnames[i])[j]) = uartlist[j-1]
        i = i + 1
コード例 #21
0
                publish_data.log("Vehicle is located at", where_it_is.address)
                print(where_it_is.address)
        if raw_data['class'] == 'TPV':
            if hasattr(raw_data, 'speed'):
                publish_data.log("Speed of the vehicle", raw_data.speed)
                print "Vehicle is moving at = " + str(raw_data.speed) + " KPH"
        if raw_data['class'] == 'TPV':
            if hasattr(raw_data, 'alt'):
                publish_data.log("Altitude", raw_data.alt)
                print "The altitude is = " + str(raw_data.alt) + " m"
        if raw_data['class'] == 'TPV':
            if hasattr(raw_data, 'time'):
                publish_data.log("Time", raw_data.time)
                print "The curent date and time is = " + str(
                    raw_data.time) + "\n"

    except GeocoderTimedOut as e:
        publish_data.log("msg", "Geocoder Timeout")
        pass
    except KeyError:
        pass
    except (KeyboardInterrupt, SystemExit):
        publish_data.close()
        print "\nEnding the current process"
        gps.running = False
        exit()
        quit()
    except StopIteration:
        session = None
        print "No incoming data from the GPS module"
コード例 #22
0
import time
from ISStreamer.Streamer import Streamer

logger = Streamer(bucket_name="Stream Example", debug_level=2)

logger.log("My Messages", "Stream Starting")
for num in range(1, 1000):
        time.sleep(0.001)
        logger.log("My Numbers", num)
        if num%2 == 0:
                logger.log("My Booleans", False)
        else: 
                logger.log("My Booleans", True)
        if num%3 == 0:
                logger.log("My Events", "pop")
        if num%10 == 0:
                logger.log("My Messages", "Stream Half Done")
logger.log("My Messages", "Stream Done")

logger.close()
コード例 #23
0
def main():

	streamer = Streamer(bucket_name="FireDash", bucket_key="python_example", access_key="ist_vg7IMJ1kf0T-YjoSjdZG-1Do8VA3tj6i")
	
	#Sending Startup Values to dashboard
	streamer.log("Status", "Online")
	streamer.log("Temperature", 0)
	streamer.log("Pressure", 0)
	streamer.log("Light", 0)
	streamer.log("FireLevel", 1)
	streamer.log("FireDetected", "Low")

	count = 0
	temp_sum = 0
	pressure_sum = 0
	light_sum = 0

	risk_rating = { 
		1: "Low", 
		2: "Moderate", 
		3: "High",
		4: "Critical", 
	}

	print("Stream Started")

	while True:
		print("Streaming")
		time.sleep(0.1) 

		count = count + 1

		#temperature sensor affected by surrounding residual heat
		#subtracting raw value from cpu temperature to get accurate results
		cpu_temp = get_cpu_temperature()
		raw_temp = weather.temperature()
		temp_fixed = raw_temp - ((cpu_temp-raw_temp)/1.3)

		#temperature, light and pressure as totaled for smoothing
		temp_sum = temp_sum + temp_fixed
		light_sum = light_sum + light.light()
		pressure_sum = pressure_sum + weather.pressure(unit = 'hPa') 

		#once allocated samples are taken, the value is averaged to get a more accurate reading
		if count == SAMPLE_RATE:
			
			temp_value = temp_sum/SAMPLE_RATE
			pressure_value = pressure_sum/SAMPLE_RATE
			light_value = light_sum/SAMPLE_RATE

			#smoothed data is sent to dash board for processing
			streamer.log("Temperature", round(temp_value,2))
			streamer.log("Pressure", round(pressure_value,2))
			streamer.log("Light", round(light_value,2))



			#calculates the risk of a fire present based on recieved data
			risk_level = calculate_risk(temp_value, pressure_value, light_value)
			streamer.log("FireLevel", risk_level)
			streamer.log("FireDetected", risk_rating.get(risk_level))

			streamer.flush()
			count = 0
			temp_sum = 0
			light_sum = 0
			pressure_sum = 0

	streamer.close()
コード例 #24
0
import time
from ISStreamer.Streamer import Streamer

logger = Streamer(bucket_name="Stream Example", debug_level=2, offline=True)

logger.log("My Messages", "Stream Starting")
for num in range(1, 1000):
    time.sleep(0.001)
    logger.log("My Numbers", num)
    if num % 2 == 0:
        logger.log("My Booleans", False)
    else:
        logger.log("My Booleans", True)
    if num % 3 == 0:
        logger.log("My Events", "pop")
    if num % 10 == 0:
        logger.log("My Messages", "Stream Half Done")
logger.log("My Messages", "Stream Done")

logger.close()
コード例 #25
0
except:
    # try the other serial port on the raspberry pi
    dbgprint("Failed to open serial port 0. Trying port 1.")
    ser = serial.Serial(port1, baud_rate, timeout=1)

dbgprint("serial port: " + ser.name + ": open=" + str(ser.isOpen()))
time.sleep(0.5)

try:
    cloud_streamer = Streamer(bucket_name=credentials.bucket_name,
                              bucket_key=credentials.bucket_key,
                              access_key=credentials.access_key)
    dbgprint("streamer.BucketName: " + str(cloud_streamer.BucketName))
    dbgprint("streamer.AccessKey: " + str(cloud_streamer.AccessKey))
    # spawn a thread to continually read Arduino sensors, cache locally, and send to the cloud
    t1 = threading.Thread(target=check_status, args=())
    t2 = threading.Thread(target=analyze_status, args=())
    # flag threads as daemons so we exit if the main thread dies
    t1.daemon = True
    t2.daemon = True
    t1.start()
    t2.start()
    while ser.isOpen():
        time.sleep(5)
except:
    try:
        ser.close()
        cloud_streamer.close()
    finally:
        dbgprint("\nQuitting")