コード例 #1
0
def configure_modbus_client():
    client = ModbusClient('192.168.1.5', port=1502)
    client.connect()
    return client
コード例 #2
0
ファイル: process.py プロジェクト: arvindh123/Py-ModToMq
def Mod_ReadWrite(ModConn, ModStatChild):
    mod = modbus_parameters.query.get(1)
    
    PubTopics = pub_mqtt_topics.query.filter(pub_mqtt_topics.mod_addresses.any(read_mod_registers.address >= 0)).all()

    try:
        while True:
            if is_connected(mod.modbus_ip,mod.modbus_port):
                ModStatChild.send("Modbus device Connection is UP")
                logger.info("Modbus device Connection is UP")
                break
            else:
                ModStatChild.send("Modbus device connection is  DOWN")
                logger.error("Modbus device connection is  DOWN")
                time.sleep(10)
        Modclient = ModbusClient(mod.modbus_ip, port = mod.modbus_port)
        msg = 0        
        while True :
            
            if ModStatChild.poll():
                msg = ModStatChild.recv()
                print("received Msg in modbus outer while loop {}".format(msg))
                logger.info("received Msg in modbus outer while loop {}".format(msg))
            if msg == 1:
                Modclient.connect()
                ModStatChild.send("Connected to Modbus device")
                logger.info("Connected to Modbus device")
                msg = 2
            while msg  == 2:
                # GetModValues = ModReadJson(Modclient, 0 , 10) 
                for topic in PubTopics:
                    GetModValues = ModReadTopic(Modclient,topic)
                    #########################
                    ModConn.send(GetModValues)
                    #########################
                    # print(GetModValues)
                time.sleep(0.5)
                if ModStatChild.poll():
                    msg = ModStatChild.recv()
                    if msg == 1 :
                        print("received Msg in modbus inner while loop {}".format(msg))
                        logger.info("received Msg in modbus inner while loop {}".format(msg))
                        msg = 2
                        ModStatChild.send("Modbus device data Acquisition already running")
                    
            while msg == 3 :
                Modclient.close()
                msg = 0
                ModStatChild.send("Modbus device connection Closed")
                
            # FlModChild.send("Disconnected from Controller")
        # FlModChild.send(GetModValues)
        # if ModConn.poll():
        #     msg = ModConn.recv()
        #     if isinstance(msg, dict):
        #         if "ModWrite" in msg:
        #             if msg["ModWrite"] == True:
        #                 ModWriteJson(ModbusClient,msg)
    except Exception as e:
        ModStatChild.send("Modbus Disconnected, Modbus process Stopped")
        ModStatChild.send(str(e))
        print(e)
############------------------------------------------------------################
コード例 #3
0
import pymodbus
import serial
import json
from pymodbus.pdu import ModbusRequest
from pymodbus.client.sync import ModbusSerialClient as ModbusClient

#initialize a serial RTU client instance
from pymodbus.transaction import ModbusRtuFramer

myUnit = 0x1B

#connect with modbus
client = ModbusClient(method='rtu',
                      port='/dev/ttyUSB0',
                      stopbits=2,
                      bytesize=8,
                      timeout=1,
                      baudrate=38400)
connection = client.connect()
print(connection)

#starting add, num of reg to read, slave unit.
result = client.read_holding_registers(298, 2, unit=myUnit)
print(result.registers[0])
print(result.registers)

debug = True
#enable hardware handshake IMPORTANT
client.socket.rtscts = True

reg = client.read_holding_registers(208, 1, unit=myUnit)
コード例 #4
0
         f.write(data)
def write_csv_header(csv_file, header):
    with open(csv_file, 'a') as f:
        f.write(header)
def write_csv_header(csv_file, header):
    with open(csv_file, 'a') as f:
        f.write(header)
params_recorded =  "Forward Volumetric Flow (m3/hr), FV Totalizer (m3/hr), Reverse Volumetric Flow (m3/hr), RV Totalizer (m3/hr), Velocity (m/sec), Forward Mass Flow, Forward Mass Totalizer, Reverse Mass Flow, Reverse Mass Totalizer"

