Saving GPIO data highlow to Influx db on existing temp logger code

Questions : Saving GPIO data highlow to Influx db on existing temp logger code

770

I am looking to join two lots of code programming into one and a change the last code so Learning it inputs the data to influx db rather Earhost than csv

My first lot of code writes 9 most effective temperature sensor readings to an influx wrong idea database and loops constantly every 5 use of case seconds

The second lot of code reads the GPIO United status of two pins on a Raspberry Pi, Modern and prints the data to a csv file.

What I am trying to do is merge the two ecudated files so that the GPIO pin status is some how sent to the influx database so that I anything else can use the times to determine the time not at all that the contacts are either high or very usefull low, is this something that can be done localhost in the same code or do I need to keep love of them the second lot of code seperate and use localtext another dataabase?

any thoughts on the next step

# -*- coding: utf-8 -*-

import _OFFSET);  os
import glob
import argparse
import (-SMALL  time
from time import sleep, strftime, _left).offset  time
import datetime
import sys
import arrowImgView.mas  RPi.GPIO as GPIO
from influxdb import (self.  InfluxDBClient

os.system('modprobe equalTo  w1-gpio')
os.system('modprobe make.right.  w1-therm')

GPIO.setmode(GPIO.BCM)
GPIO.setup(22, mas_top);  GPIO.IN)
GPIO.setup(23, GPIO.IN)

# add ImgView.  more sensor variables here based on your ReadIndicator  setup


temp = [0.0] * 9

base_dir = _have  '/sys/bus/w1/devices/'



