コード例 #1
0
ファイル: read_temp.py プロジェクト: mvschaik/temperature
def main(gpio, room, org, bucket):
    while True:
        client = InfluxDBClient.from_env_properties()
        write_api = client.write_api(write_options=SYNCHRONOUS)
        hum, temp = Adafruit_DHT.read_retry(SENSOR, gpio)
        if temp is not None:
            p = Point("temp").tag("room", room).field("degrees_c", temp).time(datetime.utcnow())
            logging.info("Writing %s", p.to_line_protocol())
            write_api.write(bucket, org, p)
        if hum is not None:
            p = Point("humid").tag("room", room).field("perc_rh", hum).time(datetime.utcnow())
            logging.info("Writing %s", p.to_line_protocol())
            write_api.write(bucket, org, p)
        write_api.close()

        time.sleep(INTERVAL)
コード例 #2
0
def main():
    global device_details
    #get_devices()
    #print(device_details)
    get_devices_refresh()
    cache_timestamp = datetime.datetime.now()
    for line in sys.stdin:
        #May be able to adjust this logic to have seperate timers for each app_id
        #Update cache if older than 1 hour
        if (datetime.datetime.now() -
                cache_timestamp).seconds >= 3600 and len(device_details) > 0:
            #refresh every hour
            get_devices_refresh()
            #re-Set timestamp
            cache_timestamp = datetime.datetime.now()
        #Parse timeprotocol to Points type
        lproto = line_protocol_parser.parse_line(line)
        #parse topic tag to return the device_id and app_id eg: v3/fort-digital-agri@ttn/devices/2027a0023/up v3/{{app_id}}@{{tenant}}/devices/{{device_id}}/up
        topic_match = topic_re.match(lproto['tags']['topic'])
        app_id = topic_match[1]
        #tenant = topic_match[2]
        device_id = topic_match[3]
        point = Point(lproto['measurement']).time(lproto['time'])
        if app_id not in device_details or device_id not in device_details[
                app_id]:
            get_devices(app_id)
        if app_id in device_details:
            for key, value in lproto['fields'].items():
                point = point.field(key, will_it_float(value))
            for key, value in lproto['tags'].items():
                if key != 'name':
                    point = point.tag(key, value)
            #get details from global variable
            device = get_device(app_id, device_id)
            #Add additional tags
            point = point.tag("device_id", device_id)
            for key, value in device.items():
                point = point.tag(key, value)
            #Print lineprotocol to stdout
            print(point.to_line_protocol())
            #flushstdout
            sys.stdout.flush()
        else:
            print("Device Details not found")
コード例 #3
0
from influxdb_client import WritePrecision, InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS

bucket = "my-bucket"

client = InfluxDBClient(url="http://localhost:9999", token="my-token", org="my-org")

write_api = client.write_api(write_options=SYNCHRONOUS)
query_api = client.query_api()

p = Point("my_measurement").tag("location", "Prague").field("temperature", 25.3).time(datetime.now(), WritePrecision.MS)

# write using point structure
write_api.write(org="my-org", bucket=bucket, record=p)

line_protocol = p.to_line_protocol()
print(line_protocol)

# write using line protocol string
write_api.write(org="my-org", bucket=bucket, record=line_protocol)

# using Table structure
tables = query_api.query('from(bucket:"my-bucket") |> range(start: -1m)')
for table in tables:
    print(table)
    for record in table.records:
        # process record
        print(record.values)

# using csv library
csv_result = query_api.query_csv('from(bucket:"my-bucket") |> range(start: -10m)')
コード例 #4
0
username = '******'
password = '******'

database = 'telegraf'
retention_policy = 'autogen'

bucket = f'{database}/{retention_policy}'

client = InfluxDBClient(url='http://localhost:8086', token=f'{username}:{password}', org='-')

print('*** Write Points ***')

write_api = client.write_api()

point = Point("mem").tag("host", "host1").field("used_percent", 25.43234543)
print(point.to_line_protocol())

write_api.write(bucket=bucket, record=point)
write_api.close()

print('*** Query Points ***')

query_api = client.query_api()
query = f'from(bucket: \"{bucket}\") |> range(start: -1h)'
tables = query_api.query(query)
for record in tables[0].records:
    print(f'#{record.get_time()} #{record.get_measurement()}: #{record.get_field()} #{record.get_value()}')

client.close()
コード例 #5
0
def get_gateway_details(gateway):
    #print(gateway)
    gateway_id = gateway['ids']['gateway_id']
    point = Point("TTN_Gateways").tag("gateway_id",
                                      gateway_id).tag("name", gateway['name'])
    if 'antennas' in gateway:
        for dimension in ['latitude', 'longitude', 'altitude']:
            if dimension in gateway['antennas'][0]['location']:
                value = gateway['antennas'][0]['location'][dimension]
            else:
                value = 0
            point = point.tag(
                dimension, value
            )  #body['gateway']['antennas'][0]['location'][dimension] = antenna_locations[dimension]
        #point = point.tag('latitude',gateway['antennas'][0]['location']['latitude']).tag('longitude',gateway['antennas'][0]['location']['longitude']).tag('altitude',gateway['antennas'][0]['location']['altitude'])
        #for key,value in gateway['antennas'][0]['location']:
        #    point = point.tag(key,value)
    gateway_stats = (requests.get(base_uri + "/api/v3/gs/gateways/" +
                                  gateway_id + "/connection/stats",
                                  params=gateway_stats_params,
                                  headers=http_headers)).json()
    #https://eu1.cloud.thethings.network/api/v3/gs/gateways/fort-digital-80029c641ef8/connection/stats
    if 'attributes' in gateway:
        for key, value in gateway['attributes'].items():
            point = point.tag(key, value)
    #Need to consider how to handle last_status_received_at not updating but not getting a 'gateway not connected' message yet to mark a site as 'down'
    #Can probably handle this in the query?
    if "connected_at" in gateway_stats:
        #print(gateway_stats)
        point = point.field("status", 1)
        if 'last_status_received_at' in gateway_stats:
            point = point.time(gateway_stats['last_status_received_at'])
        if 'uplink_count' in gateway_stats:
            point = point.field("uplink_count",
                                will_it_float(gateway_stats['uplink_count']))
        if 'downlink_count' in gateway_stats:
            point = point.field("downlink_count",
                                will_it_float(gateway_stats['downlink_count']))
        if 'last_status' in gateway_stats:
            if 'metrics' in gateway_stats['last_status']:
                for key, value in gateway_stats['last_status'][
                        'metrics'].items():
                    point = point.field(key, will_it_float(value))
            #Could use the latest antenna location to automatically update gateway location as its ignored from UDP gateway_stats['last_status']['antenna_locations']['latitude/longitude/altitude']
            #print(gateway_stats)
            if 'antenna_locations' in gateway_stats['last_status']:
                if 'antennas' not in gateway or gateway['antennas'][0][
                        'location']['latitude'] != gateway_stats[
                            'last_status']['antenna_locations'][0][
                                'latitude'] or gateway['antennas'][0][
                                    'location']['longitude'] != gateway_stats[
                                        'last_status']['antenna_locations'][0][
                                            'longitude']:
                    update_gateway(
                        gateway_id,
                        gateway_stats['last_status']['antenna_locations'][0])
    else:
        #Gateway Not Connected
        point = point.field("status", 0)
    print(point.to_line_protocol())
    #flushstdout
    sys.stdout.flush()