Пример #1
0
    def test_tcp_client_connect(self):
        """ Test the tcp client connection method"""
        with patch.object(socket, 'create_connection') as mock_method:
            mock_method.return_value = object()
            client = ModbusTcpClient()
            self.assertTrue(client.connect())

        with patch.object(socket, 'create_connection') as mock_method:
            mock_method.side_effect = socket.error()
            client = ModbusTcpClient()
            self.assertFalse(client.connect())
Пример #2
0
 def __init__(self, sh, *args, **kwargs):
     self.logger = logging.getLogger(__name__)
     self._helios_ip = self.get_parameter_value('helios_ip')
     self._client = ModbusTcpClient(self._helios_ip)
     self.alive = False
     self._is_connected = False
     self._update_cycle = self.get_parameter_value('update_cycle')
Пример #3
0
def display_remote_io(ip_address):
    '''
    display remote I/O information at the given IP address
    '''
    try:
        client = ModbusTcpClient(ip_address)
        client.write_coil(HW_CY_006, False)

        ip_holding_regs = client.read_holding_registers(HR_CI_006_CV, 6)

        client.write_registers(HW_CI_006_PV, ip_holding_regs.registers)
        cur_ip = format_modbus_ip_address(ip_holding_regs.registers[0],
                                          ip_holding_regs.registers[1])
        cur_gateway = format_modbus_ip_address(ip_holding_regs.registers[2],
                                               ip_holding_regs.registers[3])
        cur_subnet = format_modbus_ip_address(ip_holding_regs.registers[4],
                                              ip_holding_regs.registers[5])

        ip_holding_regs = client.read_holding_registers(HR_CI_009_CV, 4)
        cur_mac = format_mac(ip_holding_regs.registers)
        ip_holding_regs = client.read_holding_registers(HR_KI_003, 2)
        cur_version = format_version(ip_holding_regs.registers[0])

        print("{0} - {1}, version:{2}.{3}.{4} ".format(
            ip_address, device_type_name(ip_holding_regs.registers[1]),
            cur_version[1], cur_version[2], cur_version[3]),
              end='')
        print("gateway:{0}, subnet:{1} mac:{2}".format(cur_gateway, cur_subnet,
                                                       cur_mac))
        client.close()
    except ConnectionException:
        print("{0} - unavailable".format(ip_address))
Пример #4
0
    def test_tcp_client_recv(self):
        """ Test the tcp client receive method"""
        client = ModbusTcpClient()
        self.assertRaises(ConnectionException, lambda: client.receive(1024))

        client.socket = MockSocket()
        self.assertEqual('', client.receive(0))
        self.assertEqual('\x00' * 4, client.receive(4))
Пример #5
0
    def test_tcp_client_send(self):
        """ Test the tcp client send method"""
        client = ModbusTcpClient()
        self.assertRaises(ConnectionException, lambda: client.send(None))

        client.socket = MockSocket()
        self.assertEqual(0, client.send(None))
        self.assertEqual(4, client.send('1234'))
Пример #6
0
    def __init__(self, address, port=502, logger=None):
        if not logger:
            self.logger = logging.getLogger(__name__)
            self.logger.setLevel(logging.ERROR)
        else:
            self.logger = logger

        self.address = address
        self.client = ModbusTcpClient(address, port)
Пример #7
0
 def __init__(self, ip_address, port):
     if ip_address is not None or port is not None:
         if MODBUS_BACKEND == PYMODBUS3:
             self._client = ModbusTcpClient(ip_address, port=port)
         if MODBUS_BACKEND == UMODBUS:
             self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             self._sock.settimeout(2)  # seconds
             self._sock.connect((ip_address, port))
     super(COMx, self).__init__(com=self, registration_number=0)
Пример #8
0
    def __init__(self, sh):
        from bin.smarthome import VERSION
        if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5':
            self.logger = logging.getLogger(__name__)

        self._helios_ip = self.get_parameter_value('helios_ip')
        self._client = ModbusTcpClient(self._helios_ip)
        self.alive = False
        self._is_connected = False
        self._update_cycle = self.get_parameter_value('update_cycle')
