Esempio n. 1
2
class ModbusClientRS:
    def __init__(self):
        self.client = ModbusClient()

    def writeRegister(self, address, value):
        if self.client.is_open():
            return self.client.write_single_register(address, value)
        return None

    def readRegister(self, address, value):
        if self.client.is_open():
            self.client.read_holding_registers(address, value)

    def connect(self, host, port):
        # self.client.debug(True)
        self.client.host(SERVER_HOST)
        self.client.port(SERVER_PORT)

        if not self.client.is_open():
            if not self.client.open():
                print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT))

    def is_open(self):
        return self.client.is_open()

    def disconnect(self):
        return self.client.close()
Esempio n. 2
1
class Modbus:
    def __init__(self, host, port, unit):
        self.client = ModbusClient(host, port, unit, timeout=3)

    def __enter__(self):
        self.client.open()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.client.close()

    def toFloat(self, ushorts):
        bs = struct.pack('H', ushorts[0]) + struct.pack('H', ushorts[1])
        return struct.unpack('f', bs)

    def openConnect(self):
        try:
            if not self.isOpen:
                self.client.open()
        except:
            self.closeConnect()

    def closeConnect(self):
        self.client.close()

    @property
    def isOpen(self):
        return self.client.is_open()

    def getValue(self, addr):
        return self.toFloat(self.client.read_holding_registers(addr, 2))[0]

    def getValues(self, tags):
        return [(tag, self.getValue(tag)) for tag in tags]
class TestClientServer(unittest.TestCase):
    def setUp(self):
        # modbus server
        self.server = ModbusServer(port=5020, no_block=True)
        self.server.start()
        # modbus client
        self.client = ModbusClient(port=5020)
        self.client.open()

    def tearDown(self):
        self.client.close()

    def test_read_and_write(self):
        # word space
        self.assertEqual(self.client.read_holding_registers(0), [0],
                         'Default value is 0 when server start')
        self.assertEqual(self.client.read_input_registers(0), [0],
                         'Default value is 0 when server start')
        # single read/write
        self.assertEqual(self.client.write_single_register(0, 0xffff), True)
        self.assertEqual(self.client.read_input_registers(0), [0xffff])
        # multi-write at max size
        words_l = [randint(0, 0xffff)] * 0x7b
        self.assertEqual(self.client.write_multiple_registers(0, words_l),
                         True)
        self.assertEqual(self.client.read_holding_registers(0, len(words_l)),
                         words_l)
        self.assertEqual(self.client.read_input_registers(0, len(words_l)),
                         words_l)
        # write over sized
        words_l = [randint(0, 0xffff)] * 0x7c
        self.assertEqual(self.client.write_multiple_registers(0, words_l),
                         None)
        # bit space
        self.assertEqual(self.client.read_coils(0), [False],
                         'Default value is False when server start')
        self.assertEqual(self.client.read_discrete_inputs(0), [False],
                         'Default value is False when server start')
        # single read/write
        self.assertEqual(self.client.write_single_coil(0, True), True)
        self.assertEqual(self.client.read_coils(0), [True])
        self.assertEqual(self.client.read_discrete_inputs(0), [True])
        # multi-write at min size
        bits_l = [getrandbits(1)] * 0x1
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), True)
        self.assertEqual(self.client.read_coils(0, len(bits_l)), bits_l)
        self.assertEqual(self.client.read_discrete_inputs(0, len(bits_l)),
                         bits_l)
        # multi-write at max size
        bits_l = [getrandbits(1)] * 0x7b0
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), True)
        self.assertEqual(self.client.read_coils(0, len(bits_l)), bits_l)
        self.assertEqual(self.client.read_discrete_inputs(0, len(bits_l)),
                         bits_l)
        # multi-write over sized
        bits_l = [getrandbits(1)] * 0x7b1
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), None)
Esempio n. 4
0
class Slagboom:
    SERVER_HOST = "192.168.3.134"
    SERVER_PORT = 502
    motor1 = 1
    motor2 = 2
    start_pos = 5
    end_pos = 4
    input_reg = 5391
    output_reg = 00000

    def __init__(self):
        print("host: " + self.SERVER_HOST + "\tport: " + str(self.SERVER_PORT))
        self.c = ModbusClient(host=self.SERVER_HOST,
                              port=self.SERVER_PORT,
                              auto_open=True,
                              auto_close=True)
        while True:
            self.c.write_single_register(self.output_reg, 0b000100)
            print("output_reg:\t" +
                  str(self.c.read_holding_registers(self.output_reg, 1)[0]))
            start_ret = self.c.read_holding_registers(
                self.input_reg, 1)[0] & (1 << self.start_pos)
            print("start_sensor_state:\t" + str(start_ret))
            end_ret = self.c.read_holding_registers(self.input_reg,
                                                    1)[0] & (1 << self.end_pos)
            print("end_sensor_state:\t" + str(end_ret))
        return

    def open_slagboom(self):
        ret = 0
        print("open_slagboom")
        reg = self.c.read_holding_registers(self.output_reg,
                                            1)[0] | (1 << self.input1)
        while not ret:
            self.c.write_single_register(self.output_reg, reg)
            ret = self.c.read_holding_registers(self.input_reg,
                                                1)[0] & (1 << self.start_pos)
            print("input1 on\tstart_sensor_state:\t" + str(ret))
        reg = self.c.read_holding_registers(self.output_reg,
                                            1)[0] & ~(1 << self.input1)
        self.c.write_single_register(self.output_reg, reg)
        return

    def close_slagboom(self):
        ret = 0
        reg = self.c.read_holding_registers(self.output_reg,
                                            1)[0] | (1 << self.input2)
        while not ret:
            self.c.write_single_register(self.output_reg, reg)
            ret = self.c.read_holding_registers(self.input_reg,
                                                1)[0] & (1 << self.end_pos)
            print("input2 on\tend_sensor_state:\t" + str(ret))
        reg = self.c.read_holding_registers(self.output_reg,
                                            1)[0] & ~(1 << self.input2)
        self.c.write_single_register(self.output_reg, reg)
        return
def read_fault_present(ModbusClient):
    # reads if fault present
    r0 = ModbusClient.read_holding_registers(105, 1)
    if (len(r0) > 0) and (r0[0] == 128):
        # something returned and message is Moduel Ready for Microwaves
        print('Ready for microwaves ')
        print(r0)
    else:
        print('Fault present:')
        print(r0)
        # read the type of fault
        r1 = ModbusClient.read_holding_registers(104, 1)
        print('Type of fault:')
        print(r1)
