0

我对 Python 非常陌生(我以前的大部分编程经验都是中级 C++ 和 Java),我正在尝试开发一个脚本,该脚本将读取传感器数据并将其记录到 .csv 文件中。为此,我为代码创建了单独的类——一个将读取传感器数据并将其输出到控制台,而另一个应该获取该数据并记录它——并将它们组合成一个包含每个类的主脚本. 单独地,它们可以完美地工作,但只有 sensorReader 类功能一起使用。我试图让每个类在自己的线程中运行,同时将传感器数据从第一类(sensorReader)传递到第二类(csvWriter)。我在下面发布了一些伪代码,但如果需要,我很乐意用实际源代码澄清任何问题。

import time
import sensorStuff
import csv
import threading
import datetime


class sensorReader:

    # Initializers for the sensors.
    this.code(initializes the sensors)

    while True:

        try:
            this.code(prints the sensor data to the console)

        this.code(throws exceptions)

        this.code(waits 60 seconds)


class csvWriter:

    this.code(fetches the date and time)

    this.code(writes the headers for the excel sheet once)

    while True: 
        this.code(gets date and time)

        this.code(writes the time and one row of data to excel)

        this.code(writes a message to console then repeats every minute)


r = sensorReader()
t = threading.Thread(target = r, name = "Thread #1")
t.start()
t.join
w = csvWriter()
t = threading.Thread(target = w, name = "Thread #2")
t.start() 

我意识到最后一部分并没有真正的意义,但我真的在这里超越了我的体重,所以我什至不确定为什么只有第一类有效而不是第二类,更不用说如何为多个类实现线程. 如果有人能指出我正确的方向,我将不胜感激。

谢谢!

编辑

我决定贴出完整的源代码:

import time
import board
import busio
import adafruit_dps310
import adafruit_dht
import csv
import threading
import datetime
# import random


class sensorReader:

    # Initializers for the sensors.
    i2c = busio.I2C(board.SCL, board.SDA)
    dps310 = adafruit_dps310.DPS310(i2c)
    dhtDevice = adafruit_dht.DHT22(board.D4)

    while True:

        # Print the values to the console.
        try:
            global pres
            pres = dps310.pressure
            print("Pressure = %.2f hPa"%pres)
            global temperature_c
            temperature_c = dhtDevice.temperature
            global temperature_f
            temperature_f = temperature_c * (9 / 5) + 32
            global humidity
            humidity = dhtDevice.humidity
            print("Temp: {:.1f} F / {:.1f} C \nHumidity: {}% "
                .format(temperature_f, temperature_c, humidity))
            print("")

        # Errors happen fairly often with DHT sensors, and will occasionally throw exceptions.
        except RuntimeError as error:
            print("n/a")
            print("")

        # Waits 60 seconds before repeating.
        time.sleep(10)


class csvWriter:

    # Fetches the date and time for future file naming and data logging operations.
    starttime=time.time()
    x = datetime.datetime.now()

    # Writes the header for the .csv file once.
    with open('Weather Log %s.csv' % x, 'w', newline='') as f:
        fieldnames = ['Time', 'Temperature (F)', 'Humidity (%)', 'Pressure (hPa)']
        thewriter = csv.DictWriter(f, fieldnames=fieldnames)
        thewriter.writeheader()

    # Fetches the date and time.
    while True: 
        from datetime import datetime
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")

        # Writes incoming data to the .csv file.
        with open('Weather Log %s.csv', 'a', newline='') as f: 
            fieldnames = ['TIME', 'TEMP', 'HUMI', 'PRES'] 
            thewriter = csv.DictWriter(f, fieldnames=fieldnames)
            thewriter.writerow({'TIME' : current_time, 'TEMP' : temperature_f, 'HUMI' : humidity, 'PRES' : pres})

        # Writes a message confirming the data's entry into the log, then sets a 60 second repeat cycle.
        print("New entry added.")
        time.sleep(10.0 - ((time.time() - starttime) % 10.0)) # Repeat every ten seconds.

r = sensorReader()
t = threading.Thread(target = r, name = "Thread #1")
t.start()
t.join
w = csvWriter()
t = threading.Thread(target = w, name = "Thread #2")
t.start()
4

1 回答 1

0

这样的结构会更好。如果您将第一个循环放在一个函数中,您可以延迟它的评估,直到您准备好启动线程。但是在一个类体中它会立即运行,你永远不会得到第二个定义。

def sensor_reader():
    # Initializers for the sensors.
    this.code(initializes the sensors)
    while True:
        try:
            this.code(prints the sensor data to the console)
        except:
            print()
        this.code(waits 60 seconds)


threading.Thread(target=sensor_reader, name="Thread #1", daemon=True).start()

this.code(fetches the date and time)
this.code(writes the headers for the excel sheet once)
while True: 
    this.code(gets date and time)
    this.code(writes the time and one row of data to excel)
    this.code(writes a message to console then repeats every minute)

我把它做成了一个守护进程,所以当你终止程序时它会停止。另请注意,我们只需要创建一个线程,因为我们已经有了主线程。

于 2020-04-21T15:29:28.960 回答