def write_multiple_reg(self, starting_addr, values, slave_id=None):
     slv_id = self.default_slave_id if slave_id is None else slave_id
     for starting_idx, ending_idx in self.get_chunk_indices(values, 123):
         request_adu = tcp.write_multiple_registers(
             slv_id, starting_addr + starting_idx,
             values[starting_idx:ending_idx])
         tcp.send_message(request_adu, self.socket)
示例#2
0
    def thread_poll(self):

        startaddr = self.input_startaddr.value()
        endaddr = self.input_endaddr.value()

        while self.swjk < 10:

            if self.swjk > 1:
                print('break ok')
                break

            else:

                print('polling start')

                holdingRegisters_list = []

                for addrlist in range(startaddr, endaddr + 1):

                    try:
                        if self.fncode == 1:
                            msg_adu = tcp.read_coils(1, addrlist, 1)
                            holdingRegisters = tcp.send_message(
                                msg_adu, self.sock)

                        elif self.fncode == 10001:
                            msg_adu = tcp.read_discrete_inputs(1, addrlist, 1)
                            holdingRegisters = tcp.send_message(
                                msg_adu, self.sock)

                        elif self.fncode == 40001:
                            msg_adu = tcp.read_holding_registers(
                                1, addrlist, 1)
                            holdingRegisters = tcp.send_message(
                                msg_adu, self.sock)

                        elif self.fncode == 30001:
                            msg_adu = tcp.read_input_registers(1, addrlist, 1)
                            holdingRegisters = tcp.send_message(
                                msg_adu, self.sock)

                        holdingRegisters_list.append(holdingRegisters[0])
                    except AttributeError:
                        print('Register Addr Over')
                        holdingRegisters_list.append('None')

                    print("Register " + str(addrlist) + " poll.")
                print(holdingRegisters_list)

                items_list = []
                for registersData in holdingRegisters_list:
                    item_holdingRegisters = QTableWidgetItem()
                    item_holdingRegisters.setText(str(registersData))
                    items_list.append(item_holdingRegisters)

                for item_num in range(0, len(items_list)):
                    self.swjTableSignal.emit(item_num, 2, items_list[item_num])

            time.sleep(1)
示例#3
0
    def write_bit(self, slave_id, address, bit,value):
        message = tcp.read_holding_registers(slave_id, address, 1)
        current_value = tcp.send_message(message, self.sock)[0]

        new_value = set_bit(current_value,bit,value)

        message = tcp.write_single_register(slave_id, address,new_value)
        response = tcp.send_message(message, self.sock)
        return response
示例#4
0
    def gateway_config_write_read(self,add, value):
        config_id = 4

        message = tcp.write_multiple_registers(slave_id=config_id, starting_address=add, values=[value])
        response = tcp.send_message(message, self.sock)

        time.sleep(0.1)

        message = tcp.read_holding_registers(config_id, add, 1)
        response = tcp.send_message(message, self.sock)

        print("..")

        if response[0] != value:
            raise ValueError("Value not writen!")
    def read_discrete_inputs(self, start_discrete_address, number_of_inputs):
        """ Modbus command : Read discrete input(s) (function code = 02)

            @Argument :
            start_discrete_address (int16) : Start discrete input address where to read a input data
            number_of_inputs (int)         : number of discrete input(s) to read

            @Return :
            response : Discrete input(s) data
        """
        response = None

        # Generate modbus TCP message
        try:
            message = modbus_tcp.read_discrete_inputs(
                slave_id=self.device_id,
                starting_address=start_discrete_address,
                quantity=number_of_inputs)
        except Exception as e:
            print("Error during generate modbus message.")

        # Send message via TCP socket
        try:
            self._connect()
            response = modbus_tcp.send_message(message, self.tcp_socket)
            print("response={}".format(response))
            self._disconnect()
        except Exception as e:
            print("Error during send modbus message.")
            print(e)

        return response
    def read_coils(self, start_coil_address, number_of_coils):
        """ Modbus command : Read coil data(s) (function code = 01)

            @Argument :
            start_coil_address (int16) : Start coil address where to read a coil data
            number_of_coils (int)      : number of coil(s) to read

            @Return :
            response : Coil data (Byte)
                        The coils in the response message are packed as one coil per bit of the
                        data field. Status is indicated as 1= ON and 0= OFF.
        """
        response = None

        # Generate modbus TCP message
        try:
            message = modbus_tcp.read_coils(
                slave_id=self.device_id,
                starting_address=start_coil_address,
                quantity=number_of_coils)
        except Exception as e:
            print("Error during generate modbus message.")

        # Send message via TCP socket
        try:
            self._connect()
            response = modbus_tcp.send_message(message, self.tcp_socket)
            print("response={}".format(response))
            self._disconnect()
        except Exception as e:
            print("Error during send modbus message.")
            print(e)

        return response
    def write_registers(self, start_register_address, write_values):
        """ Modbus command : Write data to multiple registers (function code = 16)

            Argument :
            start_register_address (int16) : Start address where to write a data
            write_values (int16)           : Write data(s) 
        """

        # Enable byte system of modbus to be signed-value type
        if self.signed_type == True:
            conf.SIGNED_VALUES = True
        else:
            conf.SIGNED_VALUES = False

        # Generate modbus TCP message
        try:
            message = modbus_tcp.write_multiple_registers(
                slave_id=self.device_id,
                starting_address=start_register_address,
                values=write_values)
        except Exception as e:
            print("Error during generate modbus message.")
            print(
                "\tMaybe, write value is less than 0 as signed integer and .signed_type is set to 'False'."
            )

        # Send message via TCP socket
        try:
            self._connect()
            response = modbus_tcp.send_message(message, self.tcp_socket)
            print("response={}".format(response))
            self._disconnect()
        except Exception as e:
            print("Error during send modbus message.")
            print(e)