Esempio n. 6
0
class TestClientServer(unittest.TestCase):

    def setUp(self):
        # modbus server
        self.server = ModbusServer(port=5020, no_block=True)
        self.server.start()
        # modbus client
        self.client = ModbusClient(port=5020)
        self.client.open()

    def tearDown(self):
        self.client.close()

    def test_read_and_write(self):
        # word space
        self.assertEqual(self.client.read_holding_registers(0), [0], 'Default value is 0 when server start')
        self.assertEqual(self.client.read_input_registers(0), [0], 'Default value is 0 when server start')
        # single read/write
        self.assertEqual(self.client.write_single_register(0, 0xffff), True)
        self.assertEqual(self.client.read_input_registers(0), [0xffff])
        # multi-write at max size
        words_l = [randint(0, 0xffff)] * 0x7b
        self.assertEqual(self.client.write_multiple_registers(0, words_l), True)
        self.assertEqual(self.client.read_holding_registers(0, len(words_l)), words_l)
        self.assertEqual(self.client.read_input_registers(0, len(words_l)), words_l)
        # write over sized
        words_l = [randint(0, 0xffff)] * 0x7c
        self.assertEqual(self.client.write_multiple_registers(0, words_l), None)
        # bit space
        self.assertEqual(self.client.read_coils(0), [False], 'Default value is False when server start')
        self.assertEqual(self.client.read_discrete_inputs(0), [False], 'Default value is False when server start')
        # single read/write
        self.assertEqual(self.client.write_single_coil(0, True), True)
        self.assertEqual(self.client.read_coils(0), [True])
        self.assertEqual(self.client.read_discrete_inputs(0), [True])
        # multi-write at min size
        bits_l = [getrandbits(1)] * 0x1
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), True)
        self.assertEqual(self.client.read_coils(0, len(bits_l)), bits_l)
        self.assertEqual(self.client.read_discrete_inputs(0, len(bits_l)), bits_l)
        # multi-write at max size
        bits_l = [getrandbits(1)] * 0x7b0
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), True)
        self.assertEqual(self.client.read_coils(0, len(bits_l)), bits_l)
        self.assertEqual(self.client.read_discrete_inputs(0, len(bits_l)), bits_l)
        # multi-write over sized
        bits_l = [getrandbits(1)] * 0x7b1
        self.assertEqual(self.client.write_multiple_coils(0, bits_l), None)
def modbus_com(SERVER_HOST, SERVER_PORT, function_code, start_register,
               amount_of_registers):
    c = ModbusClient()
    c.host(SERVER_HOST)
    c.port(SERVER_PORT)
    cnt = 0
    while True:
        # open or reconnect TCP to server
        if not c.is_open():
            if not c.open():
                print("unable to connect to " + SERVER_HOST + ":" +
                      str(SERVER_PORT))
        # if open() is ok, read register (modbus function 0x03)
        if c.is_open():
            if function_code == "3":
                # Read the amount_of_registers from start_register
                regs = c.read_holding_registers(int(start_register),
                                                int(amount_of_registers))
                # if success display registers
                if regs:
                    print("reg address" + str(start_register) + "to" + str(
                        int(start_register) + int(amount_of_registers) - 1) +
                          ":" + str(regs))
            elif function_code == "16":
                #Future support
                pass

        cnt += 1
        if cnt >= 2:
            print("クライアント通信終了")
            c.close()
            break
        # sleep 1s before next polling
        time.sleep(1)
Esempio n. 8
0
def read_valid_registers(target_ip, port, reg):
    result = False
    print(f'\n=====Polling remote server for {reg}:=====')
    for i in range(start_reg, end_reg):
        client = ModbusClient(host=target_ip,
                              port=port,
                              auto_open=True,
                              auto_close=True,
                              timeout=10)
        if reg == "hold":
            data = client.read_holding_registers(i, 1)
        if reg == "input":
            data = client.read_input_registers(i, 1)
        if reg == "discrete":
            data = client.read_discrete_inputs(i, 1)
        if reg == "coil":
            data = client.read_coils(i, 1)
        if data:
            result = True
            print(f'\nValid Registers {reg} detected at {i} with value {data}')
        client.close()
        print('/', end='')
        sleep(0.1)


#	return valid_list,data_list,permission_list
    if result != True:
        print(f'\n No Valid Registers detected in specified range')
Esempio n. 9
0
 def read_all_tags(self):
     try:
         c = ModbusClient(host="192.168.2.11", port=502, debug=False)
         c.open()
         
         for name, tag in self.tag_db.items():
             mb0 = tag['modbus_start'] -1
             mb1 = tag['modbus_stop'] -1
             size = 1+mb1-mb0
             #print(name, mb0, mb1, size)
             #print(tag)
             if 0 <= mb0 < 100000:
                 val = c.read_coils(mb0)[0]
             elif 100000 <= mb0 < 200000:
                 val = c.read_discrete_inputs(mb0-100000)[0]
             elif 300000 <= mb0 < 400000:
                 val = c.read_input_registers(mb0-300000,  size)
                 if size == 1: val = val[0]
                 elif size == 2:
                     val = utils.word_list_to_long(val, big_endian=False)[0]
             elif 400000 <= mb0 < 500000:
                 val = c.read_holding_registers(mb0-400000,  size )
                 if size == 1: val = val[0]
                 elif size == 2:
                     val = utils.word_list_to_long(val, big_endian=False)[0]
             
             if tag['dtype'] == 'float32':
                 val = utils.decode_ieee(val)
             
             #print(name, val)
             self.settings[name] = val
                 
     except Exception as err:
         print("Error in read_all_tags", err)
         c.close()        
Esempio n. 10
0
def modbus_devices(register, value):
    c = ModbusClient(host="164.8.11.147", port=502, auto_open=True)
    # regs=c.read_holding_registers(33)
    # print(regs)
    regs = c.write_single_register(register, value)
    regs1 = c.read_holding_registers(register)
    print(regs1)
Esempio n. 11
0
def execute_func():
    sensor_no = ModbusClient(host="192.40.50.107",
                             port=10010,
                             unit_id=1,
                             auto_open=True)
    sensor_no.open()
    regs = sensor_no.read_holding_registers(0, 100)
    if regs:
        print(regs)
    else:
        print("read error")

    n = 0
    data_count = 0

    for n in range(50):
        data_count = n * 2
        regs[data_count], regs[data_count + 1] = regs[data_count +
                                                      1], regs[data_count]

    dec_array = regs

    data_bytes = np.array(dec_array, dtype=np.uint16)
    data_as_float = data_bytes.view(dtype=np.float32)

    time_data = datetime.datetime.now()
    print(time_data)

    start = 1
    start_range = 50

    value = [[num for num in range(start, start + start_range)],
             [num for num in range(start, start + start_range)], data_as_float]

    data = np.array(value).T.tolist()
    # print(data)

    products = data
    arr = []
    for product in products:
        vals = {}
        vals["Sensor No"] = str(int(product[1]))
        vals["Temp"] = str(product[2])
        vals["Time"] = str(time_data)
        arr.append(vals)

    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["Modbus_Database"]

    mycol = mydb["collection1"]

    record_data = arr
    mycol.insert_many(record_data)
    global documents
    documents = list(mycol.find({}, {'_id': 0}))
    print(documents)

    # myclient.drop_database('Modbus_Database')
    mycol.delete_many({})
    time.sleep(60)
Esempio n. 12
0
class kulucka:
    def __init__(self):
        self.bekle = 1
        self.host = "212.154.74.164"
        self.port = 502
        self.timeout = 2000
        self.c = None
        self.sonuc = {}

    def baglan(self):
        self.c = ModbusClient(host=self.host,
                              unit_id=1,
                              timeout=self.timeout,
                              auto_open=True,
                              auto_close=True,
                              port=self.port)

    def main(self):
        self.c.open()
        regs = self.c.read_holding_registers(12288, 6)
        if regs:
            self.parse(regs)
        else:
            print("read error")
        self.c.close()

    def parse(self, regs):
        k = 1
        for i in range(0, len(regs), 2):
            sicaklik = regs[i] / 10
            nem = regs[i + 1] / 10
            self.sonuc["kulucka" + str(k)] = {"sicaklik": sicaklik, "nem": nem}

            k += 1
        print()
