|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Multi-Device Modbus RTU Scanner |
| 4 | +
|
| 5 | +This script scans for multiple Modbus RTU devices connected to a serial port |
| 6 | +via RS485. It tests different unit IDs and function codes to identify all |
| 7 | +connected devices. |
| 8 | +""" |
| 9 | + |
| 10 | +import sys |
| 11 | +import logging |
| 12 | +import argparse |
| 13 | +from typing import List, Dict, Any, Tuple |
| 14 | + |
| 15 | +# Configure logging |
| 16 | +logging.basicConfig( |
| 17 | + level=logging.INFO, |
| 18 | + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
| 19 | +) |
| 20 | +logger = logging.getLogger("ModbusScanner") |
| 21 | + |
| 22 | +# Import the ModbusRTU client |
| 23 | +import os |
| 24 | +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) |
| 25 | +from modapi.api.rtu import ModbusRTU |
| 26 | + |
| 27 | + |
| 28 | +def scan_device(client: ModbusRTU, unit_id: int) -> Dict[str, Any]: |
| 29 | + """ |
| 30 | + Scan a specific unit ID for supported function codes and register ranges |
| 31 | + |
| 32 | + Args: |
| 33 | + client: ModbusRTU client instance |
| 34 | + unit_id: Unit ID to scan |
| 35 | + |
| 36 | + Returns: |
| 37 | + Dict with device information and supported functions |
| 38 | + """ |
| 39 | + device_info = { |
| 40 | + "unit_id": unit_id, |
| 41 | + "connected": False, |
| 42 | + "supported_functions": [], |
| 43 | + "coils": None, |
| 44 | + "discrete_inputs": None, |
| 45 | + "holding_registers": None, |
| 46 | + "input_registers": None, |
| 47 | + } |
| 48 | + |
| 49 | + # Test connection by reading first coil |
| 50 | + logger.info(f"Testing connection to unit ID {unit_id}...") |
| 51 | + |
| 52 | + # Test read_coils (function code 0x01) |
| 53 | + try: |
| 54 | + result = client.read_coils(unit_id=unit_id, address=0, count=1) |
| 55 | + if result is not None: |
| 56 | + device_info["connected"] = True |
| 57 | + device_info["supported_functions"].append("read_coils") |
| 58 | + device_info["coils"] = result |
| 59 | + logger.info(f"Unit {unit_id}: read_coils supported, result: {result}") |
| 60 | + except Exception as e: |
| 61 | + logger.debug(f"Unit {unit_id}: read_coils failed: {e}") |
| 62 | + |
| 63 | + # Test read_discrete_inputs (function code 0x02) |
| 64 | + try: |
| 65 | + result = client.read_discrete_inputs(unit_id=unit_id, address=0, count=1) |
| 66 | + if result is not None: |
| 67 | + device_info["connected"] = True |
| 68 | + device_info["supported_functions"].append("read_discrete_inputs") |
| 69 | + device_info["discrete_inputs"] = result |
| 70 | + logger.info(f"Unit {unit_id}: read_discrete_inputs supported, result: {result}") |
| 71 | + except Exception as e: |
| 72 | + logger.debug(f"Unit {unit_id}: read_discrete_inputs failed: {e}") |
| 73 | + |
| 74 | + # Test read_holding_registers (function code 0x03) |
| 75 | + try: |
| 76 | + result = client.read_holding_registers(unit_id=unit_id, address=0, count=1) |
| 77 | + if result is not None: |
| 78 | + device_info["connected"] = True |
| 79 | + device_info["supported_functions"].append("read_holding_registers") |
| 80 | + device_info["holding_registers"] = result |
| 81 | + logger.info(f"Unit {unit_id}: read_holding_registers supported, result: {result}") |
| 82 | + except Exception as e: |
| 83 | + logger.debug(f"Unit {unit_id}: read_holding_registers failed: {e}") |
| 84 | + |
| 85 | + # Test read_input_registers (function code 0x04) |
| 86 | + try: |
| 87 | + result = client.read_input_registers(unit_id=unit_id, address=0, count=1) |
| 88 | + if result is not None: |
| 89 | + device_info["connected"] = True |
| 90 | + device_info["supported_functions"].append("read_input_registers") |
| 91 | + device_info["input_registers"] = result |
| 92 | + logger.info(f"Unit {unit_id}: read_input_registers supported, result: {result}") |
| 93 | + except Exception as e: |
| 94 | + logger.debug(f"Unit {unit_id}: read_input_registers failed: {e}") |
| 95 | + |
| 96 | + return device_info |
| 97 | + |
| 98 | + |
| 99 | +def scan_unit_id_range(client: ModbusRTU, start_id: int = 1, end_id: int = 10) -> List[Dict[str, Any]]: |
| 100 | + """ |
| 101 | + Scan a range of unit IDs for Modbus devices |
| 102 | + |
| 103 | + Args: |
| 104 | + client: ModbusRTU client instance |
| 105 | + start_id: Starting unit ID |
| 106 | + end_id: Ending unit ID |
| 107 | + |
| 108 | + Returns: |
| 109 | + List of dictionaries with device information |
| 110 | + """ |
| 111 | + devices = [] |
| 112 | + |
| 113 | + for unit_id in range(start_id, end_id + 1): |
| 114 | + logger.info(f"Scanning unit ID {unit_id}...") |
| 115 | + device_info = scan_device(client, unit_id) |
| 116 | + |
| 117 | + if device_info["connected"]: |
| 118 | + devices.append(device_info) |
| 119 | + logger.info(f"Found device at unit ID {unit_id}") |
| 120 | + logger.info(f"Supported functions: {device_info['supported_functions']}") |
| 121 | + else: |
| 122 | + logger.info(f"No device found at unit ID {unit_id}") |
| 123 | + |
| 124 | + return devices |
| 125 | + |
| 126 | + |
| 127 | +def main(): |
| 128 | + """Main function to run the scanner""" |
| 129 | + parser = argparse.ArgumentParser(description='Modbus RTU Multi-Device Scanner') |
| 130 | + parser.add_argument('--port', type=str, default='/dev/ttyACM0', |
| 131 | + help='Serial port to use (default: /dev/ttyACM0)') |
| 132 | + parser.add_argument('--baudrate', type=int, default=9600, |
| 133 | + help='Baudrate to use (default: 9600)') |
| 134 | + parser.add_argument('--timeout', type=float, default=1.0, |
| 135 | + help='Communication timeout in seconds (default: 1.0)') |
| 136 | + parser.add_argument('--start-id', type=int, default=1, |
| 137 | + help='Starting unit ID to scan (default: 1)') |
| 138 | + parser.add_argument('--end-id', type=int, default=10, |
| 139 | + help='Ending unit ID to scan (default: 10)') |
| 140 | + parser.add_argument('--debug', action='store_true', |
| 141 | + help='Enable debug logging') |
| 142 | + |
| 143 | + args = parser.parse_args() |
| 144 | + |
| 145 | + if args.debug: |
| 146 | + logger.setLevel(logging.DEBUG) |
| 147 | + |
| 148 | + logger.info(f"Starting Modbus RTU scanner on {args.port} at {args.baudrate} baud") |
| 149 | + logger.info(f"Scanning unit IDs from {args.start_id} to {args.end_id}") |
| 150 | + |
| 151 | + # Create and connect ModbusRTU client |
| 152 | + client = ModbusRTU( |
| 153 | + port=args.port, |
| 154 | + baudrate=args.baudrate, |
| 155 | + timeout=args.timeout |
| 156 | + ) |
| 157 | + |
| 158 | + if not client.connect(): |
| 159 | + logger.error(f"Failed to connect to {args.port}") |
| 160 | + return 1 |
| 161 | + |
| 162 | + try: |
| 163 | + # Scan for devices |
| 164 | + devices = scan_unit_id_range(client, args.start_id, args.end_id) |
| 165 | + |
| 166 | + # Print results |
| 167 | + logger.info("\n--- SCAN RESULTS ---") |
| 168 | + if devices: |
| 169 | + logger.info(f"Found {len(devices)} Modbus RTU device(s):") |
| 170 | + for device in devices: |
| 171 | + logger.info(f"Unit ID: {device['unit_id']}") |
| 172 | + logger.info(f" Supported functions: {device['supported_functions']}") |
| 173 | + if 'read_coils' in device['supported_functions']: |
| 174 | + logger.info(f" Coils: {device['coils']}") |
| 175 | + if 'read_discrete_inputs' in device['supported_functions']: |
| 176 | + logger.info(f" Discrete inputs: {device['discrete_inputs']}") |
| 177 | + if 'read_holding_registers' in device['supported_functions']: |
| 178 | + logger.info(f" Holding registers: {device['holding_registers']}") |
| 179 | + if 'read_input_registers' in device['supported_functions']: |
| 180 | + logger.info(f" Input registers: {device['input_registers']}") |
| 181 | + else: |
| 182 | + logger.info("No Modbus RTU devices found.") |
| 183 | + |
| 184 | + finally: |
| 185 | + # Disconnect client |
| 186 | + client.disconnect() |
| 187 | + |
| 188 | + return 0 |
| 189 | + |
| 190 | + |
| 191 | +if __name__ == "__main__": |
| 192 | + sys.exit(main()) |
0 commit comments