Пример #9
0
    def connect(self):
        """Connect to target MODBUS server.

        """
        try:
            self.client = ModbusTcpClient(self.config['ip_add'])
            self.client.connect()
            self.connected = True
        except:
            print('MODBUS CLIENT:', self.process_name,
                  '-- unable to connect to target server.')
Пример #10
0
def runModBus(IOVariables):
    client = ModbusTcpClient('192.168.1.9')
    Digital_Out_1 = ModbusDigitalOutputIOCard(2048, client, IOVariables)          
    try:
        Digital_Out_1.WriteStatus()
    except ConnectionException:
        print('A connection error to the modbus occured at {}'.format(
            datetime.datetime.now()
            )
        )
        pass
    client.close()      
Пример #11
0
    def setRelayState(interlock: Interlock_model,
                      state: {0, 1}) -> Interlock_model.State:

        client = ModbusTcpClient(interlock.card.server)
        client.connect()
        client.write_coil(interlock.channel, state, unit=1)
        sleep(0.3)
        reply = client.read_coils(interlock.channel, 1, unit=1)
        state = reply.bits[0]
        client.close()
        if state == ModbusInterlock.MODBUS_OFF:
            return Interlock_model.State.LOCKED
        elif state == ModbusInterlock.MODBUS_ON:
            return Interlock_model.State.UNLOCKED
Пример #12
0
def read_sensors(request):
    sensors = Sensor.objects.all()
    sensor_data = []
    dictionary = {}
    for sensor in sensors:
        client = ModbusTcpClient(sensor.address.server, port=502, timeout=1)
        try:
            client.connect()
            if sensor.sensor_type == Sensor.SensorType.DIGITAL:
                reply = client.read_discrete_inputs(sensor.channel, 1, unit=1)
                sensor_reading = reply.bits[0]
                sensor_response = {
                    'sensor_name': sensor.name,
                    'sensor_reading': sensor_reading
                }
                if sensor.digital_sensor_alert and sensor.email and str(
                        sensor_reading) != sensor.last_value:
                    if sensor.digital_alert_value and sensor_reading:
                        send_sensor_alert_email(sensor, str(sensor_reading))
                        #send_sensor_alert_email()
                    elif not sensor.digital_alert_value and not sensor_reading:
                        send_sensor_alert_email(sensor, str(sensor_reading))
                        #send_sensor_alert_email()
            else:
                reply = client.read_input_registers(sensor.channel, 1, unit=1)
                sensor_reading = round(
                    reply.registers[0] * sensor.conversion_factor, 2)
                if sensor.high_alert_value and sensor.email:
                    if sensor_reading > sensor.high_alert_value and float(
                            sensor.last_value) <= sensor.high_alert_value:
                        send_sensor_alert_email(sensor, str(sensor_reading))
                        #send_sensor_alert_email()
                if sensor.low_alert_value and sensor.email:
                    if sensor_reading < sensor.low_alert_value and float(
                            sensor.last_value) >= sensor.low_alert_value:
                        send_sensor_alert_email(sensor, str(sensor_reading))
                        #send_sensor_alert_email()
            sensor.last_value = str(sensor_reading)
            sensor.save()
            client.close()
        except:
            sensor_reading = "Could Not Connect"
        sensor_response = {
            'sensor_name': sensor.name,
            'sensor_reading': sensor_reading
        }
        sensor_data.append(sensor_response)
        client.close()
    dictionary['sensor_data'] = sensor_data
    return render(request, 'sensors/sensor_data.html', dictionary)
Пример #13
0
def get_1wire_config(ip_address):
    try:
        client = ModbusTcpClient(ip_address)

        wire_config = []
        for i in range(MAX_1WIRE):
            holding_regs = client.read_holding_registers(
                HR_TI_001_ID_H + i * 4, 4)
            cur_uuid = format_uuid(holding_regs.registers)
            holding_regs = client.read_holding_registers(HR_TI_001 + i, 1)
            wire_config.append(
                [i, cur_uuid, i,
                 to_signed(holding_regs.registers[0]) / 10.0])

        client.close()
        return wire_config
    except ConnectionException:
        print("{0} - unavailable".format(cuip))