Esempio n. 13
0
def routineLoop():
    global ac, dados, off

    for i in ip:  #Entra na lista de ip's
        for x in add[ip.index(i)]:  #entra na lista de endereços
            ac = ModbusClient(host=i, auto_open=True, unit_id=x)
            readTemp = ac.read_input_registers(
                0)  #Leitura da temperatura lida pelo ac
            dados = ac.read_holding_registers(2, 26)
            if bool(readTemp
                    ) == False:  #Se o valor for falso pula para o próximo ac
                break
            if dados[0] == 0: off = 1
            else: off = 0
            resposta = connect(
                off, int(readTemp[0]), str(i), str(x), str(dados[1]),
                str(dados[3]),
                str(dados[2]))  #Envia os dados para API e recebe a resposta
            resposta = json.loads(resposta)
            print('Recebido: ' + str(resposta))
            decisao = decision(dados, resposta)
            d = datetime.now()
            print(decisao + " | " + str(d.hour) + ":" + str(d.minute) + ":" +
                  str(d.second))
            ac.close()
Esempio n. 14
0
 def modbus_request(self, progress_callback):
     c = ModbusClient(host="localhost", auto_open=False)
     connection_ok = c.open()
     if connection_ok:
         try:
             self.holding_registers = c.read_holding_registers(0, 3)
             print(self.holding_registers)
             regs = [
                 int(10 * self.tcurrinsp.value()),
                 int(10 * self.tcurrexp.value()),
                 int(10 * self.currpress.value())
             ]
             c.write_multiple_registers(3, regs)
             print(regs)
             c.close()
         except:
             print("modbus exception")
             pass
         else:
             print("other")
             pass
         finally:
             #print("passed")
             pass
     else:
         print("could not open")
         pass
Esempio n. 15
0
 def __init__(self, address, port):
     c = ModbusClient()
     c.host(address)
     c.port(port)
     c.unit_id(1)
     c.open()
     data = c.read_holding_registers(130, 12)
     self.data=data
     c.close()
     if data:
         self.LowT1Start = format(data[0], 'x')
         self.LowT1Stop = format(data[1], 'x')
         self.LowT2Start = format(data[2], 'x')
         self.LowT2Stop = format(data[3], 'x')
         
         self.NormT1Start = format(data[4], 'x')
         self.NormT1Stop = format(data[5], 'x')
         self.NormT2Start = format(data[6], 'x')
         self.NormT2Stop = format(data[7], 'x')
         self.PeakT1Start = format(data[8], 'x')
         self.PeakT1Stop = format(data[9], 'x')
         self.PeakT2Start = format(data[10], 'x')
         self.PeakT2Stop = format(data[11], 'x')
     else:
         print("Read Volt And Amper ERROR")
Esempio n. 16
0
def doTest():
    # TCP auto connect on modbus request, close after it
    c = ModbusClient(host="192.168.1.1", auto_open=True, auto_close=True)

    regs = c.read_holding_registers(0, 100)
    if regs:
        print(regs)
    else:
        print("read error")
Esempio n. 17
0
def main():
    router_id = Config.router_id
    my_db = None

    try:
        # ------- Reading from the screen -------
        iot_screen = ModbusClient(Config.host, Config.port, Config.auto_open)
        my_db = DataBaseModbus(Config.db_host, Config.database, Config.user,
                               Config.password)

        cell_start_index = Config.cell_start_index
        nr_of_cells_to_read = Config.nr_of_cells_to_read

        regs = iot_screen.read_holding_registers(cell_start_index,
                                                 nr_of_cells_to_read)
        if not regs:
            log("read error")
        else:
            log("Printed regs: ")
            print regs
            # put each record to database
            for data in regs:
                cell_start_index += 1
                sensor_id = cell_start_index
                measurement = MeasurementRecord(router_id, sensor_id, data)
                my_db.insert_measurement(measurement)

        log("Printing each DB record:")

        # ------- Printing data from db onto screen -------
        # From which record in DB (INDEXED FROM 0) to start reading data
        record_start_index = Config.record_start_index
        # How many records to be read
        records_count = Config.records_count
        # Cell index starting to display values
        current_cell_idx = Config.current_cell_idx

        records = my_db.get_history_measurements(record_start_index,
                                                 records_count)
        # Display data onto Modbus
        for r in records:
            log(r)
            # write_multiple_registers(start_index, [value1, value2, ...])
            if not iot_screen.write_multiple_registers(current_cell_idx,
                                                       [r.amount]):
                log("write error")
            current_cell_idx += 1

    except Error as e:
        log("Error reading data from MySQL table", e)
    finally:
        if my_db:
            my_db.close_connection()
            # print("MySQL connection is closed")

    log("Application stopped")
Esempio n. 18
0
class com(object):
    """This class implements the modbusTCP connection functions """
    def __init__(self):
        ''' Constructor for this class. '''
        self._port = 0


    def __del__(self):
        ''' Destructor for this class. '''
        if self._port !=0:
            self.close()




    def open (self,SERVER_HOST = "192.168.0.210",SERVER_PORT = 502,SERVER_UNIT = 201):
        """Open modbus connection to the ComBox

        Args:
            SERVER_HOST: network address of the ComBox. Default='192.168.0.210'
            SERVER_PORT: modbus TCP port. Default='502'
            SERVER_UNIT: modbus address of the ComBox. Default='201'

        Returns: Boolean value True or False

        """
        self._port = ModbusClient(SERVER_HOST, SERVER_PORT, SERVER_UNIT)
        if not self._port.is_open():
            if not self._port.open():
                print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT))

        return self._port.is_open()

    def close(self):
        """Closes the modbusTCP connection

        Returns: Boolean value True or False

        """
        self._port.close()
        return not self._port.is_open()

    def is_connected(self):
        """This function checks if the connection to the Schneider Conext ComBox is established
        and if it responds to readout commands. It requests the firmware version of the ComBox
        and checks for an received bitstream.

        Returns: Boolean value True or False

        return
        """
        bitstream = self._port.read_holding_registers(0x001E, 7)  # 0x001E Firmware Version str20 r
        if bitstream:
            return True
        else:
            return False
Esempio n. 19
0
    def modbus_func(self):
        sensor_no = ModbusClient(host="192.40.50.107",
                                 port=10010,
                                 unit_id=1,
                                 auto_open=True)
        sensor_no.open()
        regs = sensor_no.read_holding_registers(0, 100)

        if regs:
            print(regs)
        else:
            print("read error")
Esempio n. 20
0
class ModbusClass:
    def __init__(self):

        # Make an instance of modbus object
        self._client = ModbusClient()

    #Connect to the LOGO
    def _connectToLogo(self, ip_address, port_num):
        try:
            self._client.host(ip_address)
            self._client.port(port_num)
            self._client.open()
            print('Connected')

        except AttributeError:
            print('Failed to connect to Logo')

    # Generic Function for reading from any LOGO
    def _readData(self, _list=[], *args):
        _data = []
        for regNumber in _list:
            dataValue = self._client.read_holding_registers(
                regNumber)  # Reading voltage on AI3
            dataValue = dataValue[0]
            dataValue = int(dataValue)
            _data.append(dataValue)
        else:
            return _data

    # Perform two's compliment on any given number just incase the number is negative
    def twosCompliment(self, _list, *args):
        _result_list = []
        for number in _list:
            # All values are expected to be below 8 Bits. If More than 8 Bits, number is negative
            if number > 256:
                number = number - 65536
                _result_list.append(number)
            else:
                number = number
                _result_list.append(number)
        else:
            return _result_list

    # Convert the electrical signals into meaningful data
    def signalConditioning(self, _gain, _offset, _signals=[], *args):
        _result_list = []
        for _signal in _signals:
            _conditioned_signal = (_signal * _gain + _offset)
            _conditioned_signal = round(_conditioned_signal, 2)
            _result_list.append(_conditioned_signal)
        else:
            return _result_list
