模拟mysql 的slave_Python modbus rtu slave+mysql+随机数生产模拟数据

目的:

通过读取mysq’l rtu数据表地址数值,用python在原值得基础上加上随机数(0-9)

mysql数据

数据结构

e230f269a025a431403bdb40e782f263.png

数据列表(部分)

3a1d559e36c27fe05b0ec0ed53853972.png

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 server

server = 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 = 1

name = '0'

address = int('0')

mysql_rule(server,slave_id)

time.sleep(1) # 休眠1秒

finally:

server.stop()

if __name__ == "__main__":

main()

测试结果

在这里插入代码片

8b831db24cc7d1e9f95257f9d32022fa.png

[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

原文链接:https://blog.csdn.net/taogunet/article/details/111573429

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值