本文主要是介绍Python modbus rtu slave+mysql+随机数生产模拟数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目的:
通过读取mysq’l rtu数据表地址数值,用python在原值得基础上加上随机数(0-9)
mysql数据
数据结构
数据列表(部分)
Python代码
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import sys
import time
import pymysql
import json
import random
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
import serial
#PORT = 0
PORT = '/dev/ttyS1'
mysqlhost="localhost"
mysqluser="python"
mysqlpassword="python"
mysqlport=3306
mysqldatabase="python"
mysqlcharset='utf8'
#读取数据库触发条件规则
def mysql_rule(myserver,slaveid):db = pymysql.connect(mysqlhost, mysqluser, mysqlpassword, port=mysqlport,database=mysqldatabase, charset=mysqlcharset)cursor = db.cursor(cursor =pymysql.cursors.DictCursor) #设置游标类型为DictCursor以后,生成的就是字段名和值组成的键值对字典了sql = "SELECT * FROM rtu where slave_id='"+str(slaveid)+"'"print(sql)try:cursor.execute(sql) results = cursor.fetchall()value=[] for row in results:value=[] slave_id = row['slave_id']name = row['name']addr = int(row['addr'])myvalue =int(row['value'])+random.randint(0,9)value.append(myvalue)print(str(slave_id)+" "+name+" "+str(addr)+" "+str(myvalue))myslave = myserver.get_slave(slaveid)myslave.set_values(name,addr,myvalue)value = myslave.get_values(name,addr, 1)sys.stdout.write('done: values written: %s\r\n' % (str(value)+' id'+str(row['id']))) # 打印结果except:print("Error: unable to fecth data")cursor.close()db.close()
def main():"""main"""logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") #Create the serverserver = modbus_rtu.RtuServer(serial.Serial(PORT,baudrate=9600)) try:logger.info("running...")logger.info("enter 'quit' for closing the server") server.start() slave_1 = server.add_slave(1)slave_1.add_block('0', cst.HOLDING_REGISTERS, 0, 100)while True:slave_id = 1name = '0'address = int('0')mysql_rule(server,slave_id)time.sleep(1) # 休眠1秒finally:server.stop()if __name__ == "__main__":main()
测试结果
在这里插入代码片
[root@bogon lqj]# python rtu.py
RtuServer /dev/ttyS1 is opened
running...
enter 'quit' for closing the server
SELECT * FROM rtu where slave_id='1'
1 0 0 66
done: values written: (66,) id1
1 0 1 68
done: values written: (68,) id2
1 0 2 63
done: values written: (63,) id3
1 0 3 64
done: values written: (64,) id4
1 0 4 60
done: values written: (60,) id5
1 0 5 68
done: values written: (68,) id6
1 0 7 69
done: values written: (69,) id7
1 0 8 66
这篇关于Python modbus rtu slave+mysql+随机数生产模拟数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!