Esempio n. 21
0
def read_values():
    c = ModbusClient(host=host, auto_open=True, auto_close=True)
    old_value = -1

    while True:

        new_value = int(c.read_holding_registers(43, 1)[0])
        print("New Value: {}".format(new_value))

        if old_value == -1:
            print("Setting old value to new value.")
            old_value = new_value  # Set the old_value so we don't do weird looping

        # Detect if the counter has been reset
        if new_value < old_value:
            print("Counter has been reset externally. Force set.")
            old_value = new_value

        print("Old: {}. New: {}.".format(old_value, new_value))
        diff = new_value - old_value
        old_value = new_value

        # Push to CloudWatch, even if the value is 0
        litres = diff * float(k)
        payload = {
            "request": {
                "namespace": cw_namespace,
                "metricData": {
                    "metricName":
                    "UsageLitres",
                    "dimensions": [
                        {
                            'name': 'Device',
                            'value': 'WaterPulseMeter'
                        },
                        {
                            'name': 'Supply',
                            'value': 'Mains'
                        },
                    ],
                    "value":
                    litres,
                    "timestamp":
                    time.time()
                }
            }
        }
        # Publish to connector
        gg_client.publish(topic=cw_topic, payload=json.dumps(payload))

        time.sleep(poll_delay)
Esempio n. 22
0
def write_single_coil_regiser(ip_addr,port,coil_valid_list):
	write_coil_confirm_list=[]
	write_coil_confirm_data=[]
	client=ModbusClient(host=ip_addr,port=port,auto_open=True,auto_close=True,timeout=10)
	for i in hold_valid_list:
		data=client.write_single_register(i,43981) # HEX(ABCD) == int(43981)
		data=client.read_holding_registers(i,1)
		#print("Regiser: "+str(i)+" => Value: "+str(data))
		if data[0]:
			if 43981==data[0]:
				write_coil_confirm_list.append(i)
				write_coil_confirm_data.append(data[0])
	client.close()
	return write_coil_confirm_list,write_coil_confirm_data
Esempio n. 23
0
class MyModbus:
    def __init__(self, mode):
        if mode == "tcp":
            self.etat = mode
            self.client = ModbusClient(host=ICPCON,
                                       port=PORT,
                                       auto_open=True,
                                       auto_close=True)
            self.db = db.Mydb()
            print("---" + self.etat + " configuration---")
        else:
            self.etat = mode
            self.client = serial.Serial(port=myZwave,
                                        baudrate=9600,
                                        parity=serial.PARITY_ODD)
            self.db = db.Mydb()
            print("---" + self.etat + " configuration---")
            if self.client.isOpen():
                os.system(
                    r'echo -ne "\x01\x08\x00\xF2\x51\x01\x00\x05\x01\x51" > /dev/ttyACM0'
                )
            else:
                print("Didn't stop the light")
        return

    def readCoils(self, min=None, max=None):
        if self.etat == "tcp":
            coils = self.client.read_holding_registers(min, max)
            if coils:
                print(coils)
                self.db.insert(coils[0], coils[1])
            else:
                print("error : read not ok")
        else:
            bits = self.client.read(max)
            if bits:
                print(bits)
                #self.db.insert(bits[0],bits[1]);
            else:
                print("error : read not ok")
        return

    def writeCoils(self, to, data):

        if self.client.write_multiple_registers(to, data):  #write_single_coil
            print(" write done ")
        else:
            print("error : write not ok")
        return
Esempio n. 24
0
    def state_on(self, name_x):
        SERVER_HOST = name_x
        SERVER_PORT = 502
        c = ModbusClient()
        c.host(SERVER_HOST)
        c.port(SERVER_PORT)
        c.open()

        is_ok = c.write_single_coil(32768, True)
        bits = c.read_holding_registers(32768)

        if bits:
            self.first_read_label_text = str('Acik')
            self.image_source = "sf_yesil.png"
        else:
            self.first_read_label_text = str('cannotread')
Esempio n. 25
0
def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press ⌘F8 to toggle the breakpoint.
    # TCP auto connect on first modbus request
    c = ModbusClient(host="localhost", port=502, unit_id=1, auto_open=True)

    regs = c.read_holding_registers(0, 2)
    if regs:
        print(regs)
    else:
        print("read error")

    if c.write_multiple_registers(10, [44, 55]):
        print("write ok")
    else:
        print("write error")
Esempio n. 26
0
def readValueIP(address, port, addr, reg):
    c = ModbusIPClient()
    c.host(address)
    c.port(int(port))
    value = -1
    if not c.is_open():
        if not c.open():
            print("Unable to connect to "+address+":"+str(port))
    if c.is_open():
        try:
            value = c.read_holding_registers(int(addr), int(reg))
        except Exception as e:
            raise e
        finally:
            c.close()
    return value[0]
def polling_thread():
    global regs
    c = ModbusClient(host=SERVER_HOST, port=SERVER_PORT)
    # polling loop
    while True:
        # keep TCP open
        if not c.is_open():
            c.open()
        # do modbus reading on socket
        reg_list = c.read_holding_registers(0, 10)
        # if read is ok, store result in regs (with thread lock synchronization)
        if reg_list:
            with regs_lock:
                regs = list(reg_list)
        # 1s before next polling
        time.sleep(1)
Esempio n. 28
0
def polling_thread():
    global regs
    c = ModbusClient(host=SERVER_HOST, port=SERVER_PORT)
    # polling loop
    while True:
        # keep TCP open
        if not c.is_open():
            c.open()
        # do modbus reading on socket
        reg_list = c.read_holding_registers(0, 10)
        # if read is ok, store result in regs (with thread lock synchronization)
        if reg_list:
            with regs_lock:
                regs = list(reg_list)
        # 1s before next polling
        time.sleep(1)
Esempio n. 29
0
def readPDTemp(num):
    c = ModbusClient(host='192.168.0.4',
                     port=502,
                     unit_id=4,
                     auto_open=True,
                     auto_close=True)
    if c.is_open():
        registerPD = None
        registerTemp = None
    else:
        c.open()
        registerPD = None
        registerTemp = None
    if num == 4:
        registerPD = c.read_holding_registers(reg_addr=450, reg_nb=1)
        registerTemp = c.read_holding_registers(reg_addr=418, reg_nb=3)

    elif num == 5:
        registerPD = c.read_holding_registers(reg_addr=451, reg_nb=1)
        registerTemp = c.read_holding_registers(reg_addr=421, reg_nb=3)

    elif num == 6:
        registerPD = c.read_holding_registers(reg_addr=452, reg_nb=1)
        registerTemp = c.read_holding_registers(reg_addr=424, reg_nb=3)
    else:
        print("system error!")
    param = num, round(time.time()), registerTemp[0] / 10, registerTemp[
        1] / 10, registerTemp[2] / 10, registerPD[0]
    if registerPD:
        if registerTemp:
            try:
                with conn.cursor() as cursor:
                    cursor.execute(qry, param)
                    conn.commit()
            except TypeError:
                print('connection error with Db. Check it.')
                pass
        else:
            print("reboot CAM-4 to get temperature")
    else:
        print("reboot CAM-4 to get PD")
    c.close()

    result = {
        'i': param[0],
        'time': param[1],
        'Temp_R': param[2],
        'Temp_S': param[3],
        'Temp_T': param[4],
        'PD': param[5]
    }
    return result
Esempio n. 30
0
def polling_thd():
    global regs, cycle_count, good_count, error_count
    c = ModbusClient(host='localhost', auto_open=True)
    # polling loop
    while True:
        # do modbus reading on socket
        reg_list = c.read_holding_registers(0, len(regs))
        # if read is ok, store result in regs (with thread lock synchronization)
        with regs_lock:
            cycle_count += 1
            if reg_list:
                regs = list(reg_list)
                good_count += 1
            else:
                regs = [None] * 5
                error_count += 1
        # 1.0s before next polling
        time.sleep(1.0)
