Commit cbda2291 authored by aohui.li's avatar aohui.li

新增多串口同时刻采集脚本,获取噪音数据,上发平台

parent 3d0d4a50
...@@ -12,6 +12,7 @@ import time ...@@ -12,6 +12,7 @@ import time
# 0x00 0x06 0x00 # 0x00 0x06 0x00
SerialCom = 'COM18' SerialCom = 'COM18'
SerialCom2 = 'COM18'
# (sensor_id, register) # (sensor_id, register)
noise_Message = [ (1, 0x00), noise_Message = [ (1, 0x00),
...@@ -51,7 +52,10 @@ class Sensor: ...@@ -51,7 +52,10 @@ class Sensor:
data = self.__master.execute(noise_Message[noise_sensor_idx][0], cst.READ_HOLDING_REGISTERS, noise_Message[noise_sensor_idx][1], 1) data = self.__master.execute(noise_Message[noise_sensor_idx][0], cst.READ_HOLDING_REGISTERS, noise_Message[noise_sensor_idx][1], 1)
return data return data
S = Sensor(SerialCom) S = Sensor(SerialCom)
S2 = Sensor(SerialCom2)
# ser = serial.Serial(SerialComTest, 4800, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE) # ser = serial.Serial(SerialComTest, 4800, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)
# data_to_send = [0x02,0x03,0x00,0x06,0x00, 0x01 ,0x64 ,0x38] # data_to_send = [0x02,0x03,0x00,0x06,0x00, 0x01 ,0x64 ,0x38]
...@@ -60,20 +64,17 @@ def mqtt_task(): ...@@ -60,20 +64,17 @@ def mqtt_task():
while True: while True:
if mqtt._start_flag: if mqtt._start_flag:
if enableJianDa: if enableJianDa:
time.sleep(0.3) n1 = S2.get_noise(1)[0] / 10.0
n1 = S.get_noise(1)[0] / 10.0
else: else:
n1 = 0.0 n1 = 0.0
if enableShangLuo: if enableShangLuo:
time.sleep(0.3)
n2 = S.get_noise(2)[0] / 10.0 n2 = S.get_noise(2)[0] / 10.0
else: else:
n2 = 0.0 n2 = 0.0
if enableZhaotai: if enableZhaotai:
time.sleep(0.3) n3 = S2.get_noise(3)[0] / 10.0
n3 = S.get_noise(3)[0] / 10.0
else: else:
n3 = 0.0 n3 = 0.0
......
import serial
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
import threading
from module.myMqtt import myMqtt
import time
#############################[Sensor Config]###################################
# 485 Addr Index
# 1 2 3
# 建大jd 上洛sl 兆泰盛zt
# 0x00 0x06 0x00
SerialCom = 'COM18'
SerialCom2 = 'COM19'
ser = serial.Serial('COM20', 9600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)
# (sensor_id, register)
noise_Message = [ (1, 0x00),
(2, 0x06),
(3, 0x00)]
# Enable sensor
enableJianDa = 1
enableShangLuo = 0
enableZhaotai = 1
enableRuisen = 1
# Enable Print OnLineTime
enableOnLineTime = 0
#############################[MQTT Config]###################################
RequestTopic = 'WT/WTG93RF/99991213/opDataRequest'
EchoNoiseTopic = 'WT/WTG93RF/99991213/opData'
begin_time = time.time()
class Sensor:
def __init__(self, port):
self._port = port
try:
self._ser = serial.Serial(self._port, baudrate=4800)
self._ser.open() if not self._ser.is_open else None
self.__master = modbus_rtu.RtuMaster(self._ser)
self.__master.set_timeout(2, use_sw_timeout=True)
except Exception as exp:
print(exp)
exit(1)
def get_noise(self, noise_sensor_idx):
noise_sensor_idx -= 1
data = self.__master.execute(noise_Message[noise_sensor_idx][0], cst.READ_HOLDING_REGISTERS, noise_Message[noise_sensor_idx][1], 1)
return data
def get_noise_rs232():
head = ser.read(2) # 读取地址字节
data = ser.read(4) # 读取功能码字节
# 将字节串转换为整数
dB_data = int.from_bytes(data)
dB_data = dB_data / 10.0 # trans dB
print(dB_data)
return 0
def get_noise_rs232_():
data = ser.read(6).decode('utf-8') # 读取6个字符并解码为字符串
# 检查数据是否以'aa05'开头
if data.startswith('aa'):
# 提取数据部分('0568')
data_part = data[2:]
try:
# 将数据转换为浮点数,并转换为dB
db_value = float(data_part) / 10.0
# 打印转换后的值
print(f'Received data: {data_part} -> {db_value:.1f}dB')
except ValueError:
print('Invalid data format:', data_part)
else:
print('Invalid data received:', data)
return db_value
S = Sensor(SerialCom)
S2 = Sensor(SerialCom2)
# ser = serial.Serial(SerialComTest, 4800, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)
# data_to_send = [0x02,0x03,0x00,0x06,0x00, 0x01 ,0x64 ,0x38]
def mqtt_task():
try:
while True:
if mqtt._start_flag:
if enableJianDa:
n1 = S2.get_noise(1)[0] / 10.0
else:
n1 = 0.0
if enableShangLuo:
n2 = S.get_noise(2)[0] / 10.0
else:
n2 = 0.0
if enableZhaotai:
n3 = S.get_noise(3)[0] / 10.0
else:
n3 = 0.0
if enableRuisen:
n4 = get_noise_rs232_()
else:
n4 = 0.0
now = int(time.time())
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(now)))
data = [{"addr":"1","ts":int(now),"jd":float(n1),"sl":float(n2),"zt":float(n3),"rs":float(n4)}]
# data = json.dumps(data)
mqtt.publish(EchoNoiseTopic, data)
print(data)
time.sleep(1)
if enableOnLineTime:
end_time = time.time()
run_time = round(end_time-begin_time)
hour = run_time//3600
minute = (run_time-3600*hour)//60
second = run_time-3600*hour-60*minute
print(f"online-time:{hour}:{minute}:{second}")
except Exception as exp:
print("Error Exception:", exp)
print("Need to restart the script")
if __name__ == '__main__':
mqtt_info = {
'broker': 'www.witium.com.cn',
'port': 12883,
'user': 'witcd',
'password': 'Witium37774020'
}
mqtt = myMqtt(mqtt_info)
mqtt.set_add_topic(RequestTopic)
mqtt.open_mqtt()
mqtt_thread = threading.Thread(target=mqtt.loop_task)
mqtt_thread.start()
app_thread = threading.Thread(target=mqtt_task)
app_thread.start()
#!usr/bin/python3
import json
import time
import paho.mqtt.client as mqtt
from sympy import false
import os
import ssl
path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
resourcesPath = path + os.sep
tls = {
"ca_certs": resourcesPath+"file\\ca.crt",
"certfile": "./file/client.crt",
"keyfile": "./file/client.key",
"tls_version": ssl.PROTOCOL_TLSv1_2
}
class myMqtt:
def __init__(self, mqtt_info):
self._topic_enable = False
self._topic = []
self._mqtt_enable = False
self._mqtt_info = mqtt_info
self._client = None
self._context = None
self._start_flag = False
self._request_flag = False
def open_mqtt(self):
# open mqtt
try:
if 'user' in self._mqtt_info and 'password' in self._mqtt_info \
and 'broker' in self._mqtt_info and 'port' in self._mqtt_info:
self._client = mqtt.Client()
self._client.username_pw_set(self._mqtt_info['user'], self._mqtt_info['password'])
self._client.on_connect = self.on_connect
self._client.on_message = self.on_message
# self._client.tls_set(tls)
# self._client.tls_set(ca_certs=resourcesPath +"file\\cacert.pem", certfile=resourcesPath + "file\\cert.pem",
# keyfile=resourcesPath + "file\\key.pem",tls_version=ssl.PROTOCOL_TLSv1_2)
# self._client.tls_insecure_set(True)
self._client.connect(self._mqtt_info['broker'], self._mqtt_info['port'])
self._mqtt_enable = True
print("mqtt config success")
else:
self._mqtt_enable = False
print("mqtt config error")
except Exception as exp:
self._mqtt_enable = False
print(exp)
def set_add_topic(self, topic):
self._topic_enable = True
self._topic.append(topic)
def get_add_topic(self):
if self._topic_enable:
return self._topic
else:
return None
def clear_topic(self):
self._topic = []
self._topic_enable = False
def on_connect(self, client, userdata, flags, rc):
if self._topic_enable and self._mqtt_enable:
for index in self._topic:
self._client.subscribe(index)
print(index)
self._start_flag = True
def on_message(self, client, userdata, msg):
try:
if self._topic_enable and self._mqtt_enable:
if 'Request' in msg.topic:
self._request_flag = True
except Exception as exp:
print(exp)
def publish(self, config_topic, data):
try:
if self._topic_enable and self._mqtt_enable:
self._client.publish(config_topic, json.dumps(data, separators=(',', ':')), qos=1)
except Exception as exp:
print(exp)
def loop_task(self):
try:
if self._topic_enable and self._mqtt_enable:
self._client.loop_forever()
except Exception as exp:
print(exp)
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
# file_path = './noise_data/Motor.csv'
file_path = './noise_data/_1KHz.csv'
# Read data into a pandas DataFrame
df = pd.read_csv(file_path, sep=" ", parse_dates=["Time"])
# Convert Time to seconds for plotting
df['Time_in_seconds'] = df['Time'].dt.hour * 3600 + df['Time'].dt.minute * 60 + df['Time'].dt.second
# Plotting
plt.figure(figsize=(100, 30))
plt.plot(df['Time_in_seconds'], df['dB'], marker='o')
plt.title('dB Level Over Time')
plt.xlabel('Time (seconds)')
plt.ylabel('dB Level')
plt.grid(True)
plt.savefig('result_noise_data.png')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment