#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
VWED在线脚本Modbus使用示例
演示如何在脚本中使用Modbus功能
"""

import sys
import os
import time

# 添加项目根目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from services.online_script.script_vwed_objects import create_vwed_object


def modbus_script_example():
    """模拟在线脚本中使用Modbus功能"""
    
    print("VWED在线脚本 - Modbus使用示例")
    print("="*50)
    
    # 创建VWED对象（模拟脚本环境）
    VWED = create_vwed_object("example_script")
    
    # Modbus服务器配置
    MODBUS_HOST = "localhost"
    MODBUS_PORT = 5020
    SLAVE_ID = 1
    
    print(f"连接到Modbus服务器: {MODBUS_HOST}:{MODBUS_PORT}")
    print(f"从站ID: {SLAVE_ID}")
    
    # 示例1: 基础读取操作
    print("\n示例1: 基础读取操作")
    print("-" * 30)
    
    # 读取保持寄存器
    value = VWED.modbus.read_holding_register(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, 2)
    print(f"保持寄存器[0]: {value}")
    
    # 读取输入寄存器  
    value = VWED.modbus.read_input_register(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, 2)
    print(f"输入寄存器[0]: {value}")
    
    # 读取线圈状态
    value = VWED.modbus.read_coil_status(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0)
    print(f"线圈[0]: {value}")
    
    # 读取离散输入
    value = VWED.modbus.read_input_status(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0)
    print(f"离散输入[0]: {value}")
    
    # 示例2: 批量读取操作
    print("\n示例2: 批量读取操作")
    print("-" * 30)
    
    # 批量读取保持寄存器
    values = VWED.modbus.batch_read_holding_registers(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, 5)
    print(f"保持寄存器[0-4]: {values}")
    
    # 批量读取输入寄存器
    values = VWED.modbus.batch_read_input_registers(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, 5)
    print(f"输入寄存器[0-4]: {values}")
    
    # 示例3: 写入操作
    print("\n示例3: 写入操作")
    print("-" * 30)
    
    # 写入保持寄存器
    success = VWED.modbus.write_holding_register(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, 2, 12345)
    print(f"写入保持寄存器[0] = 12345: {'成功' if success else '失败'}")
    
    # 验证写入结果
    value = VWED.modbus.read_holding_register(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, 2)
    print(f"验证读取结果: {value}")
    
    # 写入线圈
    success = VWED.modbus.write_coil_status(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 1, True)
    print(f"写入线圈[1] = True: {'成功' if success else '失败'}")
    
    # 验证写入结果
    value = VWED.modbus.read_coil_status(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 1)
    print(f"验证读取结果: {value}")
    
    # 示例4: 批量写入操作
    print("\n示例4: 批量写入操作")
    print("-" * 30)
    
    # 批量写入保持寄存器
    test_values = [1000, 2000, 3000, 4000, 5000]
    success = VWED.modbus.batch_write_holding_register(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, test_values)
    print(f"批量写入保持寄存器[0-4]: {'成功' if success else '失败'}")
    
    # 验证结果
    values = VWED.modbus.batch_read_holding_registers(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, 5)
    print(f"验证读取结果: {values}")
    
    # 批量写入线圈
    coil_values = [True, False, True, False, True]
    success = VWED.modbus.batch_write_coil_status(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, coil_values)
    print(f"批量写入线圈[0-4]: {'成功' if success else '失败'}")
    
    # 验证结果
    values = VWED.modbus.batch_read_coil_status(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, 0, 5)
    print(f"验证读取结果: {values}")
    
    # 示例5: 通用读写操作
    print("\n示例5: 通用读写操作")
    print("-" * 30)
    
    # 使用通用方法读取不同类型的地址
    type_names = {
        '0x': '线圈',
        '1x': '离散输入', 
        '3x': '输入寄存器',
        '4x': '保持寄存器'
    }
    
    for type_str, name in type_names.items():
        value = VWED.modbus.read_single_modbus_value(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, type_str, 0)
        print(f"{name}[0] (类型{type_str}): {value}")
    
    # 通用写入（只对可写类型）
    success = VWED.modbus.write_single_modbus_value(MODBUS_HOST, MODBUS_PORT, SLAVE_ID, '4x', 10, 9999)
    print(f"通用写入保持寄存器[10] = 9999: {'成功' if success else '失败'}")
    
    # 示例6: 使用预配置实例
    print("\n示例6: 使用预配置实例")
    print("-" * 30)
    
    # 配置一个Modbus实例
    VWED.modbus.configure_modbus_instance("PLC1", MODBUS_HOST, MODBUS_PORT, SLAVE_ID, "4x")
    print("已配置实例: PLC1")
    
    # 使用实例名称进行操作
    value = VWED.modbus.read_single_modbus_value_by_instance_name("PLC1", 0)
    print(f"通过实例PLC1读取[0]: {value}")
    
    success = VWED.modbus.write_single_modbus_value_by_instance_name("PLC1", 0, 8888)
    print(f"通过实例PLC1写入[0] = 8888: {'成功' if success else '失败'}")
    
    # 验证结果
    value = VWED.modbus.read_single_modbus_value_by_instance_name("PLC1", 0)
    print(f"验证结果: {value}")
    
    # 示例7: 模拟实际应用场景
    print("\n示例7: 模拟实际应用场景")
    print("-" * 30)
    
    # 配置多个设备实例
    VWED.modbus.configure_modbus_instance("温度传感器", MODBUS_HOST, MODBUS_PORT, SLAVE_ID, "3x")
    VWED.modbus.configure_modbus_instance("控制器", MODBUS_HOST, MODBUS_PORT, SLAVE_ID, "4x")
    
    # 读取传感器数据
    temperature = VWED.modbus.read_single_modbus_value_by_instance_name("温度传感器", 0)
    humidity = VWED.modbus.read_single_modbus_value_by_instance_name("温度传感器", 1)
    print(f"温度: {temperature}, 湿度: {humidity}")
    
    # 根据传感器数据控制设备
    if temperature and temperature > 150:  # 假设温度过高
        # 启动冷却系统
        success = VWED.modbus.write_single_modbus_value_by_instance_name("控制器", 0, 1)
        print(f"温度过高({temperature})，启动冷却系统: {'成功' if success else '失败'}")
    else:
        # 关闭冷却系统
        success = VWED.modbus.write_single_modbus_value_by_instance_name("控制器", 0, 0)
        print(f"温度正常({temperature})，关闭冷却系统: {'成功' if success else '失败'}")
    
    print("\n示例脚本执行完成！")


def main():
    """主函数"""
    try:
        modbus_script_example()
    except Exception as e:
        print(f"脚本执行出错: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()