Esempio n. 31
0
def getModbusData(host, port, start_register, end_register):                                                               
    
    # Returns a list containing the data from each Modbus register between
    #...and including the start and end register
  
    # Depending on the format of any particular value you want, its data may be distributed
    #...over multiple registers and will require further formatting to be human-readable.
                                                              
    # This function only returns the data directly taken from the device's Modbus registers.
    
        # Setting up the client 
    #----------------------------------------------------
    client = ModbusClient()     # Creates a Modbus client opject 
    client.host(host)           # Assigns the specified host (IP) address to the client      
    client.port(port)           # Assigns the specified port to the client
    
    start_register -= 2     # The Modbus registers listed in the Shark100 User's manual
    end_register -= 2       #...are all offset by 2 from their actual values,
                            #...so we account for that here.
    
    num_of_registers = end_register - start_register + 1
    # Since the registers are taken as integers, we can take the range between the start and end
    #...registers and add 1 to get the total number of registers to query.
                                                                                                                            
    #----------------------------------------------------
        
        # Reading the device's Modbus registers
    #----------------------------------------------------
    

    
    client.open()     # Opens the connection
    
    response = client.read_holding_registers(start_register, num_of_registers)
                # This function returns a list of values, one for each of the Modbus registers specified.
                # It works even if some of the registers queried have data stored in different formats,
                #...so be careful not to automatically treat all data the same.
    
    client.close()     # Closes the connection
    
    #----------------------------------------------------
    
    
    return response
Esempio n. 32
0
def reader(worker, job):
    c = ModbusClient(host="localhost", port=502)

    if not c.is_open() and not c.open():
        print("unable to connect to host")

    if c.is_open():

        holdingRegisters = c.read_holding_registers(1, 4)

        # Imagine we've "energy" value in position 1 with two words
        energy = (holdingRegisters[0] << 16) | holdingRegisters[1]

        # Imagine we've "power" value in position 3 with two words
        power = (holdingRegisters[2] << 16) | holdingRegisters[3]

        out = {"energy": energy, "power": power}
        return json.dumps(out)
    return None
Esempio n. 33
0
def polling_thread():
    global regs, poll_cycle
    c = ModbusClient(host=args.host, port=args.port, unit_id=args.unit_id)
    # polling loop
    while True:
        # keep TCP open
        if not c.is_open():
            c.open()
        # do modbus reading on socket
        reg_list = c.read_holding_registers(20610,20)
        # if read is ok, store result in regs (with thread lock synchronization)
        with regs_lock:
            if reg_list:
                regs = list(reg_list)
                poll_cycle += 1
            else:
                poll_cycle = 0
        # 1s before next polling
        time.sleep(0.2)
Esempio n. 34
0
def read_valid_registers(ip_addr,port,reg):
	valid_list=[]
	data_list=[]
	permission_list=[]
	client=ModbusClient(host=ip_addr,port=port,auto_open=True,auto_close=True,timeout=10)
	for i in tqdm(range(1,500)):
		if reg == "hold":
			data=client.read_holding_registers(i,1)
		if reg == "input":
			data=client.read_input_registers(i,1)
		if reg == "discrete":
			data=client.read_discrete_inputs(i,1)
		if reg == "coil":
			data=client.read_coils(i,1)
		if data:
				valid_list.append(i)
				data_list.append(data[0])
				permission_list.append("Read")
	client.close()
	return valid_list,data_list,permission_list
Esempio n. 35
0
def monitor_register(target_ip, port, address, delay, reg):
    while True:
        client = ModbusClient(host=target_ip,
                              port=port,
                              auto_open=True,
                              auto_close=True,
                              timeout=1)
        if reg == "Holding":
            data = client.read_holding_registers(address, 1)
        if reg == "Input":
            data = client.read_input_registers(address, 1)
        if reg == "Discrete":
            data = client.read_discrete_inputs(address, 1)
        if reg == "Coil":
            data = client.read_coils(address, 1)
        if data:
            print(f'{reg} register at address {address} has value {data}')
        #print ('.', end='')
        client.close()
        sleep(delay)
Esempio n. 36
0
def polling_thread():
    global regs, client
    client = ModbusClient(host=SERVER_HOST, port=SERVER_PORT)
    isOpen = False
    # polling loop
    while True:
        # keep TCP open
        if not client.is_open():
            print("unable to connect to " + SERVER_HOST + ":" +
                  str(SERVER_PORT))
            client = ModbusClient(host=SERVER_HOST, port=SERVER_PORT)
            client.open()

        # do modbus reading on socket
        reg_list = client.read_holding_registers(0, 10)
        # if read is ok, store result in regs (with thread lock synchronization)
        if reg_list:
            with threadlock:
                regs = list(reg_list)
        # 1s before next polling
        time.sleep(1)
Esempio n. 37
0
def modbus(ip):

    dip = "Offline"

    # Initiate modbus client
    c = ModbusClient(host=ip, port=502, auto_open=True, timeout=1)

    # Read Modbus outputs
    reg = c.read_holding_registers(0, 100)

    # Close Modbus connection
    c.close()

    if reg:

        # Register 49 (array position 48) is dip switch settings
        # Convert float response to 8 bit binary string and reverse order (all in one line boiiii)
        dip = f'{reg[48]:08b}'[::-1]
        # Convert to array
        dip = [c for c in dip]

    return (dip)
Esempio n. 38
0
EOL         = "\n"

c = ModbusClient(host=SERVER_HOST, port=SERVER_PORT)

if not c.open():
    print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT))
    sys.exit(1)

# banner
sys.stdout.write("----------------------------------------" + EOL)
sys.stdout.write("NTS   0 0 0 0  0 0 0 0  0 1 1 1  1 1 1 1" + EOL)
sys.stdout.write("      1 2 3 4  5 6 7 8  9 0 1 2  3 4 5 6" + EOL)
sys.stdout.write("----------------------------------------" + EOL)

# do modbus read
regs = c.read_holding_registers(20610, 20)
c.close()

# if read ok
if regs:
    for i, value in enumerate(regs):
        # builts bits list
        bits = utils.get_bits_from_int(value, val_size=16)
        bits.reverse()
        # line name (ME or Txx)
        sys.stdout.write("ME    " if not i else "T%02d   " % i)
        # bit value (1 or " ")
        for x, bit in enumerate(bits):
            sys.stdout.write("1 " if bit else ". ")
            if not (x+1)%4:
                sys.stdout.write(" ")