示例#8
0
 def write(self):
     message = tcp.write_multiple_registers(slave_id=1, starting_address=0, values=self._output_regs)    
     # time.sleep(.5)
     while True:
         try:
             print(self._output_regs)
             print(message)
             try:
                 response = tcp.send_message(message, self.client)
             except ValueError as ve:
                 print(response)
             break
         except OSError as e:
             print('No he poodido leer. Error {e}')
             while True:
                 try:
                     self.client.connect((self.ip, self.port))
                     print('Socket conectado')
                     break
                 except OSError as e:
                     print('No he poodido conectar. Error {e}')
                     time.sleep(5)
                     continue
     os.system('clear')
     print(Text.from_markup(str(self)))            
    def write_coil(self, coil_address, write_value):
        """ Modbus command : write single coil data (function code = 05)

            @Argument :
            coil_address (int16) : Coil address where to write a coil data
            write_value (int)    : write value
        """

        # Generate modbus TCP message
        try:
            message = modbus_tcp.write_single_coil(slave_id=self.device_id,
                                                   address=coil_address,
                                                   value=write_value)
        except Exception as e:
            print("Error during generate modbus message.")

        # Send message via TCP socket
        try:
            self._connect()
            response = modbus_tcp.send_message(message, self.tcp_socket)
            print("response={}".format(response))
            self._disconnect()
        except Exception as e:
            print("Error during send modbus message.")
            print(e)
示例#10
0
def updateRecord(currentScore, ip):
    global lastrowid, ind_serial
    sock_modbus = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    data_base = sqlite3.connect('score.db')
    try:
        sock_modbus.connect(('10.11.13.' + ip, 502))
        str_message = tcp.read_input_registers(slave_id=1,
                                               starting_address=102,
                                               quantity=1)
        list_response = tcp.send_message(str_message, sock_modbus)
    finally:
        sock_modbus.close()
    if list_response[0] != currentScore:
        tmpScore = list_response[0]
        try:
            tmp_cur = data_base.cursor()
            tmp_sql = (
                'UPDATE game SET score=\'{0}\' WHERE  id_game=\'{1}\';'.format(
                    tmpScore, lastrowid))
            tmp_cur.execute(tmp_sql)
            tmp_cur.close()
            data_base.commit()
        finally:
            data_base.close()
        return tmpScore
    return currentScore
示例#11
0
    def __doRequest(self,message):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self.ipAddr, self.port))

        response = tcp.send_message(message, sock)
        sock.close()
        return response
示例#12
0
def openDoor(ip):
    global Threat_Flags
    try:  #open door
        if not Threat_Flags[0]:
            try:
                sock_modbus = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock_modbus.connect(('10.11.13.' + ip, 502))
                str_message = tcp.write_single_coil(slave_id=1,
                                                    address=100,
                                                    value=1)
                list_response = tcp.send_message(str_message, sock_modbus)
            except socket.error as e:
                print('except')
                QMessageBox(QMessageBox.Critical, "Error:\n", str(e)).exec()
            else:
                pygame.mixer.music.load("fb.mp3")
                pygame.mixer.music.play(5)
                createRecord()
                GameThread(ip).start()
                setDoor(0)
                SleepThread(10, setDoor, 1).start()
            finally:
                sock_modbus.close()
    except:  #open door
        answerMessage = '{} >> unenable to start game'.format(
            time.strftime('%H:%M:%S|%y.%m.%d', time.localtime()))
        logging.warning(answerMessage)

    else:  #open door
        answerMessage = '{} >> start game'.format(
            time.strftime('%H:%M:%S|%y.%m.%d', time.localtime()))
        logging.info(answerMessage)
    def write_coils(self, coil_start_address, write_values):
        """ Modbus command : write multiple coils data (function code = 15)

            @Argument :
            coil_start_address (int16) : Coil start address where to write a set of coils data
            write_values (int)    : write value(s) (list-type)
        """

        # Generate modbus TCP message
        try:
            message = modbus_tcp.write_multiple_coils(
                slave_id=self.device_id,
                starting_address=coil_start_address,
                values=write_values)
        except Exception as e:
            print("Error during generate modbus message.")

        # Send message via TCP socket
        try:
            self._connect()
            response = modbus_tcp.send_message(message, self.tcp_socket)
            print("response={}".format(response))
            self._disconnect()
        except Exception as e:
            print("Error during send modbus message.")
            print(e)