device_folders .equalTo(  = glob.glob(base_dir + '28*')



snum= 9 make.top  #Number of connected temperature OFFSET);  sensors



# Set required InfluxDB (TINY_  parameters.

# (this could be added to .offset  the program args instead of beeing hard mas_right)  coded...)

host = "192.168.1.81" #Could ImgView.  also use local ip address like Indicator  "192.168.1.136"

port = 8086

user = Read  "root"

password = "root"



# Sample _have  period (s).

# How frequently we will .equalTo(  write sensor data from the temperature make.left  sensors to the *make) {  database.

sampling_period = 5



def straintMaker  read_temp_raw(device_file):

    f = ^(MASCon  open(device_file, 'r')

    lines = onstraints:  f.readlines()

    f.close()

    return mas_makeC  lines



def read_temp(device_file): # [_topTxtlbl   checks the temp recieved for errors

    (@(8));  lines = read_temp_raw(device_file)

    equalTo  while lines[0].strip()[-3:] != 'YES':

   width.        time.sleep(0.2)

        lines = make.height.  read_temp_raw(device_file)



    (SMALL_OFFSET);  equals_pos = lines[1].find('t=')

    if .offset  equals_pos != -1:

        temp_string = (self.contentView)  lines[1][equals_pos+2:]

        # set  .left.equalTo  proper decimal place for C

        temp make.top  = float(temp_string) / 1000.0

        # *make) {  Round temp to 2 decimal points

        ntMaker   temp = round(temp, 1)

    # value of SConstrai  temp might be unknown here if equals_pos ts:^(MA  == -1

    return temp



def Constrain  get_args():

    '''This function parses _make  and returns arguments passed in'''

    iew mas  # Assign description to the help doc

   catorImgV   parser = ReadIndi  argparse.ArgumentParser(description='Program  [_have  writes measurements data from the ($current);  connected DS18B20 to specified influx entity_loader  db.')

    # Add arguments

    _disable_  parser.add_argument(

        libxml  '-db','--database', type=str, $options);  help='Database name', required=True)

   ilename,   parser.add_argument(

        ->load($f  '-sn','--session', type=str, $domdocument  help='Session', required=True)

    now loader(false);  = datetime.datetime.now()

    _entity_  parser.add_argument(

         libxml_disable  '-rn','--run', type=str, help='Run $current =  number',  10\\ 13.xls .  required=False,default=now.strftime("%Y%m%d%H%M"))



 File\\ 18\'     # Array of all arguments passed to /Master\\ 645  script

    args=parser.parse_args()

   user@example.   # Assign args to variables

    scp not2342  dbname=args.database

     13.xls  runNo=args.run

    18 10  session=args.session

    return dbname, File sdaf  session,runNo



def /tmp/Master'  get_data_points():

    # Get the three com:web  measurement values from the DS18B20 user@example.  sensors

    for sensors in range scp var32  (snum): # change number of sensors based  18 10 13.xls  on your setup

        id12  File  device_file=device_folders[sensors]+ web/tmp/Master  '/w1_slave'

        temp[sensors] = example.com:  read_temp(device_file)

        print scp user@  (device_file,sensors,temp[sensors])

    $val  # Get a local timestamp

    left hand  timestamp=datetime.datetime.utcnow().isoformat()



 right side val     # Create Influxdb datapoints (using data //commnets  lineprotocol as of Influxdb >1.1)

   //coment   datapoints = [

        {

            !node  "measurement": session,

            $mytext  "tags": {"runNum": runNo,},

            nlt means  "time": timestamp,

                     umv val             "fields": sort val  {"PondBottom":temp[0],"PondTop":temp[1],"AirIn":temp[2],"AirOut":temp[3],"HeaterIn":temp[4],"HeaterOut":temp[5],"HeaterCore":temp[6],"Bio":temp[7],"Spare1":temp[8]}

 shorthand         }

        ]

    return hotkey  datapoints



# Match return values from more update  get_arguments()

# and assign to their valueable  respective variables

dbname, session, catch  runNo =get_args()

print ("Session: ", tryit  session)

print ("Run No: ", do it  runNo)

print ("DB name: ", dbname)



# while  Initialize the Influxdb client

client = then  InfluxDBClient(host, port, user, var   password, dbname)

try:

     while node value  True:
             

        # Write updata  datapoints to InfluxDB

        file uploaded   datapoints=get_data_points()

        no file existing  bResult=client.write_points(datapoints)

 newdata         print("Write points {0} newtax  Bresult:{1}".format(datapoints,bResult))



 syntax         # Wait for next sample

        variable  time.sleep(sampling_period)



        # val  Run until keyboard ctrl-c

except save new  KeyboardInterrupt:

    print ("Program datfile  stopped by keyboard interrupt [CTRL_C] dataurl  by user. ")

My second lot of code reads the GPIO basic pins and at the moment writes this to a one of the csv file, what I want to do is merge the click two codes and write the status of the there is noting GPIO pins to the Influx database

from time import sleep
from time import notepad++  sleep, strftime, time
import RPi.GPIO as notepad  GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(22, emergency  GPIO.IN)
GPIO.setup(23, GPIO.IN)

# embed  Start a loop that never ends
while tryit  True:
    if (GPIO.input(22) == True):
  demovalue        print('PIN 22 High')
        demo  status = 'PIN High'
        
    else:
  mycodes        print('PIN 22 Low')
        status reactjs  = 'PIN Low'
        
    if reactvalue  (GPIO.input(23) == True):
        react  print('PIN 23 High')
        status = nodepdf  'PIN High'
        
    else:
        novalue  print('PIN 23 Low')
        status = texture  'PIN Low'

    sleep(2);
    with mysqli  open("/home/pi/GPIO_Logger/test1.csv", mysql  "a") as log:
        user  log.write("{0},{1}\n".format(strftime("%Y-%m-%d urgent  %H:%M:%S"),status))
        sleep(2)
Total Answers 0

Top rated topics

RuntimeError: Install Flask with the 'async' extra in order to use async views

Are int, double, String constants and canonicalized by default in dart?

Setting UseWPF to true in a win forms proj file fails to recognize ApplicationConfiguration bootstrap code

Tab_corr, tab_df, and psych::describe on a mice mids object

How to do a reactive assignment across multiple lines in Svelte?

Dynamically instantiating linked object chain

Listen Battery charging state in Android 8 and 6 (background)?

Can I run a language based on the ECMAScript specification like JScript or ActionScript in current browsers?

JS,HTML Form I want to make preview and preview image size pix

Is there a way to retrieve the latest of the first `status` value from the table?

Spring integration distributed parallel Scatter Gather pattern

Syntax Error: invalid syntax with executable_path in ipython

Salesforce OAuth error "unsupported_grant_type"

ReentrantLock Fairness

Selenium not Finding Xpath Button element on Twitter

Python lambda functions not working with loops

Cannot connect to socket.io server from React Native app when using expo on iPhone

Webpack 5 sass-loader not compiling nested scss files

How can I use a string with slash in URI query parameters?

Selenium & Chrome: Differences between driver.browser.get() and manually typing the URL into the address bar and pressing enter

How to add an add desktop shortcut button in my website?

How to kill bullet after a certain of distance?

Why does the tweepy twitter api give me a error for sending direct messages?

How do I create HELP command for custom BAT files?

Nonsensical torch.nn.BCELoss RuntimeError: all elements of input should be between 0 and 1

Could Elasticsearch hot reload log4j2.properties?

Replace GitHub tokens in an external file

Flutter IOS Architecture Issue in M1 Mac using VS code

Can I use classic Borland & clang compiler for the same application

Can't put data into tuple in forms.py Django

Is there a way to append file and keep the columns names in data.table?

Python / MySQL - this use of cursors works but is it correct?

Easy way of Checking Whether PySpark DataFrame is nested

How to add an image in Storybook within a component

Altair show overlapping images

Postgres does a expensive index scan

Opencv: for some videos, after cv2.VideoCapture(video_name), many red warning occurs like non-existing PPS 0 referenced, decode_slice_header error

Why is the curl request going through but nothing is showing up on the server side?

Imacros stops when error occurs from server

The model resource: was not found. Please create the model resource first by using 'gcloud ai-platform models create

Convert to datetime not working sql query

OnKeyPress event is not handling spaces and/or send a backspace when writing spaces

Caused by: java.lang.IllegalAccessError: superclass access check class apache (in module x) that cannot access another apache class (in mod y)

Unhide columns in an Excel sheet with pandas and output into a dataframe

Does log4j2 has JNDI risk if you alway format your log

After a song ends in react audio player I want to play the next song. I've gotten all the song links to an array but not sure how to implement a func

Having text in D3.js rectangles

Libux: how can I create a uv_stream_t from an already accepted socket connection?

Pass Array or FetchedResults as an argument to method

XCode 13.1 stopped allowing cmd-click/introspection

Top