本文整理汇总了Python中pymodbus.client.sync.ModbusSerialClient类的典型用法代码示例。如果您正苦于以下问题:Python ModbusSerialClient类的具体用法?Python ModbusSerialClient怎么用?Python ModbusSerialClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ModbusSerialClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SerialRtuChannel
class SerialRtuChannel(BaseChannel):
def __init__(self, network, channel_name, channel_protocol, channel_params, channel_manager, channel_type):
self.port = channel_params.get("port", "")
self.stopbits = channel_params.get("stopbits", serial.STOPBITS_ONE)
self.parity = channel_params.get("parity", serial.PARITY_NONE)
self.bytesize = channel_params.get("bytesize", serial.EIGHTBITS)
self.baudrate = channel_params.get("baudrate", 9600)
self.timeout = channel_params.get("timeout", 2)
self.modbus_client = None
BaseChannel.__init__(self, network, channel_name, channel_protocol, channel_params, channel_manager,
channel_type)
def run(self):
self.modbus_client = ModbusSerialClient(method='rtu',
port=self.port,
baudrate=self.baudrate,
stopbits=self.stopbits,
parity=self.parity,
bytesize=self.bytesize,
timeout=self.timeout)
try:
self.modbus_client.connect()
logger.debug("连接串口成功.")
except Exception, e:
logger.error("连接串口失败,错误信息:%r." % e)
self.modbus_client = None
示例2: __init__
def __init__(self, remote, timeout=0.01):
if len(remote.split("."))==3:
#we probably have a TCP request
print "TCP connection to: ", remote
self.client=ModbusTcpClient(remote, 502)
self.__modbus_timeout=timeout
else:
if os.name!="posix" and timeout<0.03:
print "RS485 timeout too low, using 0.03 seconds"
self.__modbus_timeout=0.03
else:
self.__modbus_timeout=timeout
print "RS485 connection to: ", remote
self.client=ModbusSerialClient(method="rtu", port=remote, stopbits=1,bytesize=8,
parity="N",baudrate=38400, timeout=self.__modbus_timeout)
#print self.client.connect()
#motor tresholds, use default values unless a calibration file is loaded
self.neutral=125*np.ones(5, dtype='int8')
self.min_fwd=1*np.ones(5, dtype='int8')
self.min_bwd=-1*np.ones(5, dtype='int8')
self.motor_max=80#seems constant across all AUVs
#flag for motors mounted the wrong way
self.motor_spin=1*np.ones(5, dtype='int8')
#flag if the motors are calibrated
self.calib=False
#flag to exit watchdog thread
self.exit=False
self.alarms_byte=0
self.__status=[0 for _ in range(16)]
self.alarms_list=[[False]*12,
['Water ingress main compartment',
'Water ingress left battery',
'Water ingress right battery',
'Overheating',
'Low power',
'Over consumption',
'Maximum depth',
'Start error',
'SPI error',
'I2C error'
]]
self.rwlock=threading.Lock()
self.statuslock=threading.Lock()
self.__motors_values=[0,0,0,0,0]
self.modbus_write(1, 0xC000)#wtf ?!
print "rock'n roll baby"
#launch watchdog thread and exit __init__
threading.Thread(target=self.__keep_alive).start()
示例3: PyModbusClient
class PyModbusClient(BaseModbusClient):
def __init__(self, *args, **kwargs):
super(PyModbusClient, self).__init__(*args, **kwargs)
if self.method == "tcp":
from pymodbus.client.sync import ModbusTcpClient
self.client = ModbusTcpClient(self.host, self.port)
else:
from pymodbus.client.sync import ModbusSerialClient
argnames = ("stopbits", "bytesize", "parity", "baudrate", "timeout")
kwargs = dict((k, getattr(self, k)) for k in argnames)
kwargs.update({
"port": self.host,
})
self.client = ModbusSerialClient(self.method, **kwargs)
def read_coils(self, address, count):
resp = self.client.read_coils(address, count, unit=self.unit)
if resp is None:
raise NoDeviceResponse()
return resp.bits[:count]
def write_coil(self, address, value):
resp = self.client.write_coil(address, int(value), unit=self.unit)
if resp is None:
raise NoDeviceResponse()
return resp.value
示例4: testSerialClientRecv
def testSerialClientRecv(self):
''' Test the serial client receive method'''
client = ModbusSerialClient()
self.assertRaises(ConnectionException, lambda: client._recv(1024))
client.socket = mockSocket()
self.assertEqual('', client._recv(0))
self.assertEqual('\x00'*4, client._recv(4))
示例5: testSerialClientSend
def testSerialClientSend(self):
''' Test the serial client send method'''
client = ModbusSerialClient()
self.assertRaises(ConnectionException, lambda: client._send(None))
client.socket = mockSocket()
self.assertEqual(0, client._send(None))
self.assertEqual(4, client._send('1234'))
示例6: testSerialClientSend
def testSerialClientSend(self, mock_serial):
''' Test the serial client send method'''
mock_serial.in_waiting = None
mock_serial.write = lambda x: len(x)
client = ModbusSerialClient()
self.assertRaises(ConnectionException, lambda: client._send(None))
# client.connect()
client.socket = mock_serial
self.assertEqual(0, client._send(None))
self.assertEqual(4, client._send('1234'))
示例7: testSerialClientConnect
def testSerialClientConnect(self):
''' Test the serial client connection method'''
with patch.object(serial, 'Serial') as mock_method:
mock_method.return_value = object()
client = ModbusSerialClient()
self.assertTrue(client.connect())
with patch.object(serial, 'Serial') as mock_method:
mock_method.side_effect = serial.SerialException()
client = ModbusSerialClient()
self.assertFalse(client.connect())
示例8: SerialRtuChannel
class SerialRtuChannel(BaseChannel):
def __init__(self, channel_params, devices_file_name, protocol, mqtt_client, network_name):
BaseChannel.__init__(self, channel_params, devices_file_name, protocol, mqtt_client, network_name)
# 配置项
self.port = channel_params.get("port", "")
self.baund = channel_params.get("baund", 9600)
self.stopbits = channel_params.get("stopbits", serial.STOPBITS_ONE)
self.parity = channel_params.get("parity", serial.PARITY_NONE)
self.bytesize = channel_params.get("bytesize", serial.EIGHTBITS)
self.timeout = channel_params.get("timeout", 2)
self.protocol.set_device_info(self.port, self.baund)
# modbus通信对象
self.modbus_client = ModbusSerialClient(method='rtu',
port=self.port,
baudrate=self.baund,
stopbits=self.stopbits,
parity=self.parity,
bytesize=self.bytesize,
timeout=self.timeout)
@staticmethod
def check_config(channel_params):
if "port" not in channel_params or "baund" not in channel_params:
return False
return BaseChannel.check_config(channel_params)
def run(self):
# 首先上报设备数据
for device_id in self.devices_info_dict:
device_info = self.devices_info_dict[device_id]
device_msg = {
"device_id": device_info["device_id"],
"device_type": device_info["device_type"],
"device_addr": device_info["device_addr"],
"device_port": device_info["device_port"],
"protocol": self.protocol.protocol_type,
"data": ""
}
self.mqtt_client.publish_data(device_msg)
try:
self.modbus_client.connect()
logger.debug("连接串口成功.")
except Exception, e:
logger.error("连接串口失败,错误信息:%r." % e)
self.modbus_client = None
return
while True:
# 该线程保持空转
time.sleep(5)
示例9: __init__
def __init__(self, *args, **kwargs):
super(PyModbusClient, self).__init__(*args, **kwargs)
if self.method == "tcp":
from pymodbus.client.sync import ModbusTcpClient
self.client = ModbusTcpClient(self.host, self.port)
else:
from pymodbus.client.sync import ModbusSerialClient
argnames = ("stopbits", "bytesize", "parity", "baudrate", "timeout")
kwargs = dict((k, getattr(self, k)) for k in argnames)
kwargs.update({
"port": self.host,
})
self.client = ModbusSerialClient(self.method, **kwargs)
示例10: main
def main(host, port, mqtt_username, mqtt_password, instance, name, serial_port):
modbus = ModbusClient(method='rtu', port=serial_port, baudrate=9600, timeout=1)
if not modbus.connect():
logger.error("Cannot connect to modbus")
return
client = mqtt.Client()
client.loop_start()
client.connect(host, port, 60)
if mqtt_username is not None:
client.username_pw_set(mqtt_username, mqtt_password)
try:
while True:
now = int(time())
r = modbus.read_holding_registers(0, 16, unit=1)
bat_volt = r.registers[8] * 96.667 * 2**(-15)
bat_curr = r.registers[11] * 316.67 * 2**(-15)
bat_temp = r.registers[15]
client.publish('{}/{}/power'.format(instance, name), "{} {:0.2f}".format(now, bat_volt * bat_curr), 0)
client.publish('{}/{}/voltage'.format(instance, name), "{} {:0.2f}".format(now, bat_volt), 0)
client.publish('{}/{}/current'.format(instance, name), "{} {:0.2f}".format(now, bat_curr), 0)
client.publish('{}/{}/temperature'.format(instance, name), "{} {}".format(now, bat_temp), 0)
sleep(5)
except KeyboardInterrupt:
pass
client.disconnect()
client.loop_stop()
modbus.close()
示例11: main
def main(args):
global PUMP_TIME
global SENSOR_TIME
try:
PUMP_TIME = int(args[1])
SENSOR_TIME = int(args[2])
print('using custom args. pump time: %d sensor time: %d' % (PUMP_TIME, SENSOR_TIME))
except:
PUMP_TIME = 3
SENSOR_TIME = 5
print('using default args. pump time: %d sensor time: %d' % (PUMP_TIME, SENSOR_TIME))
startMeasurement()
# Connect to sensor and record data
try:
client = ModbusClient(method = "rtu", port="/dev/ttyS0",stopbits = 1, bytesize = 8, parity = 'N', baudrate= 9600)
# Connect to the serial modbus server
connection = client.connect()
if connection:
recordData(client)
# Closes the underlying socket connection
client.close()
except Exception as error:
print('CO2 measurement failed: ' + repr(error))
finally:
endMeasurement()
示例12: run
def run(self):
global tCtrl
_sample=select(tCtrl.samples,'id',self.id)
_protocol=select(tCtrl.protocols,'id',_sample.properties['protocol_id'])
_transport=select(tCtrl.transports,'id',_sample.properties['transport_id'])
_rule=select(tCtrl.rules,'id',_sample.properties['rule_id'])
_method=_protocol.properties['method']
_port=_transport.properties['port']
_para=_transport.properties['para']
_timeout=int(_transport.properties['timeout'])/1000.0
client = ModbusClient(method=_method, port=_port,baudrate= \
Baudrate(_para),bytesize=Bytesize(_para),parity=Parity(_para),\
stopbits=Stopbits(_para),timeout=_timeout)
_index=int(_rule.properties['index'])
_count=int(_rule.properties['count'])
_unit_begin=Begin(_rule.properties['range'])
_unit_end=End(_rule.properties['range'])
client.connect()
self.interval = int(_protocol.properties['period'])
while not self.thread_stop:
for i in range(_unit_begin,_unit_end):
start_ = datetime.utcnow()
response=client.read_holding_registers(address=_index, \
count=_count,unit=i)
tCtrl.samples[self.index].data[i]=response.registers
print response.registers #getRegister(1)/10.0
end_ = datetime.utcnow()
print '[cost time] %s' %(end_-start_)
time.sleep(self.interval)
示例13: ModbusClient
def pa
#---------------------------------------------------------------------------#
#---------------------------------------------------------------------------#
# configure the client logging
#---------------------------------------------------------------------------#
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)
for port in ['/dev/ttyxuart3']:
client = ModbusClient(method='rtu', port=port, baudrate=9600, timeout=1, retries=1)
client.connect()
try:
for addr in [3,10]:
# for addr in xrange(10,15):
print ('Meter Modbus Address: %d' % addr)
# regs = client.read_holding_registers(768,120,unit=addr); print regs.registers if regs else None
# regs = client.read_holding_registers(128,4,unit=addr); print regs.registers if regs else None
regs = client.read_holding_registers(142,8,unit=addr); print regs.registers if regs else None
for addr in xrange(5,9):
print ('Inverter Modbus Address: %d' % addr)
regs = client.read_holding_registers(33,10,unit=addr); print regs.registers if regs else None
except AttributeError, e:
print 'Device not responding'
finally:
示例14: connect
def connect():
try:
client = None
client = ModbusClient(retries = 0, method='rtu', port='/dev/ttyUSB1', baudrate=38400, stopbits=1, parity='N', bytesize=8, timeout=1)
client.connect()
return client
except Exception as e:
print "Error while connecting client: \n"+e.__str__()
示例15: __init__
def __init__(self):
ModbusClient.__init__(self,method='rtu')
self.port=0
self.baudrate=9600
self.bytesize=8
self.parity="E"
self.stopbits=1
self.timeout=1
self.connect()
self.unit=1 #slave address
self.nms={"pv":0x3,"sv":0x2,}