Пример #14
0
        def __init__(self):
            if (self.logger == None):
                self.createLogger('generalPLCgateway')
            if len(self.plc_host) > 1:
                plc_client = ModbusTcpClient(self.plc_host)
            try:
                if len(self.plc_host) > 1:
                    result = plc_client.read_holding_registers(0, 5, unit=0X01)
                    if len(result.registers) == 5:
                        print("Gateway connected succesfully to PLC : " +
                              str(result))
                #self.update_conected_plc(self.plc_host)

                else:
                    print("connection is terminated ")
                    self.logger.error("connection is terminated ")
            except Exception as e:
                print("error sending data to PLC " + str(e))
                self.logger.error("error sending data to PLC " + str(e))
Пример #15
0
def write_network_config(cuip, aip, agw, asn, amac):
    try:
        client = ModbusTcpClient(cuip)
        client.write_register(HW_CI_006_PV, aip >> 16)
        client.write_register(HW_CI_006_PV + 1, aip & 0xffff)
        client.write_register(HW_CI_007_PV, agw >> 16)
        client.write_register(HW_CI_007_PV + 1, agw & 0xffff)
        client.write_register(HW_CI_008_PV, asn >> 16)
        client.write_register(HW_CI_008_PV + 1, asn & 0xffff)

        client.write_register(HW_CI_009_PV, 0)
        client.write_register(HW_CI_009_PV + 1, amac >> 32)

        client.write_register(HW_CI_009_PV + 2, (amac & 0xFFFFFFFF) >> 16)
        client.write_register(HW_CI_009_PV + 3, (amac & 0xFFFFFFFF) & 0xffff)
        client.write_coil(HW_CY_006, True)
        client.close()
    except ConnectionException:
        print("{0} - unavailable".format(cuip))
Пример #16
0
    def test_basic_sync_tcp_client(self):
        """ Test the basic methods for the tcp sync client"""

        # receive/send
        client = ModbusTcpClient()
        client.socket = MockSocket()
        self.assertEqual(0, client.send(None))
        self.assertEqual(1, client.send('\x00'))
        self.assertEqual('\x00', client.receive(1))

        # connect/disconnect
        self.assertTrue(client.connect())
        client.close()

        # already closed socket
        client.socket = False
        client.close()

        self.assertEqual("127.0.0.1:502", str(client))
Пример #17
0
def runModBus(IOVariables):
    #---------------------------------------------------------------------------#
    # choose the client you want
    #---------------------------------------------------------------------------#
    # make sure to start an implementation to hit against. For this
    # you can use an existing device, the reference implementation in the tools
    # directory, or start a pymodbus server.
    #---------------------------------------------------------------------------#
    client = ModbusTcpClient('192.168.1.9')
    #rq = client.write_registers(2048, [0])
    #rr = client.read_input_registers(000, 1)
    #print (rr.registers)       
    #---------------------------------------------------------------------------#
    # configure io card
    #---------------------------------------------------------------------------#
    #Digital_In_1 = ModbusDigitalInputIOCard(0, client)   
    #print('IOVariables in modbus.py: {IOVariables} '.format(IOVariables=IOVariables))  
    Digital_Out_1 = ModbusDigitalOutputIOCard(2048, client, IOVariables)          
    #---------------------------------------------------------------------------#
    # Run io card
    #---------------------------------------------------------------------------#
    #Digital_In_1.ReadStatus()
    #---------------------------------------------------------------------------#
    # Run io card
    #---------------------------------------------------------------------------#
    try:
        Digital_Out_1.WriteStatus()
    except ConnectionException:
        print('A connection error to the modbus occured at {}'.format(
            datetime.datetime.now()
            )
        )
        pass
    #---------------------------------------------------------------------------#
    # close the client
    #---------------------------------------------------------------------------#
    client.close()      
