89 lines
2.2 KiB
Python
89 lines
2.2 KiB
Python
'''
|
|
Script to get CO2 values and write it to text file
|
|
need parameter: CO2_port
|
|
/usr/bin/python3 /var/www/moduleair_pro_4g/MH-Z19/write_data.py ttyAMA4
|
|
'''
|
|
|
|
import serial
|
|
import requests
|
|
import json
|
|
import sys
|
|
import subprocess
|
|
import time
|
|
|
|
parameter = sys.argv[1:] # Exclude the script name
|
|
#print("Parameters received:")
|
|
port='/dev/'+parameter[0]
|
|
|
|
ser = serial.Serial(
|
|
port=port,
|
|
baudrate=9600,
|
|
parity=serial.PARITY_NONE,
|
|
stopbits=serial.STOPBITS_ONE,
|
|
bytesize=serial.EIGHTBITS,
|
|
timeout = 1
|
|
)
|
|
|
|
|
|
# Command to read CO2 concentration
|
|
# Contains 9 bytes (byte 0 ~ 8)
|
|
# FIRST byte: fixed to 0xFF
|
|
# SECOND byte: sensor number (factory default is 0 x01)
|
|
# THIRD byte: 0x86 Gas Concentration
|
|
|
|
# end with proof test value Checksum
|
|
|
|
|
|
READ_CO2_COMMAND = b'\xFF\x01\x86\x00\x00\x00\x00\x00\x79'
|
|
|
|
file_path = "/var/www/moduleair_pro_4g/matrix/input.txt"
|
|
|
|
|
|
def read_co2():
|
|
# Send the read command to the MH-Z19
|
|
ser.write(READ_CO2_COMMAND)
|
|
|
|
# Wait for the response from the sensor
|
|
time.sleep(2) # Wait for the sensor to respond
|
|
|
|
# Read the response from the sensor (9 bytes expected)
|
|
response = ser.read(9)
|
|
|
|
# Print the response to debug
|
|
print(f"Response: {response}")
|
|
|
|
# Check if the response is valid (the first byte should be 0xFF)
|
|
if len(response) < 9:
|
|
print("Error: No data or incomplete data received.")
|
|
return None
|
|
|
|
if response[0] == 0xFF:
|
|
# Extract the CO2 concentration value (byte 2 and 3)
|
|
co2_concentration = response[2] * 256 + response[3]
|
|
return co2_concentration
|
|
else:
|
|
print("Error reading data from sensor.")
|
|
return None
|
|
|
|
|
|
|
|
def main():
|
|
try:
|
|
co2 = read_co2()
|
|
if co2 is not None:
|
|
print(f"CO2 Concentration: {co2} ppm")
|
|
output_file = "/var/www/moduleair_pro_4g/matrix/input_MHZ16.txt"
|
|
with open(output_file, "w") as file:
|
|
file.write(f"{co2} \n")
|
|
print(f"Data written to {output_file}")
|
|
else:
|
|
print("Failed to get CO2 data.")
|
|
|
|
except KeyboardInterrupt:
|
|
print("Program terminated.")
|
|
finally:
|
|
ser.close()
|
|
|
|
if __name__ == '__main__':
|
|
main()
|