DATA_PATH = r"C:\Users\Sajal Sirohi.DESKTOP-RTVGPUA\Desktop\Flow sensor project"
no_of_meters = 4
meter_id = 1
lim = 0

try:
    client = ModbusClient(method="rtu", port="COM5", stopbits=1, bytesize=8, parity='N', baudrate=9600)
    connection = client.connect()
except:
    print("Unable to connect to the Com Port, Please try Again \n")

l= 1

answer = []
data_convert = []

while (l <= no_of_meters):
    csv_file_path = os.path.join(DATA_PATH, "flow_meter_id_" + str(l) + ".csv")
    if path.isfile(csv_file_path):
        break
    else:
        write_csv_header(csv_file_path, "Timestamp," +
import pymodbus
import serial
from pymodbus.pdu import ModbusRequest
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from pymodbus.transaction import ModbusRtuFramer

import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

client = ModbusClient(method="rtu",
                      port="/dev/ttyUSB2",
                      stopbits=1,
                      bytesize=8,
                      parity='E',
                      baudrate=9600)
connection = client.connect()

print(connection)

result = client.read_holding_registers(40101, 1, unit=1)
print(result)

client.close()
コード例 #6
0
#!/usr/bin/env python

from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.exceptions import ConnectionException
import logging

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)

#####################################
# Code
#####################################
client = ModbusClient('localhost', port=502)

try:
    client.connect()
    while True:
        rq = client.write_register(0x10, 1) # Run Plant, Run!
        rq = client.write_register(0x1, 0) # Level Sensor
        rq = client.write_register(0x2, 0) # Limit Switch
        rq = client.write_register(0x3, 1) # Motor
        rq = client.write_register(0x4, 1) # Nozzle
except KeyboardInterrupt:
    client.close()
except ConnectionException:
    print "Unable to connect / Connection lost"
コード例 #7
0
 def setUp(self):
     """ Initializes the test environment """
     super(Runner, self).setUp()
     self.client = ModbusClient()
コード例 #8
0
from pymodbus.client.sync import ModbusTcpClient as ModbusClient  # библиотека для работы по протоколу Modbus
from datetime import datetime
import time
import csv

a = 'Сумма цифр числа Фибоначчи №164'
b = 'Сумма цифр числа Фибоначчи №100'
c = 'Сумма цифр числа Фибоначчи №137'
d = 'Сумма цифр числа Фибоначчи №89'

x = 'Число високосных лет от 2020 и 10000 включительно'

client = ModbusClient('159.93.112.94',
                      port=1936)  # создание объекта client класса ModbusClient
status = client.connect()  # вызов функции подключения к устройству
# t = client.read_input_registers(0, 1, unit=1)                      # вызов функции чтения пяти регистров (начиная с 0) с устройства
# print(t.registers)                                                 # вывод считанных регистров в консоль

filename = round(time.time())