Пример #18
0
        if "r" in _access:
            rr = client.read_coils(_address, 1)
            print(_tagname, rr)
        a += 1


# Placing all the tags in the tags dict
tags = []  #list for all the  imported tags
tl = str
i = 0

for line in tagimport:
    tl = tagimport[i]
    tl.rstrip()
    a = tl.split(',')
    name, address, access, dataType = a
    address = (address.zfill(5))
    dataType = dataType.rstrip()
    tags.append((name, address, access, dataType))
    i += 1

#tags[1].append(2)

#print(tags)

client = ModbusTcpClient(clientIP, port=clientPort)
go = 1
while go == 1:
    read_all(tags)
    go = 0
Пример #19
0
 def test_sync_tcp_client_instantiation(self):
     client = ModbusTcpClient()
     self.assertNotEqual(client, None)
Пример #20
0
import socket
#HOST = '169.254.66.181'  # The server's hostname or IP address
#HOST = '127.0.0.1'  # The server's hostname or IP address
HOST = '169.254.118.177'  # The server's hostname or IP address
PORT = 5005  # The port used by the server
Message = "Hello"
BUFFSIZE = 1024
'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send((Message).encode())
data = s.recv(BUFFSIZE)
s.close()
print(data)
'''

from pymodbus3.client.sync import ModbusTcpClient

client = ModbusTcpClient('169.254.118.177', 5005)
client.write_coil(1, True)
result = client.read_coils(1, 1)
print(result.bits[0])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send((Message).encode())
data = s.recv(BUFFSIZE)
print(data)
client.close()
Пример #21
0
from pymodbus3.client.sync import ModbusTcpClient

inp = input(
    u"Press any key and enter to send a packet... (Just enter to quit)")
client = ModbusTcpClient('100.100.100.2')
while (inp):
    client.write_coil(1, True)
    result = client.read_coils(1, 1)
    print(result.bits[0])
    client.close()
    inp = input(
        u"Press any key and enter to send a packet... (Just enter to quit)")
Пример #22
0
                      ri['address']) and (ri['address'] + ri['count'] >
                                          nr['address'] - PROXIMITY):
                    ri['count'] = max(ri['count'],
                                      nr['address'] - ri['address'] + 1)
                    nr = None
                    break
        if nr:
            readList.append(nr)

#debugging output
if args.verbose:
    print(registerList)
    print(readList)

#create modbus client
client = ModbusTcpClient(args.ip_address, args.port)

#read modbus data
data = {}
lastFilename = ''
while True:
    for ri in readList:
        result = '-'
        if ri['type'] == 0:
            result = client.read_coils(ri['address'],
                                       ri['count'],
                                       unit=args.unit)
        if ri['type'] == 1:
            result = client.read_discrete_inputs(ri['address'],
                                                 ri['count'],
                                                 unit=args.unit)
Пример #23
0
    },
    'module10': {
        'ch1': 713,
        'ch2': 715,
        'ch3': 717,
        'ch4': 719
    },
    'module11': {
        'ch1': 721,
        'ch2': 723,
        'ch3': 725,
        'ch4': 727
    }
}

client = ModbusTcpClient('192.168.100.12')

# configure I/O modules (input = 0x100, output = 0x180)
client.write_register(
    6146, 0x180, unit=10
)  #<--- this is supposed to config module 2, point 0 as an output but it doesn't work...
client.write_register(input_output_flags['module2']['ch1'], 0x180)
client.write_register(input_output_flags['module2']['ch2'], 0x180)
client.write_register(input_output_flags['module2']['ch3'], 0x180)
client.write_register(input_output_flags['module3']['ch1'], 0x180)
print("config set")

# save configuration to flash (doesn't work... see Opto doc 1465, page 104)
#client.write_register(0, 0x00000003, unit=30)
#print("saved to flash")
Пример #24
0
from pymodbus3.client.sync import ModbusTcpClient  #.client.sync
import time as t
from twisted.internet import reactor, protocol
from pymodbus3.constants import Defaults

import logging
logging.basicConfig()
a = 1
client = ModbusTcpClient('10.181.5.35', port=502)

rq = client.write_coil(1, True)
rr = client.read_coils(1, 1)
assert (rq.function_code < 0x80)  # test that we are not an error
assert (rr.bits[0] == True)  # test the expected value
#result = client.read_coils(0,1)
"""arguments = {
    'read_address':    1,
    'read_count':      8,
    'write_address':   1,
    'write_registers': [20]*8,"""

while a < 4:
    rq = client.write_registers(0, [0] * 15)
    rq2 = client.write_registers(
        1000, [241] * 100)  #Startadresse, skrevet verdi, antall registre
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    client.write_coil(0, True)
    client.write_coil(1, True)
    client.write_coil(2, False)
    client.write_coil(3, True)
Пример #25
0
 def __init__(self, ip, port):
     self.連線 = ModbusTcpClient(host=ip, port=port)
Пример #26
0
 
from pymodbus3.client.sync import ModbusTcpClient  
 
        # instead of this

       # 192.168.1.22:502
        #PLC Mod Bus Regs 40001-40100
        
        
 #40096-40100     monnth day hour .....  
#Reg 2 Bytes --> not 4 bytes     
 


plc_client = ModbusTcpClient('192.168.1.22')
# result =client.read_holding_registers(0,5,unit=0X01) 
# print (str(result))
try:
    for x in range(5,6):
        result = plc_client.write_registers( 9,[int(x)  ],unit=0X01) 
        result = plc_client.write_registers(40007,[int(x) ],unit=0X01) 
        result = plc_client.write_registers(40010,[int(1)],unit=0X01) 
 
    print (str(result))
except Exception as e:
    print("error sending data to plc " + str(e))
 

plc_client.close()
Пример #27
0
def on_message(client, userdata, msg):
    jsonModbusShadow = json.loads(str(bytes.decode(msg.payload)))
    if "desired" in jsonModbusShadow["state"]:
        listRegisters = jsonModbusShadow["state"]["desired"]["registers"]
        print(str(listRegisters))
        try:
            sync_client_write(int(register['register']), listRegisters.value)
        except:
            print("Register Error Handled")


#def on_log(client, userdata, level, msg):
#    print(msg.topic+" "+str(msg.payload))

#client = ModbusTcpClient('127.0.0.1')
client = ModbusTcpClient('192.168.0.101')
pathname = os.path.abspath(os.path.dirname(sys.argv[0]))

with open(pathname + '/' + 'thingInfo.json') as data_file:
    configData = json.load(data_file)
thingName = configData['thingName']
print(thingName)
mqttc = paho.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
#mqttc.on_log = on_log

awshost = "data.iot.us-east-1.amazonaws.com"
awsport = 8883
clientId = thingName
thingName = thingName
Пример #28
0
def plugin_poll(handle):
    """ Poll readings from the modbus device and returns it in a JSON document as a Python dict.

    Available for poll mode only.

    Args:
        handle: handle returned by the plugin initialisation call
    Returns:
        returns a reading in a JSON document, as a Python dict, if it is available
        None - If no reading is available
    Raises:
    """

    try:
        global mbus_client
        if mbus_client is None:
            try:
                source_address = handle['address']['value']
                source_port = int(handle['port']['value'])
            except Exception as ex:
                e_msg = 'Failed to parse Modbus TCP address and / or port configuration.'
                _LOGGER.error('%s %s', e_msg, str(ex))
                raise ValueError(e_msg)
            try:
                mbus_client = ModbusTcpClient(host=source_address, port=source_port)
                mbus_client_connected = mbus_client.connect()
                if mbus_client_connected:
                    _LOGGER.info('Modbus TCP Client is connected. %s:%d', source_address, source_port)
                else:
                    raise RuntimeError("Modbus TCP Connection failed!")
            except:
                mbus_client = None
                _LOGGER.warn('Failed to connect! Modbus TCP host %s on port %d', source_address, source_port)
                return

        """ 
        read_coils(self, address, count=1, **kwargs)  
        read_discrete_inputs(self, address, count=1, **kwargs)
        read_holding_registers(self, address, count=1, **kwargs)
        read_input_registers(self, address, count=1, **kwargs)
        
            - address: The starting address to read from
            - count: The number of coils / discrete or registers to read
            - unit: The slave unit this request is targeting
            
            On TCP/IP, the MODBUS server is addressed using its IP address; therefore, the MODBUS Unit Identifier is useless. 

            Remark : The value 0 is also accepted to communicate directly to a MODBUS TCP device.
        """
        unit_id = UNIT
        modbus_map = json.loads(handle['map']['value'])

        readings = {}

        # Read coils
        coils_address_info = modbus_map['coils']
        if len(coils_address_info) > 0:
            for k, address in coils_address_info.items():
                coil_bit_values = mbus_client.read_coils(99 + int(address), 1, unit=unit_id)
                readings.update({k: coil_bit_values.bits[0]})

        # Discrete input
        discrete_input_info = modbus_map['inputs']
        if len(discrete_input_info) > 0:
            for k, address in discrete_input_info.items():
                read_discrete_inputs = mbus_client.read_discrete_inputs(99 + int(address), 1, unit=unit_id)
                readings.update({k:  read_discrete_inputs.bits[0]})

        # Holding registers
        holding_registers_info = modbus_map['registers']
        if len(holding_registers_info) > 0:
            for k, address in holding_registers_info.items():
                register_values = mbus_client.read_holding_registers(99 + int(address), 1, unit=unit_id)
                readings.update({k: register_values.registers[0]})

        # Read input registers
        input_registers_info = modbus_map['inputRegisters']
        if len(input_registers_info) > 0:
            for k, address in input_registers_info.items():
                read_input_reg = mbus_client.read_input_registers(99 + int(address), 1, unit=unit_id)
                readings.update({k: read_input_reg.registers[0] })

        wrapper = {
            'asset': handle['assetName']['value'],
            'timestamp': utils.local_timestamp(),
            'key': str(uuid.uuid4()),
            'readings': readings
        }

    except Exception as ex:
        _LOGGER.error('Failed to read data from modbus device. Got error %s', str(ex))
        raise ex
    else:
        return wrapper
Пример #29
0
    class __CalculatedParams:

        params = ConfParams()
        user = ThingBoardUser()
        dt2 = 1 / 6000
        TMS_DL = float(params.getParam("INITIAL_TMS_DL"))
        CFT = 0

        TCC_MODE = params.getParam("TCC_MODE")
        TCC = float(params.getParam("INITIAL_TCC"))
        alpha0 = int(params.getParam("IIR_Alfa"))
        dict_Tcycle_A_2_by_sensor_id = {}
        dict_Tcharge_by_sensor_id = {}
        timer = None
        plc_client = None
        if len(params.getParam("PLC_HOST")) > 1:
            plc_client = ModbusTcpClient(params.getParam("PLC_HOST"))

        # after 30 seconds, "hello, world" will be printed
        # a time counter will be more than “TMS” or the time counter will be more than 5 sec

        def init_timer(self):
            # print("init_timer:"+str(self.TMS))
            min_interval = min(5.0, float(self.TMS_DL))
            self.timer = threading.Timer(min_interval, self.timerFunction)
            self.timer.start()

        def timerFunction(self):
            self.submit_CFT_and_TCC()
            # print("sent by Timer, TMS:"+str(self.TMS))

        def set_param(self, sensor_id, param_name, value):
            if self.timer == None:
                self.init_timer()

            if (not param_name):
                return

            if (param_name == "Tcycle_A_2"):
                self.process_Tcycle_A_2(sensor_id, value)

            elif (param_name == "Tcharge"):
                self.process_Tcharge(sensor_id, value)

            elif (param_name == "TBagSpacing"):
                self.submit_parameter("TBS", 0.01 * value, 3)

            elif (param_name == "ChBHight"):
                self.submit_parameter("ABH", 0.1 * value, 4)

            elif (param_name == "Tbaglength"):
                self.submit_parameter("TBL", 0.01 * value, 5)

        def submit_parameter(self, out_param_name, value, plc_reg_address=None):
            ts = {"ts": int(round(time.time() * 1000))}

            # if start_new_data:
            data = []

            new_obj_to_send = {"ts": ts["ts"], "values": {}}

            # Lior process out_param_name ,value
            # Change - Start
            attr_to_send = calculate_info(out_param_name, value)
            #print(value_storage)
            #print(attr_to_send)
            self.user.send_attributes("PLC", attr_to_send)
            
            # new_obj_to_send["values"][out_param_name] = value
            new_obj_to_send["values"][out_param_name] = add_color_digit(value, out_param_name)
            # Change - End

            data.append(new_obj_to_send)
            value = int(value * pow(2, 9))
            try:
                try:
                    if not self.plc_client == None:
                        result = self.plc_client.write_registers(plc_reg_address, [value], unit=0X01)
                        print(out_param_name + " Sent to PLC : " + str(value))
                        self.sendIsAlive()
                except Exception as e:
                    print("error sending data to PLC :  " + str(e))

                self.user.send_telemetry("PLC", data, False, None, None)

            except Exception as e:
                print("error sending data to Things Board :  " + str(e))
                # self.generalLogger.error("error sending data serv " + str(e))

        def process_Tcycle_A_2(self, sensor_id, value):
            self.dict_Tcycle_A_2_by_sensor_id[sensor_id] = value
            if (len(self.dict_Tcycle_A_2_by_sensor_id) == 3 and len(self.dict_Tcharge_by_sensor_id) == 3):
                self.submit_CFT_and_TCC()

        def process_Tcharge(self, sensor_id, value):
            self.dict_Tcharge_by_sensor_id[sensor_id] = value
            if (len(self.dict_Tcycle_A_2_by_sensor_id) == 3 and len(self.dict_Tcharge_by_sensor_id) == 3):
                self.submit_CFT_and_TCC()

        def sendIsAlive(self):
            data = {"ts": int(round(time.time() * 1000)), "values": {"is_alive": True}}
            jsonData = json.dumps(data)
            re = self.user.post(self.user.telemetry_url.format(self.user.access_token("MODBUS")), jsonData)

        def submit_CFT_and_TCC(self):
            if not self.timer == None:
                self.timer.cancel()

            if (len(self.dict_Tcycle_A_2_by_sensor_id) == 0 and len(self.dict_Tcharge_by_sensor_id) == 0):
                # print("no values to be sent by timer, init_timer")
                self.init_timer()
                return

            Nsyc = 0
            ATsycle = 0
            self.CFT = 0

            for value in self.dict_Tcycle_A_2_by_sensor_id.values():

                if (value > 2800 and value < 18000):
                    ATsycle += value
                    Nsyc += 1

            if Nsyc:
                ATsycle = ATsycle / Nsyc
                self.TMS_DL = (float(((10000 - (float(self.alpha0))) * (float(self.TMS_DL)) + (float(self.alpha0)) * (
                    float(ATsycle))) / 10000))
                # self.TMS = self.dt2*float(self.TMS_DL)

            Nsyc = 0
            Tcharge_values_list = []
            if self.TCC_MODE == '0':
                for value in self.dict_Tcharge_by_sensor_id.values():

                    if (value > 0 and value < self.TMS_DL):
                        Tcharge_values_list.append(int(value))
                    else:
                        Tcharge_values_list.append(0)

                if len(Tcharge_values_list) > 0:
                    self.TCC = self.dt2 * max(Tcharge_values_list)


            elif self.TCC_MODE == '1':
                self.TCC = 0
                for value in self.dict_Tcharge_by_sensor_id.values():

                    if (value > 0 and value < self.TMS_DL):
                        self.TCC += value
                        Nsyc += 1

                if Nsyc:
                    self.TCC = self.dt2 * self.TCC / Nsyc

            #             Mode 2: (Median(TCharge(1), TCharge(2), TCharge(3)))
            # If  0<TCharge(n)<( TMS_DL), Add TCharge(n) to a buffer
            # TCC = dt2*(median of the buffer)

            if self.TCC_MODE == '2':
                for value in self.dict_Tcharge_by_sensor_id.values():

                    if (value > 0 and value < self.TMS_DL):
                        Tcharge_values_list.append(int(value))

                if len(Tcharge_values_list) > 0:
                    self.TCC = self.dt2 * median(Tcharge_values_list)
                else:
                    self.TCC = 0




            elif self.TCC_MODE == '3':
                for value in self.dict_Tcharge_by_sensor_id.values():

                    if (value > 0 and value < self.TMS_DL):
                        Tcharge_values_list.append(int(value))
                    else:
                        Tcharge_values_list.append(0)

                if len(Tcharge_values_list) > 0:
                    value1 = max(Tcharge_values_list)

                    Tcharge_values_list.remove(value1)
                    if len(Tcharge_values_list) > 0:
                        value2 = max(Tcharge_values_list)
                        self.TCC = self.dt2 * (value1 + value2) / 2

                    else:
                        self.TCC = self.dt2 * value1
            if ATsycle > 0:
                self.CFT = self.dt2 * ATsycle - self.TCC;

            ts = {"ts": int(round(time.time() * 1000))}

            # if start_new_data:
            data = []

            new_obj_to_send = {"ts": ts["ts"], "values": {}}

            # Change - Start
            attr_to_send = calculate_info("CFT", self.CFT)
            #print(value_storage)
            #print(attr_to_send)
            self.user.send_attributes("PLC", attr_to_send)
            
            attr_to_send = calculate_info("TCC", self.TCC)
            #print(attr_to_send)
            self.user.send_attributes("PLC", attr_to_send)
            

            # new_obj_to_send["values"]["CFT"] = self.CFT
            new_obj_to_send["values"]["CFT"] = add_color_digit(self.CFT, "CFT")
            # new_obj_to_send["values"]["TCC"] = self.TCC
            new_obj_to_send["values"]["TCC"] = add_color_digit(self.TCC, "TCC")
            # Change - End

            data.append(new_obj_to_send)

            cftToSend = int(self.CFT * pow(2, 9))
            tccToSend = int(self.TCC * pow(2, 9))
            try:
                try:
                    if not self.plc_client == None:
                        result = self.plc_client.write_registers(1, [tccToSend], unit=0X01)
                        print("  TCC data sent to PLC :  " + str(tccToSend))
                        result = self.plc_client.write_registers(6, [cftToSend], unit=0X01)
                        print("  CFT data sent to PLC :  " + str(cftToSend))
                        result = self.plc_client.write_registers(9, [1], unit=0X01)
                        self.sendIsAlive()


                except Exception as e:
                    print("error sending data to PLC :  " + str(e))

                self.user.send_telemetry("PLC", data, False, None, None)

            except Exception as e:
                print("error sending data to Things Board :  " + str(e))
                # self.generalLogger.error("error sending data serv " + str(e))

            self.dict_Tcycle_A_2_by_sensor_id = {}
            self.dict_Tcharge_by_sensor_id = {}
            # self.timer = threading.Timer(min(5,int(self.TMS)), self.timerFunction)
            self.init_timer()
Пример #30
0
def sync_client_read(registerNumber):
    try:
        #client.write_coil(1, False)
        #result = client.read_coils(1,1)
        #print(result.bits[0])
        result = client.read_holding_registers(registerNumber, 1)
        return result.registers
        #print(result.bits)
#     except exceptions.ConnectionException:
    except:
        print("Connection Error Handled")
        output = False
    return output


#client = ModbusTcpClient('127.0.0.1')
client = ModbusTcpClient('192.168.1.21')

while 1 == 1:
    sleep(5)
    registersPerPage = 256
    pagenumber = 3
    startOffset = 0
    endOffset = 6 + 1
    for register in range(registersPerPage * pagenumber + startOffset,
                          registersPerPage * pagenumber + endOffset):
        registers = sync_client_read(register)
        print("register" + str(register))
        print("msg sent: register value " + str(registers))