概述
# @File : pub.py
# @Author: Wang Zhimin
# @Date : 2021/05/19
# python 3.6
import json
import random
import time
from datetime import datetime
from paho.mqtt import client as mqtt_client
import modbus_tk
# import modbus_tk.defines as cst
# import modbus_tk.modbus_tcp as modbus_tcp
import pandas as pd
import modbus_tk.defines as md
import modbus_tk.modbus_tcp as mt
logger = modbus_tk.utils.create_logger("console")
import logging
data3=pd.read_csv("./Config2.csv")
# print(data3.iloc[0,1])
broker = str(data3.iloc[0,1])
port = int(data3.iloc[0,4])
topic = "data"
# generate client ID with pub prefix randomly
# client_id = f'python-mqtt-{random.randint(0, 1000)}'
client_id = f"{str(data3.iloc[0,0])}"
username=str(data3.iloc[0,2])
password=str(data3.iloc[0,3])
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
logger.info("Connected to MQTT Broker!")
else:
logger.info("Failed to connect, return code %dn", rc)
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.username_pw_set(username=username, password=password)
client.connect(broker, port)
return client
def publish(client):
# msg_count = 0
try:
while True:
time.sleep(0.1)
data=pd.read_csv("./Config.csv")
data2=pd.read_csv("./Config2.csv")
jsonlist=[]
for i in range(data.shape[0]):
aaa=master.execute(slave=data.iloc[i,1], function_code=md.READ_INPUT_REGISTERS, starting_address=data.iloc[i,2], quantity_of_x=data.iloc[i,3], output_value=1)
a=[]
for k in aaa:
a.append(k/100)
dict={"addr":str(i+1),"val":a}
jsonlist.append(dict)
dict2={"did":str(data2.iloc[0,0]),"utime":int(round(time.time()*1000)),"content":jsonlist}
dict2_=json.dumps(dict2)
msg = f"{dict2_}"
result = client.publish(topic, msg)
status = result[0]
if status == 0:
logger.debug(f"Send `{msg}` to topic `{topic}`")
else:
logger.info(f"Failed to send message to topic {topic}")
# msg_count += 1
except:
logger.info("由于目标计算机积极拒绝,无法连接。")
# logger.info()
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
data4 = pd.read_csv("./Config2.csv")
level_=data4.iloc[0,7]
if int(level_)==0:
logger.setLevel(level=logging.DEBUG)
else:
logger.setLevel(level=logging.INFO)
while True:
master = mt.TcpMaster(str(data4.iloc[0,5]), int(data4.iloc[0,6]))
master.set_timeout(5.0)
logger.info("connected")
run()
最后
以上就是细心蜜粉为你收集整理的modbus TCP Mqtt 从CSV文件中读取配置参数的全部内容,希望文章能够帮你解决modbus TCP Mqtt 从CSV文件中读取配置参数所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复