Esempio n. 39
0
class ModbusTCPSensor(OMPluginBase):
    """
    Get sensor values form modbus
    """

    name = 'modbusTCPSensor'
    version = '1.0.7'
    interfaces = [('config', '1.0')]

    config_description = [{'name': 'modbus_server_ip',
                           'type': 'str',
                           'description': 'IP or hostname of the ModBus server.'},
                          {'name': 'modbus_port',
                           'type': 'int',
                           'description': 'Port of the ModBus server. Default: 502'},
                          {'name': 'debug',
                           'type': 'int',
                           'description': 'Turn on debugging (0 = off, 1 = on)'},
                          {'name': 'sample_rate',
                           'type': 'int',
                           'description': 'How frequent (every x seconds) to fetch the sensor data, Default: 60'},
                          {'name': 'sensors',
                           'type': 'section',
                           'description': 'OM sensor ID (e.g. 4), a sensor type and a Modbus Address',
                           'repeat': True,
                           'min': 0,
                           'content': [{'name': 'sensor_id', 'type': 'int'},
                                       {'name': 'sensor_type', 'type': 'enum', 'choices': ['temperature',
                                                                                           'humidity',
                                                                                           'brightness']},
                                       {'name': 'modbus_address', 'type': 'int'},
                                       {'name': 'modbus_register_length', 'type': 'int'}]}]

    default_config = {'modbus_port': 502, 'sample_rate': 60}

    def __init__(self, webinterface, logger):
        super(ModbusTCPSensor, self).__init__(webinterface, logger)
        self.logger('Starting ModbusTCPSensor plugin...')

        self._config = self.read_config(ModbusTCPSensor.default_config)
        self._config_checker = PluginConfigChecker(ModbusTCPSensor.config_description)

        py_modbus_tcp_egg = '/opt/openmotics/python/plugins/modbusTCPSensor/pyModbusTCP-0.1.7-py2.7.egg'
        if py_modbus_tcp_egg not in sys.path:
            sys.path.insert(0, py_modbus_tcp_egg)

        self._client = None
        self._samples = []
        self._save_times = {}
        self._read_config()

        self.logger("Started ModbusTCPSensor plugin")

    def _read_config(self):
        self._ip = self._config.get('modbus_server_ip')
        self._port = self._config.get('modbus_port', ModbusTCPSensor.default_config['modbus_port'])
        self._debug = self._config.get('debug', 0) == 1
        self._sample_rate = self._config.get('sample_rate', ModbusTCPSensor.default_config['sample_rate'])
        self._sensors = []
        for sensor in self._config.get('sensors', []):
            if 0 <= sensor['sensor_id'] < 32:
                self._sensors.append(sensor)
        self._enabled = len(self._sensors) > 0

        try:
            from pyModbusTCP.client import ModbusClient
            self._client = ModbusClient(self._ip, self._port, auto_open=True, auto_close=True)
            self._client.open()
            self._enabled = self._enabled & True
        except Exception as ex:
            self.logger('Error connecting to Modbus server: {0}'.format(ex))

        self.logger('ModbusTCPSensor is {0}'.format('enabled' if self._enabled else 'disabled'))

    def clamp_sensor(self, value, sensor_type):
        clamping = {'temperature': [-32, 95.5, 1],
                    'humidity': [0, 100, 1],
                    'brightness': [0, 100, 0]}
        return round(max(clamping[sensor_type][0], min(value, clamping[sensor_type][1])), clamping[sensor_type][2])

    @background_task
    def run(self):
        while True:
            try:
                if not self._enabled or self._client is None:
                    time.sleep(5)
                    continue
                om_sensors = {}
                for sensor in self._sensors:
                    registers = self._client.read_holding_registers(sensor['modbus_address'],
                                                                    sensor['modbus_register_length'])
                    if registers is None:
                        continue
                    sensor_value = struct.unpack('>f', struct.pack('BBBB',
                                                                   registers[1] >> 8, registers[1] & 255,
                                                                   registers[0] >> 8, registers[0] & 255))[0]
                    if not om_sensors.get(sensor['sensor_id']):
                        om_sensors[sensor['sensor_id']] = {'temperature': None, 'humidity': None, 'brightness': None}

                    sensor_value = self.clamp_sensor(sensor_value, sensor['sensor_type'])

                    om_sensors[sensor['sensor_id']][sensor['sensor_type']] = sensor_value
                if self._debug == 1:
                    self.logger('The sensors values are: {0}'.format(om_sensors))

                for sensor_id, values in om_sensors.iteritems():
                    result = json.loads(self.webinterface.set_virtual_sensor(sensor_id, **values))
                    if result['success'] is False:
                        self.logger('Error when updating virtual sensor {0}: {1}'.format(sensor_id, result['msg']))

                time.sleep(self._sample_rate)
            except Exception as ex:
                self.logger('Could not process sensor values: {0}'.format(ex))
                time.sleep(15)

    @om_expose
    def get_config_description(self):
        return json.dumps(ModbusTCPSensor.config_description)

    @om_expose
    def get_config(self):
        return json.dumps(self._config)

    @om_expose
    def set_config(self, config):
        config = json.loads(config)
        for key in config:
            if isinstance(config[key], basestring):
                config[key] = str(config[key])
        self._config_checker.check_config(config)
        self.write_config(config)
        self._config = config
        self._read_config()
        return json.dumps({'success': True})
Esempio n. 40
0
import time

SERVER_HOST = "192.168.181.76"
SERVER_PORT = 502

c = ModbusClient()

# uncomment this line to see debug message
#c.debug(True)

# define modbus server host, port
c.host(SERVER_HOST)
c.port(SERVER_PORT)

while True:
    # open or reconnect TCP to server
    if not c.is_open():
        if not c.open():
            print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT))

    # if open() is ok, read register (modbus function 0x03)
    if c.is_open():
        # read 10 registers at address 0, store result in regs list
        regs = c.read_holding_registers(0, 10)
        # if success display registers
        if regs:
            print("reg ad #0 to 9: "+str(regs))

    # sleep 2s before next polling
    time.sleep(2)
