连接测试和循环以防连接丢失,以防止脚本结束

问题是当grafana服务器停止进行备份或其他操作时,脚本会出错并且不会自动恢复,所以我正在寻找一种创建可发送数据的连接测试循环的方法,如果 Grafana 服务器关闭,则连续脚本将一直工作,直到 Grafana 服务器启动并运行,从而恢复向 Grafana 服务器发送温度数据。


因为当前我最终得到消息中错误的脚本 requests.exceptions.ConnectionError: HTTPConnectionPool


使用脚本 python templogger.py -db=influx_db_temperature -sn=temperature -rn=RUN


我的脚本:


#!/usr/bin/python

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


import os

import glob

import argparse

import time

import datetime

import sys

from influxdb import InfluxDBClient


os.system('modprobe w1-gpio')

os.system('modprobe w1-therm')


# add more sensor variables here based on your setup


# For multiple sensor

# temp=['sensor code','tttttttttt','ddddddddddd','ssssssssss']

temp=['0120215dbea2','0120327e05bf']

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


# Ext = 28-0120215dbea2

# Int = 28-0120327e05bf


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


snum=2 #Number of connected temperature sensors


# Set required InfluxDB parameters.

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

host = "NasGrafana.lan.prive" #Could also use local ip address like "192.168.1.136"

port = 8086

user = "temperature"

password = "12345678"

 

# Sample period (s).

# How frequently we will write sensor data from the temperature sensors to the database.

sampling_period = 120


def read_temp_raw(device_file): 

    f = open(device_file, 'r')

    lines = f.readlines()

    f.close()

    return lines

 

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

    lines = read_temp_raw(device_file)

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

        time.sleep(0.2)

        lines = read_temp_raw(device_file)


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

    if equals_pos != -1:

        temp_string = lines[1][equals_pos+2:]

        # set proper decimal place for C

        temp = float(temp_string) / 1000.0

        # Round temp to 2 decimal points

        temp = round(temp, 1)

    # value of temp might be unknown here if equals_pos == -1

    return temp



慕桂英546537
浏览 124回答 1
1回答

慕斯王

强迫我继续添加 try- except 因为最后只是我没有在脚本中正确定位这是允许脚本不会因连接错误而崩溃的修改。#!/usr/bin/python# -*- coding: utf-8 -*-import osimport globimport argparseimport timeimport datetimeimport sysfrom influxdb import InfluxDBClientos.system('modprobe w1-gpio')os.system('modprobe w1-therm')# add more sensor variables here based on your setup# For multiple sensor# temp=['sensor code','tttttttttt','ddddddddddd','ssssssssss']temp=['0120215dbea2','0120327e05bf']base_dir = '/sys/bus/w1/devices/'# Ext = 28-0120215dbea2# Int = 28-0120327e05bfdevice_folders = glob.glob(base_dir + '28*')snum=2 #Number of connected temperature sensors# Set required InfluxDB parameters.# (this could be added to the program args instead of beeing hard coded...)host = "NasGrafana.lan.prive" #Could also use local ip address like "192.168.1.136"port = 8086user = "temperature"password = "12345678" # Sample period (s).# How frequently we will write sensor data from the temperature sensors to the database.sampling_period = 120def read_temp_raw(device_file):     f = open(device_file, 'r')    lines = f.readlines()    f.close()    return lines def read_temp(device_file): # checks the temp recieved for errors    lines = read_temp_raw(device_file)    while lines[0].strip()[-3:] != 'YES':        time.sleep(0.2)        lines = read_temp_raw(device_file)    equals_pos = lines[1].find('t=')    if equals_pos != -1:        temp_string = lines[1][equals_pos+2:]        # set proper decimal place for C        temp = float(temp_string) / 1000.0        # Round temp to 2 decimal points        temp = round(temp, 1)    # value of temp might be unknown here if equals_pos == -1    return tempdef get_args():    '''This function parses and returns arguments passed in'''    # Assign description to the help doc    parser = argparse.ArgumentParser(description='Program writes measurements data from the connected DS18B20 to specified influx db.')    # Add arguments    parser.add_argument(        '-db','--database', type=str, help='Database name', required=True)    parser.add_argument(        '-sn','--session', type=str, help='Session', required=True)    now = datetime.datetime.now()    parser.add_argument(        '-rn','--run', type=str, help='Run number', required=False,default=now.strftime("%Y%m%d%H%M"))        # Array of all arguments passed to script    args=parser.parse_args()    # Assign args to variables    dbname=args.database    runNo=args.run    session=args.session    return dbname, session,runNo    def get_data_points():    # Get the three measurement values from the DS18B20 sensors    for sensors in range (snum): # change number of sensors based on your setup        device_file=device_folders[sensors]+ '/w1_slave'        temp[sensors] = read_temp(device_file)        print (device_file,sensors,temp[sensors])    # Get a local timestamp    timestamp=datetime.datetime.utcnow().isoformat()    NumDevice=os.path.basename(os.path.dirname(device_file))        # Create Influxdb datapoints (using lineprotocol as of Influxdb >1.1)    datapoints = [        {            "measurement": session,            # "tags": {"runNum": NumDevice,},            "tags": {"runNum": runNo,},            "time": timestamp,            #"fields": {"temperature 1":temp[0],"temperature 2":temp[1],"temperature 3":temp[2],"temperature 4":temp[3]}            "fields": {"temperature 1":temp[0],"temperature 2":temp[1]}        }        ]    return datapoints# Match return values from get_arguments()# and assign to their respective variablesdbname, session, runNo =get_args()   print ("Session: ", session)print ("Run No: ", runNo)print ("DB name: ", dbname)# Initialize the Influxdb clientclient = InfluxDBClient(host, port, user, password, dbname)        try:     while True:        # Write datapoints to InfluxDB        datapoints=get_data_points()        try:            bResult=client.write_points(datapoints)            print("Write points {0} Bresult:{1}".format(datapoints,bResult))        except:            print("Error lan connection")            #time.sleep(30)            #continue                    # Wait for next sample        time.sleep(sampling_period)                # Run until keyboard ctrl-cexcept KeyboardInterrupt:    print ("Program stopped by keyboard interrupt [CTRL_C] by user. ")
打开App,查看更多内容
随时随地看视频慕课网APP