while True:
    row = {}
    time_now = datetime.now()
    t = client.read_input_registers(0, 1, unit=1).registers

    row['time'] = time_now
    row['t'] = t[0] / 100
    print(row)
    with open(f'{filename}.csv', 'a') as csv_file:
        writer = csv.DictWriter(csv_file,
                                delimiter=";",
コード例 #9
0
 def __init__(self) -> None:
     super().__init__()
     self.client = ModbusClient('192.168.1.92', port=502)
     self.client.connect()
     print("Connected")
コード例 #10
0
def main():
    """Main function.
    """

    # Create parser.
    parser = argparse.ArgumentParser()

    # Add arguments.
    parser.add_argument("--port",
                        type=str,
                        default="COM10",
                        help="Serial port.")
    parser.add_argument("--unit", type=int, default=1, help="Unit ID.")

    # Take arguments.
    args = parser.parse_args()

    # Get args.
    unit = args.unit
    port = args.port

    # Modbus thermometer.
    p_analyser = PowerAnalyser()

    # Create client.
    with ModbusClient(method="rtu",
                      port=port,
                      baudrate=2400,
                      timeout=1,
                      xonxoff=False,
                      rtscts=False,
                      dsrdtr=False) as client:

        params_names = p_analyser.get_parameters_names()

        #---------------------------------------------------------------------------#
        # Generate request.
        #---------------------------------------------------------------------------#
        requests = p_analyser.generate_requests(unit)

        #---------------------------------------------------------------------------#
        # Run thought device parameters.
        #---------------------------------------------------------------------------#
        for param_name in params_names:

            # Execute request for the given parameter.
            response = client.execute(requests[param_name])

            # Check the response.
            assert not response.isError(
            ), "Device did not respond properly to the request."

            # Get parameter by name
            parameter = p_analyser.get_parameter_by_name(param_name)

            # Convert register offset indexes.
            registers = convert_reg_offset(parameter.addresses,
                                           response.registers)

            # Convert registers to actual value.
            param_value = p_analyser.get_parameter_value(param_name, registers)

            print(response)
            print("Name: {}; Value: {:.2f}".format(param_name, param_value))
            print()
コード例 #11
0
def air_modbus2mongodb_next():
    try:
        t = time()

        DBclient = MongoClient('mongodb://192.168.1.10/',
                               username='******',
                               password='******',
                               authSource='admin',
                               serverSelectionTimeoutMS=2000)

        # try:  # 数据库连接测试
        #     # The ismaster command is cheap and does not require auth.
        #     DBclient.admin.command('ismaster')
        # except ConnectionFailure as e:  # Exception
        #     DBclient.close()
        #     log.error(e)
        #     # print("Server not available")
        #     return

        db = DBclient['sensor_management']
        # collection = db['air_condition']
        collection = db['data_test_ac_1223']
        logger = db['air_condition_logger_1223']

        equipments = [{} for i in range(len(ads.equipment_index))]
        for i in range(9):  # 9根总线读数据
            client = ModbusClient(ads.conn[i][0],
                                  port=ads.conn[i][1],
                                  timeout=3)
            bus = ads.buses[i]

            is_connected = client.connect()
            if not is_connected:  # modbus连接失败
                data_db = {
                    'name': 'bus{:0>1d}'.format(i + 1),
                    'err': 'Modbus Connect Failed',
                    'datetime': datetime.now()
                }
                result = logger.insert_one(data_db)
                client.close()
                sleep(1)
                continue

            for j in range(ads.bus_sensor_number[i]):
                rr = client.read_holding_registers(ads.rgs_start +
                                                   j * ads.rgs_len,
                                                   ads.len_data,
                                                   unit=ads.box_ads)
                if not hasattr(rr, 'registers'):  # 无返回数据
                    data_db = {
                        'name':
                        'bus{:0>1d}:'.format(i + 1) + ads.equipment_index[i] +
                        '-' + bus[j][1],
                        'message':
                        rr.message,
                        'err':
                        'No Data Return',
                        'datetime':
                        datetime.now()
                    }
                    result = logger.insert_one(data_db)
                    continue

                data_modbus = rr.registers
                type = data_modbus[0] // 256  # 数据类型
                if type != bus[j][2]:
                    data_db = {
                        'name':
                        'bus{:0>1d}:'.format(i + 1) + ads.equipment_index[i] +
                        '-' + bus[j][1],
                        'data':
                        data_modbus,
                        'err':
                        'Wrong Type Index: Should be 0x{:0X}, but accepted 0x{:0X}'
                        .format(bus[j][2], type),
                        'datetime':
                        datetime.now()
                    }
                    result = logger.insert_one(data_db)
                    continue
                pos = data_modbus[0] % 16  # 小数位数
                sign_n = data_modbus[0] % 256 - pos  ## 有无符号
                if sign_n == 0x80:
                    sign = True  # 有符号
                elif sign_n == 0x00:
                    sign = False  # 无符号
                else:
                    data_db = {
                        'name':
                        'bus{:0>1d}:'.format(i + 1) + ads.equipment_index[i] +
                        '-' + bus[j][1],
                        'data':
                        data_modbus,
                        'err':
                        'Wrong Sign Index: Should be 0x{:0X} or 0x{:0X}, but accepted 0x{:0X}'
                        .format(0x80, 0x00, sign_n),
                        'datetime':
                        datetime.now()
                    }
                    result = logger.insert_one(data_db)
                    continue

                data_origin = data_modbus[1]
                if sign and data_origin >= 32767:
                    data = -(65536 - data_origin) / (10**pos)
                else:
                    data = data_origin / (10**pos)

                # equipments[bus[j][1]] = data
                # equipments[ads.equipment_index[bus[j][0]]][bus[j][1]] = data
                equipments[bus[j][0]][bus[j][1]] = data
            client.close()

        for eqt in range(9):  # 9个设备写入数据库
            data_db = {
                'name': ads.equipment_index[eqt],
                'data': equipments[eqt],
                'datetime': datetime.now()
            }
            result = collection.insert_one(data_db)

        DBclient.close()
        log.info('Time Consuming: ' + str(time() - t))
    except Exception as e:
        # log.exception(e)
        # client.close()
        # DBclient.close()
        log.error(e)
        log.info('Time Consuming: ' + str(time() - t))
        return
コード例 #12
0
import sys
import logging

from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.payload import BinaryPayloadBuilder
from pymodbus.client.sync import ModbusSerialClient as ModbusClient

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)