def test_response_on_multi_bit_value_read_requests(sock, function):
    """ Validate response of a succesful Read Holding Registers or Read
    Input Registers request.
    """
    slave_id, starting_address, quantity = (1, 0, 10)
    req_adu = function(slave_id, starting_address, quantity)

    assert tcp.send_message(req_adu, sock) == [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
def test_response_on_single_bit_value_read_requests(sock, function):
    """ Validate response of a succesful Read Coils or Read Discrete Inputs
    request.
    """
    slave_id, starting_address, quantity = (1, 0, 10)
    req_adu = function(slave_id, starting_address, quantity)

    assert tcp.send_message(req_adu, sock) == [0, 1, 0, 1, 0, 1, 0, 1, 0,  1]
def test_response_single_value_write_request(sock, function, value):
    """ Validate responde of succesful Read Single Coil and Read Single
    Register request.
    """
    slave_id, starting_address, value = (1, 0, value)
    req_adu = function(slave_id, starting_address, value)

    assert tcp.send_message(req_adu, sock) == value
def test_response_on_single_bit_value_read_requests(sock, function):
    """ Validate response of a succesful Read Coils or Read Discrete Inputs
    request.
    """
    slave_id, starting_address, quantity = (1, 0, 10)
    req_adu = function(slave_id, starting_address, quantity)

    assert tcp.send_message(req_adu, sock) == [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
def test_response_single_value_write_request(sock, function, value):
    """ Validate responde of succesful Read Single Coil and Read Single
    Register request.
    """
    slave_id, starting_address, value = (1, 0, value)
    req_adu = function(slave_id, starting_address, value)

    assert tcp.send_message(req_adu, sock) == value
def test_response_on_multi_bit_value_read_requests(sock, function):
    """ Validate response of a succesful Read Holding Registers or Read
    Input Registers request.
    """
    slave_id, starting_address, quantity = (1, 0, 10)
    req_adu = function(slave_id, starting_address, quantity)

    assert tcp.send_message(req_adu, sock) ==\
        [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
示例#20
0
def send_message():
    message = tcp.read_holding_registers(slave_id=1,
                                         starting_address=0,
                                         quantity=4)
    try:
        response = tcp.send_message(message, sock)
        return response
    except ValueError:
        print("Whoops... WTS seems to be not responding")
def test_response_multi_value_write_request(sock, function, values):
    """ Validate response of succesful Write Multiple Coils and Write Multiple
    Registers request.

    Both requests write 2 values, starting address is 0.
    """
    slave_id, starting_address = (1, 0)
    req_adu = function(slave_id, starting_address, values)

    assert tcp.send_message(req_adu, sock) == 2
def test_response_multi_value_write_request(sock, function, values):
    """ Validate response of succesful Write Multiple Coils and Write Multiple
    Registers request.

    Both requests write 2 values, starting address is 0.
    """
    slave_id, starting_address = (1, 0)
    req_adu = function(slave_id, starting_address, values)

    assert tcp.send_message(req_adu, sock) == 2
示例#23
0
 def set_discharge(self, discharge=3000):
     """ Set discharge value."""
     ret_status = True
     message = write_passive_register(slave_id=self.slave_id, 
                                      address=self.DISCHARGE, 
                                      value=discharge)
     try:
         response = tcp.send_message(message, self.modbus_tcp)
     except:
         ret_status = False
         response = 0
     return ret_status, response
示例#24
0
 def set_auto(self):
     """ Switch inverter to AUTO."""
     ret_status = True
     message = write_passive_register(slave_id=self.slave_id, 
                                      address=self.AUTO, 
                                      value=0)
     try:
         response = tcp.send_message(message, self.modbus_tcp)
     except:
       ret_status = False
       response = 0
     return ret_status, response
示例#25
0
 def set_standby(self):
     """ Switch inverter to STANDBY."""
     ret_status = True
     message = write_passive_register(slave_id=self.slave_id,
                                      address=self.STANDBY,
                                      value=self.STANDBY_VAL)
     try:
         response = tcp.send_message(message, self.modbus_tcp)
     except:
       ret_status = False
       response = 0
     return ret_status, response
示例#26
0
 def get_battery_percentage(self):
     """ Return the current charge percentage of the batteries."""
     ret_status = True
     message = tcp.read_holding_registers(slave_id=self.slave_id,
                                          starting_address=self.BATTPCT,
                                          quantity=1)
     try:
         response = tcp.send_message(message, self.modbus_tcp)
     except:
         ret_status = False
         response = [-1]
     return ret_status, response[0]
示例#27
0
 def get_inverter_state(self):
     """ Return the inverter state."""
     ret_status = True
     message = tcp.read_holding_registers(slave_id=self.slave_id,
                                          starting_address=self.ME_STATE, 
                                          quantity=1)
     try:
         response = tcp.send_message(message, self.modbus_tcp)
     except:
         ret_status = False
         response = [-1]
     return ret_status, response[0], self.INV_STATES[response[0]]
示例#28
0
 def read_input(self):
     """ Read the inverter's input registers."""
     ret_status = True
     message = tcp.read_input_registers(slave_id=self.slave_id,
                                        starting_address=self.ME_INPUT, 
                                        quantity=self.NUM_INPUT)
     try:
         response = tcp.send_message(message, self.modbus_tcp)
     except:
         ret_status = False
         response = 0
     return ret_status, response
示例#29
0
 def read_holding(self):
     """ Read all the holding registers from inverter."""
     ret_status = True
     message = tcp.read_holding_registers(slave_id=self.slave_id,
                                          starting_address=self.ME_HOLDING, 
                                          quantity=self.NUM_HOLDING)
     try:
         response = tcp.send_message(message, self.modbus_tcp)
     except:
         ret_status = False
         response = 0
     return ret_status, response
    def read_multiple_reg(self, starting_addr, count, slave_id=None):
        slv_id = self.default_slave_id if slave_id is None else slave_id

        response = [None] * count
        for starting_idx, ending_idx in self.get_chunk_indices(
                range(count), 125):
            request_adu = tcp.read_holding_registers(
                slv_id, starting_addr + starting_idx,
                ending_idx - starting_idx)
            response[starting_idx:ending_idx] = tcp.send_message(
                request_adu, self.socket)

        return response
示例#31
0
    def read(self, sock, slave_id=0):
        """
        Attempt to read a raw value from the register.
        This function has debugging logging that will print all bytes returned
        from the server.
        """
        # NOTE: Addresses are 0 indexed, but the documented registers are 1 indexed.
        msg = tcp.read_holding_registers(slave_id, self.register - 1, 1)
        resp = tcp.send_message(msg, sock)

        # Extract the single value from the results
        val = resp[0]
        print("{} ({}): {}".format(self.name, self.register, val))

        return val
示例#32
0
def get_data(ip_address, port=502):
    """get_data is excpected to return a unique value."""
    try:
        # Start of your code (example below)
        conf.SIGNED_VALUES = False
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((ip_address, port))
        message = tcp.read_holding_registers(slave_id=1,
                                             starting_address=0,
                                             quantity=1)
        response = tcp.send_message(message, sock)
        sock.close()
        return response[0]
        # End of your code
    except ConnectionRefusedError as e:
        raise GetDataException(e)
示例#33
0
 def send_message(self, message):
     self.mutex.lock()
     response = None
     if not self.connected:
         self.mutex.unlock()
         return response
     try:
         response = tcp.send_message(message, self.sock)
     except Exception as ex:
         logger.error("Error sending message to server. {}".format(str(ex)))
         if "timed out" in str(ex):
             self.mutex.unlock()
             return None
         self.connected = False
     self.mutex.unlock()
     return response
 def __send_modbus_message(self, adu):
     with self.__lock:
         while True:
             try:
                 result = tcp.send_message(adu, self.__modbus_socket)
                 return result
             except socket.timeout as ex:
                 rospy.logwarn('Modbus socket timed out. Reconnecting.')
                 self.connect()
             except socket.error as ex:
                 if ex.errno in {errno.EPIPE, errno.ETIMEDOUT}:
                     rospy.logwarn_throttle(
                         1, 'Receive modbus data failed (Error: %s). '
                         'Reconnecting.' % (ex, ))
                     self.connect()
                 else:
                     raise
示例#35
0
#!/usr/bin/env python
# scripts/examples/simple_client.py
import socket

from umodbus import conf
from umodbus.client import tcp

# Enable values to be signed (default is False).
conf.SIGNED_VALUES = True

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 502))

# Returns a message or Application Data Unit (ADU) specific for doing
# Modbus TCP/IP.
message = tcp.write_multiple_coils(slave_id=1, address=1, values=[1, 0, 1, 1])

# Response depends on Modbus function code. This particular returns the
# amount of coils written, in this case it isr3.
response = tcp.send_message(message, sock)

sock.close()