Esempio n. 41
0
class ClientGUI:
    def __init__(self):
        self.lock = RLock()
        self.calibgui = None
        self.client = ModbusClient()
        self.register_values_widgets = {}
        self.counter = 1
        self.find_thread = None
        self.obj_data = None
        self.stop_signal = False
        self.__build_ui()

    def run_ui(self):
        self.root.mainloop()

    def __build_ui(self):
        # ui hierarchy:
        #
        #root
        #   connectframe
        #       connectlabel
        #       connectbutton
        #       snapshotbutton
        #       calibbuton
        #   mainframe
        #       registerframe
        #           reglabel
        #           registergridframe
        #               ...
        #       outputframe
        #           outputlabel
        #           outputtext

        root = Tk()
        self.root = root
        root.wm_title("RemoteSurf Modbus Client")
        root.protocol("WM_DELETE_WINDOW", self.__delete_window)

        self.font = tkFont.Font(root = root, family = "Helvetica", size = 12)

        connectframe = Frame(root)
        connectbutton = Button(connectframe, text = "Connect", command = self.__connectbutton_click)
        connectlabel = Label(connectframe, text = "Not connected.")
        calibbutton = Button(connectframe, text = "Calibrate", command = self.__calibbutton_click)
        homebutton = Button(connectframe, text = "Home", command = self.__homebutton_click)
        findbutton = Button(connectframe, text = "Find", command = self.__findbutton_click)
        mainframe = Frame(root)
        registerframe = Frame(mainframe)
        reglabel = Label(registerframe, text = "Set registers")
        registergridframe = Frame(registerframe)
        # outputframe = Frame(mainframe)
        # outputlabel = Label(outputframe, text = "Output")
        # vscrollbar = Scrollbar(outputframe)
        # hscrollbar = Scrollbar(outputframe)
        # outputtext = ThreadSafeConsole(outputframe, root, vscrollbar, font = self.font, wrap = NONE)

        connectframe.pack(side = TOP, fill = X)
        connectlabel.pack(side = BOTTOM, anchor = W)
        homebutton.pack(side = RIGHT)
        findbutton.pack(side = RIGHT)
        calibbutton.pack(side = RIGHT)
        connectbutton.pack(side = RIGHT)
        mainframe.pack(side = BOTTOM, fill = BOTH, expand = YES)
        registerframe.pack(side = TOP, expand = YES, anchor = W)
        # outputframe.pack(side = BOTTOM, fill = BOTH, expand = YES)
        reglabel.pack(side = TOP, anchor = CENTER)
        registergridframe.pack(side = BOTTOM, anchor = W)
        # registerframe.config(bg = "cyan")
        # mainframe.config(bg = "pink")
        # registergridframe.config(bg = "red")

        registergridframe.columnconfigure(0, weight = 1)
        registergridframe.columnconfigure(1, weight = 1)
        registergridframe.columnconfigure(2, weight = 1)
        registergridframe.columnconfigure(3, weight = 1)

        self.x_pad = 10
        registergrid_widgets = []
        titles = ["Address", "Label", "Value", ""]
        col = 0
        for title in titles:
            title_label = Label(registergridframe, text = title)
            title_label.grid(row = 0, column = col, padx = self.x_pad)
            registergrid_widgets.append(title_label)
            col += 1

        registers_data = [(500, "x"),
                     (501, "y"),
                     (502, "z"),
                     (503, "A"),
                     (504, "B"),
                     (505, "C"),
                     ]

        for i in range(len(registers_data)):
            reg_data = registers_data[i]
            row = i + 1
            self.__add_register(registergridframe, reg_data, row, registergrid_widgets)

        # hscrollbar.config(orient = HORIZONTAL, command = outputtext.xview)
        # hscrollbar.pack(side = BOTTOM, fill = X)
        # outputtext.config(state = DISABLED, yscrollcommand = vscrollbar.set, xscrollcommand = hscrollbar.set)  #must change to NORMAL before writing text programmatically
        # outputtext.pack(side = LEFT, fill = BOTH, expand = YES, padx = x_padding, pady = y_padding)
        # vscrollbar.config(command = outputtext.yview)
        # vscrollbar.pack(side = RIGHT, fill = Y)

        self.connectframe = connectframe
        self.connectlabel = connectlabel
        self.connectbutton = connectbutton
        self.mainframe = mainframe
        self.registerframe = registerframe
        self.reglabel = reglabel
        self.registergridframe = registergridframe
        self.calibbutton = calibbutton
        # self.outputframe = outputframe
        # self.outputlabel = outputlabel
        # self.vscrollbar = vscrollbar
        # self.hscrollbar = hscrollbar
        # self.outputtext = outputtext

        root.update()
        w, h = root.winfo_width(), root.winfo_height()
        root.minsize(w, h)
        x, y = MAINFRAME_POS
        root.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def __homebutton_click(self):
        values = {
            500: 300,
            501: 0,
            502: 500,
            503: 180,
            504: 0,
            505: 180,
        }
        self.set_values(values, go_to_value = False)

    def __add_register(self, master, data, row, widget_list):
        regaddresslabel = Label(master, text=str(data[0]))
        regaddresslabel.grid(row=row, column=0)
        reglabellabel = Label(master, text=data[1])
        reglabellabel.grid(row=row, column=1)
        regvalueentry = AccessibleEntry(master, justify = RIGHT)
        regvalueentry.set("0")
        regvalueentry.grid(row=row, column=2, padx=self.x_pad)
        regsetbtn = Button(master, text="Set", command = self.__setbutton_click)
        regsetbtn.grid(row=row, column=3)
        widget_list.append(regaddresslabel)
        widget_list.append(reglabellabel)
        widget_list.append(regvalueentry)
        widget_list.append(regsetbtn)
        self.register_values_widgets[data[0]] = (0, regvalueentry)

    def __calibbutton_click(self):
        if not self.calibgui:
            self.calibgui = CalibGUI(self)

    def __findbutton_click(self):
        if self.find_thread is None:
            self.find_thread = Thread(target=self.__find_object)
            self.find_thread.start()

    def __find_object(self):
        import DataCache as DC
        from glob import glob
        from os.path import join
        import numpy as np
        from SFMSolver import SFMSolver, find_ext_params
        import Utils

        print "FINDING"

        np.set_printoptions(precision=3, suppress=True)

        files_dir = "out/2017_3_8__14_51_22/"
        files = glob(join(files_dir, "*.jpg"))
        masks = []
        for f in files:
            m = f.replace(".jpg", "_mask.png")
            masks.append(m)
        sfm = SFMSolver(files, masks)
        if self.obj_data is None:
            imgs, kpts, points, data = sfm.calc_data_from_files_triang_simple()
            self.obj_data = imgs, kpts, points, data
        else:
            imgs, kpts, points, data = self.obj_data

        arr_calib = DC.getData("out/%s/arrangement_calib.p" % ARRANGEMENT_CALIB_DIR)
        ttc = arr_calib["ttc"]
        tor = arr_calib["tor"]
        if "cam_mtx" in arr_calib:
            print "camMtx, distcoeffs load"
            Utils.camMtx = arr_calib["cam_mtx"]
            Utils.dist_coeffs = arr_calib["dist_coeffs"]

        if self.stop_signal:
            self.stop_signal = False
            return

        for point in FIND_POINTS:
            values = {
                500: point[0],
                501: point[1],
                502: point[2],
                503: point[3],
                504: point[4],
                505: point[5],
            }
            print "set_values call"
            self.set_values(values, True)
            print "set_values return"

            time.sleep(0.5)
            CamGrabber.capture_if_no_chessboard = True
            CamGrabber.capture = True
            time.sleep(0.5)

            if self.stop_signal:
                self.stop_signal = False
                return

        find_dir = logger.outputdir
        files = glob("%s/*.jpg" % find_dir)
        print files
        # files_dir = "out/2017_4_5__15_57_20/"
        # files = glob(join(files_dir, "*.jpg"))
        files.sort()
        files = files[-len(FIND_POINTS):]
        results = []

        for f in files:
            res = find_ext_params(f, imgs, kpts, points, data, tor, ttc)
            results.append(res)
            if self.stop_signal:
                self.stop_signal = False
                return

        for i in range(len(results)):
            print i, results[i]
            write_log((i, results[i]))
        result = max(results, key=lambda x: x[2])
        write_log(result)


        values = {
            500: int(result[0][0] * 10),
            501: int(result[0][1] * 10),
            502: int(result[0][2] * 10) + 200,
            503: int(result[1][2]),
            504: int(result[1][1]),
            505: int(result[1][0]),
        }

        print "num inl: ", result[2]
        pprint(values)
        self.set_values(values, go_to_value=False)
        self.find_thread = None

    def __connectbutton_click(self):
        if self.client.is_open():
            self.client.close()
        else:
            self.client.host(SERVER_HOST)
            self.client.port(SERVER_PORT)
            if self.client.open():
                write_log("Connection established")
                self.refresh_values()
                self.read_robot_pos()
            else:
                write_log("ERROR: Connecting failed")
        self.__update_gui()

    def read_robot_pos(self):
        write_log("Reading robot position:")
        posdict = {}
        for i in range(1000, 1006):
            if self.client.is_open():
                with self.lock:
                    real_val_uint = self.client.read_input_registers(i)[0]
                    real_val_holding_uint = self.client.read_holding_registers(i)[0]
                assert real_val_uint == real_val_holding_uint
                real_val_int = uintToInt16(real_val_uint)
                posdict[i] = real_val_int
                write_log("%d, %d" % (i, real_val_int))
            else:
                write_log("ERROR: Read could not be completed, client not connected.")
                self.__update_gui()
                break
        write_log("Read done.")
        return posdict

    def refresh_values(self):
        for address in self.register_values_widgets:
            if self.client.is_open():
                value, widget = self.register_values_widgets[address]
                with self.lock:
                    real_val_uint = self.client.read_input_registers(address)[0]
                    real_val_holding_uint = self.client.read_holding_registers(address)[0]
                assert real_val_uint == real_val_holding_uint
                real_val_int = uintToInt16(real_val_uint)
                widget.set(str(real_val_int))
                self.register_values_widgets[address] = (real_val_int, widget)
            else:
                write_log("ERROR: Read could not be completed, client not connected.")
                self.__update_gui()
                break
        write_log("Refresh done.")
        return self.register_values_widgets

    def __update_gui(self):
        if self.client.is_open():
            self.connectlabel.config(text = "Connected to: %s:%d" % (SERVER_HOST, SERVER_PORT))
            self.connectbutton.config(text = "Disconnect")
        else:
            self.connectbutton.config(text = "Connect")
            self.connectlabel.config(text = "Not connected.")
        self.root.update()

    def __print_memory(self):
        self.refresh_values()
        write_log("Memory dump:")
        write_log("------------")
        for address in self.register_values_widgets:
            val, widget = self.register_values_widgets[address]
            write_log("%d, %d" % (address, val))
        write_log("------------")

    def __setbutton_click(self, wait = False):
        if not self.client.is_open():
            write_log("ERROR: Not connected to client")
            return

        # writing message counter
        retval = self.__write_register(COUNTER_REGISTER_OUT, self.counter)
        if not retval:
            self.__update_gui()
            return

        # writing registers
        for address in self.register_values_widgets:
            value, widget = self.register_values_widgets[address]
            widgetvalue_int = None
            try:
                widgetvalue_int = int(widget.get())
            except ValueError:
                write_log("ERROR: Wrong input format in value entry for address: %d" % address)
                continue

            if value == widgetvalue_int:
                continue

            retval = self.__write_register(address, widgetvalue_int)
            if retval:
                self.register_values_widgets[address] = (widgetvalue_int, widget)
            else:
                self.__update_gui()
        self.refresh_values()

        # message counter wait
        if wait:
            global break_wait
            while not break_wait:
                with self.lock:
                    counter = self.client.read_input_registers(COUNTER_REGISTER_IN)[0]
                if counter == self.counter:
                    break
                time.sleep(0.1)
            break_wait = False

        # counter increment
        self.counter = (self.counter + 1) % 20

        if PRINT_ALL_MEMORY_ON_WRITE:
            self.__print_memory()
            self.read_robot_pos()

    def __write_register(self, address, value):
        if not (-32768 <= value <= 32767):
            write_log("ERROR: -32768 <= value <= 32767 is false for address: %d" % address)
            return False

        widgetvalue_uint = intToUint16(value)
        if self.client.is_open():
            with self.lock:
                retval = self.client.write_single_register(address, widgetvalue_uint)
            if retval:
                write_log("Register written. Address: %d, value: %d" % (address, value))
                return True
            else:
                write_log("ERROR: Write failed. Address: %d, value: %d" % (address, value))
        else:
            write_log("ERROR: client not connected.")
        return False

    def set_values(self, values, wait = True, go_to_value = True):
        """
        :param values: dictionary of { address : value} both int
        :return:
        """
        for address in values:
            if address not in self.register_values_widgets:
                continue

            val, widget = self.register_values_widgets[address]
            widget.set(str(values[address]))
        if go_to_value:
            self.__setbutton_click(wait)

    def __delete_window(self):
        CamGrabber.exit = True
        self.stop_signal = True
        self.client.close()
        self.root.quit()