# create connection (boot mode is 9600)
client = ModbusClient(method='rtu',
                      port='/dev/ttyUSB0',
                      baudrate=9600,
                      timeout=1.5)
client.connect()

idslave = 0x01

if len(sys.argv) == 2:
    try:
        idslave = int(sys.argv[1])
    except:
        print "usage: %s [idslave]" % sys.argv[0]
        sys.exit(-1)

print "modbus cmd: 0x01 value: 0x0000 length: 0x01\n"
result = client.write_register(address=0x0000,
                               value=0x0000,
コード例 #13
0
                    client.write_registers(int(inv_act_idxs_registers[i]), int(value[i]) , unit = id)
                    print('Quadrant change for inv:', inv_act_idxs_registers[i], 'to quadrant', value[i] )
        else:
            pass
        '''
    except Exception as e:
        print(e)

    finally:
        client.close()


IP = '131.243.41.14'
PORT = 504
x = 50
client = ModbusClient(IP, port=PORT)

#Pcmd_kVA = np.array([[x,x,x],[-x,-x,-x],[-x,-x,-x], [x,x,x], [0,0,0]]) #3 phase each array is a new iteration command
#Qcmd_kVA = np.array([[x,x,x],[x,x,x], [-x,-x,-x], [-x,-x,-x], [0,0,0]])
#Pact = np.array([[0,0,0],[x,x,x], [-x,-x,-x], [-x,-x,-x], [x,x,x]])
#Qact = np.array([[0,0,0],[x,x,x], [x,x,x], [-x,-x,-x], [-x,-x,-x]])
act_idxs = np.array([1, 2, 3])  #phases
Pcmd_kVA = np.array([x, x, x])
Qcmd_kVA = np.array([x, x, x])
Pact = np.array([0, 0, 0])
Qact = np.array([0, 0, 0])
#for i in range(len(Pcmd_kVA)):
modbustoOpal_quadrant(Pcmd_kVA[i], Qcmd_kVA[i], Pact[i], Qact[i], act_idxs,
                      client)
#print('wait 30 sec...')
#time.sleep(30)
コード例 #14
0
def get_b100_readings(address, port):
    """
    The B100 FogLAMP plugin module calls this function to get the readings for the device.

    The address should be the IP address of the B100
    The Modbus TCP port should usually be 502
    """

    # This global modbus_client object should allow us to leave a continuous Modbus
    # connection open
    global modbus_client

    # This will open the Modbus connection to the B100 the first time that we call get_b100_readings.
    # It will also reopen the connection if it has been closed
    if modbus_client is None:
        try:
            modbus_client = ModbusClient(address,
                                         port=port,
                                         framer=ModbusFramer)
        except ModbusIOException as ex:
            _LOGGER.exception(
                'Modbus I/O exception opening B100 connection: {}'.format(ex))
        except ParameterException as ex:
            _LOGGER.exception(
                'Modbus I/O exception opening B100 connection: {}'.format(ex))
        except ModbusException as ex:
            _LOGGER.exception(
                'Modbus exception opening B100 connection: {}'.format(ex))
        except Exception as ex:
            _LOGGER.exception(
                'Exception opening B100 connection: {}'.format(ex))

    # We are currently using the register values of the B100. If the SEL equipment acts as an intermediary then
    # the registers and unit will need to be changed to what the SEL equipment makes available. Make sure to update the
    # byte and word order and scaling value in decode_and_scale_registers if that changes as well.
    LTC_TANK_TEMP_REG = 216
    TOP_OIL_TEMP_REG = 268
    UNIT = 1
    SCALING_VALUE = 1000
    # In general you will always need to read two 16-bit register to get the 32-bit signed integer Modbus reading. This
    # will probably not change.
    NUM_REGISTERS_TO_READ = 2

    # Additional readings may be easily added here by getting additional modbus readings and adding them to the
    # readings object below
    ltc_tank_temp = None
    top_oil_temp = None

    ltc_tank_temp = get_modbus_reading('LTC Tank Temp', SCALING_VALUE,
                                       LTC_TANK_TEMP_REG,
                                       NUM_REGISTERS_TO_READ, UNIT)
    top_oil_temp = get_modbus_reading('Top Oil Temp', SCALING_VALUE,
                                      TOP_OIL_TEMP_REG, NUM_REGISTERS_TO_READ,
                                      UNIT)

    # This readings object returns the values to FogLAMP where they are embedded inside a FogLAMP reading object
    # containing the asset name, a timestamp, and a GUID. We may include any arbitrary set of readings in this
    # readings object including static meta-data, if desired.
    readings = {'ltc_tank_temp': ltc_tank_temp, 'top_oil_temp': top_oil_temp}

    # Return the readings object to the FogLAMP function plugin_poll function that called us.
    return readings
コード例 #15
0
ファイル: Ch1_OFF-ReleA.py プロジェクト: Alan050818/modbus
#!/usr/bin/env python

from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.transaction import ModbusRtuFramer

import pymodbus
import serial
from pymodbus.pdu import ModbusRequest

import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s '
          '%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import json, time
import inspect

client1 = ModbusClient('192.168.1.10', port=502, framer=ModbusRtuFramer)
client1.connect()

rq = client1.write_register(1, 512, unit=3)
rr = client1.read_holding_registers(1, 1, unit=3)
dassert(rq, lambda r: r.function_code < 0x80)
status = rr.registers[0]
print(status)
コード例 #16
0
ファイル: common.py プロジェクト: tost11/solar-controller
def getClient():
    return ModbusClient(method="rtu",
                        port="/dev/ttyUSB0",
                        baudrate=115200,
                        timeout=1)
コード例 #17
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#import serial
import time
#import pymodbus
#from pymodbus.pdu import ModbusRequest
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
#from pymodbus.transaction import ModbusRtuFramer
#import sys
import paho.mqtt.client as mqtt

mbclient = ModbusClient(method="rtu",
                        timeout=1,
                        port='/dev/ttyACM0',
                        stopbits=1,
                        bytesize=8,
                        parity='N',
                        baudrate=19200)
connection = mbclient.connect()
print(connection)
time.sleep(2)
result = mbclient.write_register(0, 20, unit=4)
print(result)
コード例 #18
0
#!/usr/bin/env python
from pymodbus.constants import Defaults
from pymodbus.client.sync import ModbusTcpClient as ModbusClient

Defaults.Timeout = 25
Defaults.Retries = 5
client = ModbusClient('ipaddress.of.venus', port='502')
client.write_register(807, 0)
コード例 #19
0
argnum=len(sys.argv)
if argnum < 4:
    print('use arguments: mba regadd count_or_datahex host:port_or_port')
    exit()
    
mba=int(sys.argv[1]) # mb aadress
regaddr=int(sys.argv[2]) # address to read or hex data to write
port=sys.argv[4]
print('port',port) # debug

if ":" in port:
    host=port.split(':')[0]
    port=int(port.split(':')[1])
    from pymodbus.client.sync import ModbusTcpClient as ModbusClient
    if (port <10000 or port > 10003): # tcp
        client = ModbusClient(host=host, port=port)
    else: # xport or barionet
        client = ModbusClient(host=host, port=port, framer=ModbusRtuFramer)
else:
    from pymodbus.client.sync import ModbusSerialClient as ModbusClient # using serial modbusRTU
    client = ModbusClient(method='rtu', stopbits=1, bytesize=8, parity='E', baudrate=19200, timeout=1, port=port)
    

if len(sys.argv[3]) == 4: # write 1 register
    regcount=int(sys.argv[3],16) # data, hex kujul
    print('writing single register data',regcount)
    cmd=6
elif len(sys.argv[3]) == 8: # write 2 registers
    regcount=str(sys.argv[3])
    lodata=int(regcount[4:],16)
    hidata=int(regcount[0:4],16)
コード例 #20
0
 def setUp(self):
     ''' Initializes the test environment '''
     self.initialize(
         ["../tools/reference/diagslave", "-m", "tcp", "-p", "12345"])
     self.client = ModbusClient(port=12345)
コード例 #21
0
    def initModbus(self):

        self.modbusClient = ModbusClient(MODBUS_SERVER_IP,
                                         port=MODBUS_SERVER_PORT)
コード例 #22
0
ファイル: scanner.py プロジェクト: jsloane/solar-logger
            if 'exception_code' in vars(result):
                break
            time.sleep(0.1)
            continue
    return result


ip = config.inverter_ip
PortN = config.inverter_port
num_reg = 29000
nb_reg = 1
UnitID = 0
j = 0

print("openning")
client = ModbusClient(host=ip, port=PortN, timeout=5)
time.sleep(1)
print(time.strftime("%a, %d %b %Y %H:%M:%S"))
if client.connect():
    time.sleep(2)
    i = num_reg - 1
    while (i < 30000):
        i += 1
        #       print("trying " + str(i))
        result = read_holding(client, UnitID, i, 1)
        try:
            j = result.registers[0]
            print("reading " + str(i) + " 1")
            print(result.registers)
            continue
        except Exception as Error:
コード例 #23
0
    dbClient.ping()
    dbClientConnected = True
except:
    dbClientConnected = False
    print("Not connected to InfluxDB")

try:
    mqttClient = mqtt.Client()
    mqttClient.username_pw_set(mqttUsername, mqttPassword)
    mqttClient.connect(mqttHost, mqttPort, 60)
except:
    print("Not connected to MQTT")

chargeStationModbus = ModbusClient(chargeStationIP,
                                   port=502,
                                   unit_id=1,
                                   auto_open=True,
                                   auto_close=True)
print("Connected to chargingStation: {}".format(chargeStationModbus.connect()))


def limitChargeStationCurrent(num,
                              minimum=minimumCurrent,
                              maximum=maximumCurrent):
    return max(min(num, maximum), minimum)


def changeChargeStationCurrent(current):
    builder = BinaryPayloadBuilder(byteorder=Endian.Big, wordorder=Endian.Big)
    builder.add_32bit_float(limitChargeStationCurrent(current))
    registers = builder.to_registers()
コード例 #24
0
    result = cursor.fetchall()
    avg = result[0][0]

    query3 = 'delete from test1 where Location = ' + str(merge_loc)
    cursor.execute(query3)
    db.commit()

    query4 = query = (
        """insert into test1(Date_and_Time, Temperature, Target_Time, Status, Location) values (%s,%s,%s,%s,%s)""",
        (merge_date, avg, merge_target, merge_status, merge_loc))
    cursor.execute(query4)
    db.commit()


#Modbus Connection initialise
client = ModbusClient(host='192.168.178.10',
                      port=502)  ##Modbus connection establish
client.connect()
client.write_registers(0, [0] * 10)  ##Open Connection

#mode :Store = 0, Unstore = 1
while True:
    while True:
        merge_rows()
        statusupdate()
        mode = mode_selection()  ##result of the mode query
        if mode == 0:
            while True:
                xStartRec = read_register(3)
                if xStartRec == 0:
                    break
            temp = sensor_read()
コード例 #25
0
from time import sleep

# from pymodbus.client.sync import ModbusUdpClient as ModbusClient
# from pymodbus.client.sync import ModbusSerialClient as ModbusClient

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

UNIT = 0x1
# Set.TransactionId = 0x1500
# Set.ProtocolId = 0

try:
    client = ModbusClient('192.168.1.146',
                          port=12345,
                          timeout=3,
                          framer=ModbusFramer)  #
    # from pymodbus.transaction import ModbusRtuFramer
    # client = ModbusClient('localhost', port=5020, framer=ModbusRtuFramer)
    # client = ModbusClient(method='binary', port='/dev/ptyp0', timeout=1)
    # client = ModbusClient(method='ascii', port='/dev/ptyp0', timeout=1)
    # client = ModbusClient(method='rtu', port='COM2', timeout=1,
    #                       baudrate=115200)
    # client = ModbusClient(method='rtu', port='COM2', timeout=1, baudrate=115200)
    is_connected = client.connect()

    # log.debug("Write to a Coil and read back")
    # rq = client.write_coil(0, True, unit=UNIT)
    # rr = client.read_coils(0, 1, unit=UNIT)
    # assert(not rq.isError())     # test that we are not an error
    # assert(rr.bits[0] == True)          # test the expected value
コード例 #26
0
CP_ADDR = 0x01
GEO_ADDR = 0x04

#---------------------------------------------------------------------------#
# configure the client logging
#---------------------------------------------------------------------------#
import logging
import csv
import os.path
import datetime

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.ERROR)

client = ModbusClient('10.0.0.17', port=502)
client.connect()

outputFolder = '/tmp/'

#---------------------------------------------------------------------------#
# CSV stuff
#---------------------------------------------------------------------------#

# REMEMBER! to create the folder and set the access rights to write:
# chmod a+w /var/cts700/
csvPath = "/var/cts700/"
csvPrefix = "cts700-"
fileName = csvPrefix + datetime.datetime.now().strftime("%Y-%m-%d") + ".csv"

allLabels = ["Timestamp"]
コード例 #27
0
ファイル: modbusMaster.py プロジェクト: rohitrgupta/emsrouter
    def run(self):
        self.load_db()
        #print(self.servers)
        start_timer = datetime.now()
        #ref_time=time.time()
        
        client = ModbusClient(self.server_ip, port=self.server_port)
        print("Modbus Connecting to :",self.server_ip, self.server_port)
        while not self.exit.is_set():
            #time.sleep(5.0 - ((time.time() - ref_time) % 5.0))
            # run this loop for each server in the self.servers
            for s in self.servers:
                print("Run for server", s, self.servers[s])
                start = self.servers[s]["start_address"]
                query_start = self.servers[s]["start_address"]
                query_size = self.servers[s]["query_size"]
                block_end = query_start + self.servers[s]["block_length"]
                modbus_unit = self.servers[s]["unit"]
                query_interval = self.servers[s]['interval'] * 1000
                sections = self.sections[s]
                query_continue = True
                error_count = 0
                while query_continue and error_count < 5:
                    self.wait_for_next_query()
                    #time.sleep(.05)
                    #aft = datetime.now()
                    #print("Previous query ",  start_timer , "This time ", aft)
                    #delay = query_interval - (aft - start_timer).microseconds
                    #if delay > 0:
                    #    time.sleep(delay/ 1000000.0 )
                    #else:
                    #    time.sleep(.1)
                    #new_start_timer = datetime.now()

                    #if start + query_size < total_length:
                    #query_length = self.get_query_length(start, query_size, sections)
                    query_length = self.get_query_length(query_start, block_end, start, query_size, sections)
                    #else:
                    #    query_length = total_length - start
                    if query_length == 0:
                        print("&&&&&&&&&&&&&&&&&&&&&&&",s)
                        query_continue = False
                        continue

                    #print("Modbus query",start_timer, modbus_unit, query_start, query_length, block_end, s)
                    print("Modbus query",start, query_length, block_end, s)
                    try:
                        rr = client.read_holding_registers(start, query_length, unit=modbus_unit)
                    except:
                        print("error in read_holding_registers call", start, query_length, modbus_unit)
                        error_count+=1
                        continue
                    #print("RR value", rr, s, self.servers[s])
                    #self.start_timer = self.new_start_timer
                    t_recv = time.time()
                    ## add error handling code for response
                    #print(rr, register_range)
                    try:
                        data = copy.copy(rr.registers)
                        #print("Data", len(data))
                    except:
                        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t_recv)), "error in reading modbus ", error_count, modbus_unit,  rr)
                        error_count+=1
                        continue
                    #print("converting")
                    d2 = self.convert_format(query_start, block_end, data, sections, start, query_length)
                    #print("              d2", d2)
                    #print("sending dara from modbus")
                    #logging.debug("Sending:%f",t_recv)
                    k = (s, start, query_length)
                    print("Modbus sending               k", k, len(d2) )
                    self.modbus_q.put([t_recv, k, d2])
                    start = start + query_length
                    if start >= block_end:
                        start = 0
                        query_continue = False
                    logging.info("modbusMaster %d Run loop", self.servers)
        #print(self.servers)
        logging.warning("modbusMaster %s Exit loop", str(self.servers))
        return
コード例 #28
0
            client.close()
    except:
        print("Please check the used tty device")
        raise

    #stopTs = time.time()
    #timeDiff = stopTs - startTs
    #print "\nTime execution %s sec" % timeDiff

    # Delay 1 second the recall  scheduler.enterabs(time, priority, action, argument)
    local_handler.enterabs(t + 0.1, 1, readRegister, (local_handler, t + 0.1))


try:
    #startTs = time.time()

    # Connect to the device via modbus
    client = ModbusClient(method=methName,
                          port=portName,
                          stopbits=stpBits,
                          baudrate=baudSpeed)
    handler = sched.scheduler(time.time, time.sleep)
    t = time.time()

    # Indicate the schedule function  scheduler.enter(delay, priority, action, argument)
    handler.enter(0, 1, readRegister, (handler, t))
    handler.run()

except:
    print("Process was stoped unexpectedly ")
コード例 #29
0
ファイル: custom-message.py プロジェクト: krtk30/pymodbus
        if not context.validate(self.function_code, self.address, self.count):
            return self.doException(merror.IllegalAddress)
        values = context.getValues(self.function_code, self.address, self.count)
        return CustomModbusResponse(values)

#---------------------------------------------------------------------------# 
# This could also have been defined as
#---------------------------------------------------------------------------# 
from pymodbus.bit_read_message import ReadCoilsRequest

class Read16CoilsRequest(ReadCoilsRequest):

    def __init__(self, address):
        ''' Initializes a new instance

        :param address: The address to start reading from
        '''
        ReadCoilsRequest.__init__(self, address, 16)

#---------------------------------------------------------------------------# 
# execute the request with your client
#---------------------------------------------------------------------------# 
# using the with context, the client will automatically be connected
# and closed when it leaves the current scope.
#---------------------------------------------------------------------------# 
with ModbusClient('127.0.0.1') as client:
    request = CustomModbusRequest(0)
    result = client.execute(request)
    print result

コード例 #30
0
ファイル: spc.py プロジェクト: Abishek1808/FA
link_toGetUrl="http://www.flsevoii.com:3093/api/getdata?sid=0"
link_toFetchReqUrl="http://www.flsevoii.com:3093/api/FD?sid=0&"
link_toPostFetchUrl="http://www.flsevoii.com:3093/api/FDD/0"
link_toSendMasterurl="http://www.flsevoii.com:3093/api/MD?sid=0&"

eC=[1,2,4,8]
errorCode=[None]*len(eC)
for i in range (len(eC)):
    errorCode[i]=hex(eC[i])
porta='COM4'
baudratea= 9600
ID=1


#client = ModbusClient(method='rtu', port=porta,timeout=2, parity='E', stopbits=1, baudrate=9600, unit=1)
client = ModbusClient('localhost', port=502, timeout=1, parity='N', baudrate=9600, unit=1)

now = datetime.datetime.now()
sendTime = now.replace(hour=23, minute=45, second=0, microsecond=0)

def getmodbusData(rL):
    client.connect()
    rr = client.read_holding_registers(1, rL, unit=1)
    if not hasattr(rr,'registers'):
        print ('recurring---')
        time.sleep(4)
        getmodbusData(rL)
    client.close()
    return rr.registers

def bytes(num):