亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

連接測試和循環以防連接丟失,以防止腳本結束

連接測試和循環以防連接丟失,以防止腳本結束

PHP
慕桂英546537 2023-11-09 21:24:12
問題是當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 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 temp
查看完整描述

1 回答

?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

強迫我繼續添加 try- except 因為最后只是我沒有在腳本中正確定位


這是允許腳本不會因連接錯誤而崩潰的修改。


#!/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


def 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 variables

dbname, session, runNo =get_args()   

print ("Session: ", session)

print ("Run No: ", runNo)

print ("DB name: ", dbname)


# Initialize the Influxdb client

client = 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-c

except KeyboardInterrupt:

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




查看完整回答
反對 回復 2023-11-09
  • 1 回答
  • 0 關注
  • 101 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號