Esempio n. 42
0
class modBusWriteRead():
    def __init__(self,client_host):
        self.client_host = client_host
        self.client_port = 502
        self.err_list = []
        self.connect() #buradan bağlantı yapılacak;

    def connect(self):
        self.modbus_c = ModbusClient()
        self.modbus_c.host(self.client_host)
        self.modbus_c.port(self.client_port)
        if not self.modbus_c.is_open():
            if not self.modbus_c.open():
                text="unable to connect to " + self.client_host + ":" + str(self.client_port)
                print(text)

    def write_data_reg(self,address,list):
        if self.modbus_c.open():
            if len(list)>120:
                sent_list = self.hazirla_dizi_to_write(list)
                i = 0
                hedef_reg_taban = address
                for list_to_sent in sent_list:
                    hedef_reg = hedef_reg_taban + (i * 120)
                    a = self.modbus_c.write_multiple_registers(hedef_reg, list_to_sent)
                    if a == None or a == False:
                        self.err_list.append(False)
                    i += 1
            else:
                a = self.modbus_c.write_multiple_registers(address, list)
                if a == None or a == False:
                    self.err_list.append(False)
        if len(self.err_list) > 0:
            self.err_list = []
            pass
            # dikkat
            # print("data göndermede hata oluştu, tekrar deneyin !")

    def hazirla_dizi_to_write(self,d_list):
        # eğer gönderilecek değer 120 den büyük ise aşağıdaki fonksiyon 120 lik diziler döndürüyor
        r_list = []
        g_list = []
        i = 0
        for index in range(len(d_list)):
            g_list.append(d_list[index])
            i += 1
            if i > 119:
                i = 0
                r_list.append(g_list)
                g_list = []
            if (len(d_list) - 1) == index and i < 119:
                r_list.append(g_list)
        return r_list

    def read_data_reg(self,address,reg_count,read_float=False ):
        # burada 16 lık ya da float olarak okunabiliyor
        if self.modbus_c.is_open():
            if read_float == False:
                plc_list_int = self.modbus_c.read_holding_registers(address, reg_count)
                return plc_list_int
            elif read_float == True:
                plc_list_f_16=self.modbus_c.read_holding_registers(address,reg_count)
                if plc_list_f_16 is not None:
                    plc_list_float=self.long_to_float(plc_list_f_16)
                    return plc_list_float

    def long_to_float(self,list_16):
        list_float=[]
        list_16.reverse()
        list_long=utils.word_list_to_long(list_16)
        for any_long in list_long:
            list_float.append(utils.decode_ieee(any_long))
        list_float.reverse()
        return list_float
Esempio n. 43
0
c=ModbusClient()
#c.debug(1)
c.host("163.111.184.31")
c.unit_id(33)

while(True):
  # keep TCP link open
  if not c.is_open():
    c.open()

  if c.is_open():
    # loop start time
    start = time.time()
    # #20506
    r = c.read_holding_registers(20506)
    if r:
      ret = rrdtool.update(RRD_POS, 'N:%d' % r[0])
    # #20492
    r = c.read_holding_registers(20492)
    if r:
      ret = rrdtool.update(RRD_FLOW, 'N:%d' % r[0])
    # #20494
    r = c.read_holding_registers(20494)
    if r:
      ret = rrdtool.update(RRD_SP, 'N:%d' % r[0])
    # loop end time
    end = time.time()
    loop_time = end - start
    # wait before next cycle
    time.sleep(RRD_REFRESH - loop_time)
Esempio n. 44
0
                    is_ok = c.write_single_register(2, 0)
                    if not is_ok:
                        c.open()
            else:
                is_ok = c.write_single_register(3, 0)
                if not is_ok:
                    c.open()


        else:
            # static
            is_ok = c.write_single_register(1, 0)
            if not is_ok:
               c.open()

        reg = c.read_holding_registers(4, 1)
        if reg[0] == 2:
            sys.exit()

        f = open('C.txt', 'a')
        str1 = ''.join(str(alpha_a_int[i]))
        f.write(str1)
        f.write(' ')
        str1 = ''.join(str(alpha_b_int[i]))
        f.write(str1)
        f.write(' ')
        str1 = ''.join(str(omg_a_int[i]))
        f.write(str1)
        f.write(' ')
        str1 = ''.join(str(omg_b_int[i]))
        f.write(str1)