# -*- coding: utf-8 -*-
"""
@file: arcwelding_example.py
@brief: 焊接工艺包接口示例
@copyright: Copyright (C) 2024 ROKAE (Beijing) Technology Co., LTD. All Rights Reserved.
Information in this file is the intellectual property of Rokae Technology Co., Ltd,
And may contains trade secrets that must be stored and viewed confidentially.
"""
import setup_path
import platform
import time
import math
from datetime import timedelta
from concurrent.futures import Future, ThreadPoolExecutor
from typing import List, Tuple, Optional
import inspect
# 根据操作系统导入相应的模块
if platform.system() == 'Windows':
    from Release.windows import xCoreSDK_python
    from Release.windows.xCoreSDK_python import arcwelding
    from Release.windows.xCoreSDK_python.EventInfoKey import ArcWeldState
    from Release.windows.xCoreSDK_python.EventInfoKey import MoveExecution
elif platform.system() == 'Linux':
    from Release.linux import xCoreSDK_python
    from Release.linux.xCoreSDK_python import arcwelding
    from Release.linux.xCoreSDK_python.EventInfoKey import ArcWeldState
    from Release.linux.xCoreSDK_python.EventInfoKey import MoveExecution
else:
    raise ImportError("Unsupported operating system")
from move_example import wait_robot,wait_pos_finish
from log import print_log, print_separator

ArcWelding = arcwelding.ArcWelding
PI = math.pi


def arcwelding_op(robot, arc_welding, ec):
    # set_weld_mode_example(arc_welding, ec) # 设置焊接模式
    # enable_arc_data(arc_welding, ec)  # 生效焊接参数
    # set_arc_on_data_example(arc_welding, ec)  # 读写起弧参数
    # set_arc_data_example(arc_welding, ec)  # 读写焊接参数
    # set_arc_off_data_example(arc_welding, ec)  # 读写收弧参数
    # set_weave_data_example(arc_welding, ec)  # 读写摆动参数
    # set_weave_adaptive_data_example(arc_welding, ec)  # 读写摆动自适应参数
    # set_seg_data_example(arc_welding, ec)  # 读写间断焊参数
    # set_laser_track_data_example(arc_welding, ec)  # 读写激光跟踪参数
    # set_laser_search_data_example(arc_welding, ec)  # 读写激光寻位参数
    # set_io_setting_example(arc_welding, ec)  # 读写IO设置
    # set_characteristic_curve_data_example(arc_welding, ec)  # 读写特性曲线参数
    # set_running_param_example(arc_welding, ec)  # 读写运行参数
    # set_welder_and_connect_example(arc_welding, ec)  # 焊机设置
    # set_eni_have_weld_example(arc_welding, ec)  # ENI焊接设置
    # feed_on_wire_example(arc_welding, ec) # 送丝
    # feed_back_wire_example(arc_welding, ec) # 退丝
    # detect_gas_example(arc_welding, ec) # 检气
    # get_welder_state_example(arc_welding, ec) # 获取焊机状态
    # set_arc_weld_state_watcher(robot, ec) # 设置焊接状态监视
    # query_weld_state_example(robot, ec) # 查询焊接状态
    set_move_state_watcher(robot, ec) # 设置机器人运动状态监视
    # set_and_save_current_voltage_example(arc_welding, ec) # 在线设置和保存电流电压
    # example_welding(arc_welding, ec) # 铆焊
    # example_command(robot, arc_welding, ec) # 焊接指令示例
    wmovecf_example(robot, arc_welding, ec) # 整圆焊接示例
    # set_laser_sensor_state_watcher(robot, ec) # 设置激光传感器状态监视
    # laser_track_example(robot, arc_welding, ec) # 激光传感器器设置
    # laser_auto_cali_example(robot, arc_welding, ec) # 激光传感器自动标定
    # laser_search_example(robot, arc_welding, ec) # 激光寻位示例
    # arc_set_example(robot, ec) # 修改焊接参数
    # seg_on_example(robot, arc_welding, ec) # 间断焊示例
    # laser_track_command_example(robot, arc_welding, ec) # 激光跟踪指令示例
    # FeedOnOrBackWireExample(robot, arc_welding, ec) # 送丝/退丝指令示例
    # set_anticollision(robot, arc_welding, ec) # 防撞器示例
    pass


# 设置焊接模式
def set_weld_mode_example(arc_welding: ArcWelding, ec):
    print_separator("enter SetWeldModeExample")

    weld_mode = arcwelding.WeldMode.TestRun
    arc_welding.setWeldMode(weld_mode, ec)
    print_log("setWeldMode", ec)
    weld_mode_ret = arc_welding.getWeldMode(ec)
    print_log("getWeldMode", ec)
    print_info(f"set: TestRun, return: {weld_mode_ret.name}")
    time.sleep(1)

    weld_mode = arcwelding.WeldMode.Simu
    arc_welding.setWeldMode(weld_mode, ec)
    print_log("setWeldMode", ec)
    weld_mode_ret = arc_welding.getWeldMode(ec)
    print_log("getWeldMode", ec)
    print_info(f"set: Simu, return: {weld_mode_ret.name}")
    time.sleep(1)

    weld_mode = arcwelding.WeldMode.Real
    arc_welding.setWeldMode(weld_mode, ec)
    print_log("setWeldMode", ec)
    weld_mode_ret = arc_welding.getWeldMode(ec)
    print_log("getWeldMode", ec)
    print_info(f"set: Real, return: {weld_mode_ret.name}")


# 设置起弧参数
def set_arc_on_data_example(arc_welding: ArcWelding, ec):
    print_info("enter SetArcOnDataExample")
    # 下发ArcOnData默认值
    arc_on_data_default = arcwelding.ArcOnData()
    arc_welding.setArcOnData(arc_on_data_default, ec)
    print_log("setArcOnData", ec)

    # 下发ArcOnData自定义值
    arc_on_data_custom = arcwelding.ArcOnData()
    arc_on_data_custom.name = "Custom1_name"
    arc_on_data_custom.annotation = "Custom1_annotation"
    arc_on_data_custom.mode = "low_spatter"
    arc_on_data_custom.current_mode = "wire_feed"
    arc_on_data_custom.voltage_mode = "separate"
    arc_on_data_custom.current = 120
    arc_on_data_custom.voltage = 2
    arc_on_data_custom.hold_time = 200
    arc_on_data_custom.detect_time = 500
    arc_on_data_custom.confirm_time = 50
    arc_on_data_custom.preflow_time = 200
    arc_on_data_custom.prearc_time = 50
    arc_on_data_custom.slow_wire_feed_speed = 8
    arc_on_data_custom.pre_wirefeed_time = 10
    arc_on_data_custom.ramp_time = 100
    arc_on_data_custom.re_arcon.enable = True
    arc_on_data_custom.re_arcon.retry_time = 3
    arc_on_data_custom.re_arcon.wire_retract_delay_time = 0
    arc_on_data_custom.re_arcon.wire_retract_time = 100
    arc_on_data_custom.re_arcon.current_step = 10
    arc_on_data_custom.re_arcon.voltage_step = 0.1
    arc_on_data_custom.scratch_arcon.enable = False
    arc_on_data_custom.scratch_arcon.distance = 50
    arc_on_data_custom.scratch_arcon.back_speed = 10
    arc_on_data_custom.scratch_arcon.step = 5
    arc_welding.setArcOnData(arc_on_data_custom, ec)
    print_log("setArcOnData", ec)

    # 获取ArcOnData
    arc_on_data_default_ret = arc_welding.getArcOnData(
        arc_on_data_default.name, ec)
    print_log("getArcOnData", ec)
    arc_on_data_custom_ret = arc_welding.getArcOnData(arc_on_data_custom.name,
                                                      ec)
    print_log("getArcOnData", ec)

    # 打印ArcOnData
    def print_arc_on_data(data: arcwelding.ArcOnData):
        print_info(f"Name: {data.name}")
        print_info(f"Annotation: {data.annotation}")
        print_info(f"Mode: {data.mode}")
        print_info(f"Current Mode: {data.current_mode}")
        print_info(f"Voltage Mode: {data.voltage_mode}")
        print_info(f"Current: {data.current}")
        print_info(f"Voltage: {data.voltage}")
        print_info(f"Hold Time: {data.hold_time}")
        print_info(f"Detect Time: {data.detect_time}")
        print_info(f"Confirm Time: {data.confirm_time}")
        print_info(f"Preflow Time: {data.preflow_time}")
        print_info(f"Prearc Time: {data.prearc_time}")
        print_info(f"Slow Wire Feed Speed: {data.slow_wire_feed_speed}")
        print_info(f"Pre Wirefeed Time: {data.pre_wirefeed_time}")
        print_info(f"Ramp Time: {data.ramp_time}")

        print_info("Re Arc On Parameters:")
        print_info(f"  Enable: {data.re_arcon.enable}")
        print_info(f"  Retry Time: {data.re_arcon.retry_time}")
        print_info(
            f"  Wire Retract Delay Time: {data.re_arcon.wire_retract_delay_time}"
        )
        print_info(f"  Wire Retract Time: {data.re_arcon.wire_retract_time}")
        print_info(f"  Current Step: {data.re_arcon.current_step}")
        print_info(f"  Voltage Step: {data.re_arcon.voltage_step}")

        print_info("Scratch Arc On Parameters:")
        print_info(f"  Enable: {data.scratch_arcon.enable}")
        print_info(f"  Distance: {data.scratch_arcon.distance}")
        print_info(f"  Back Speed: {data.scratch_arcon.back_speed}")
        print_info(f"  Step: {data.scratch_arcon.step}")

    print_arc_on_data(arc_on_data_default_ret)
    print_arc_on_data(arc_on_data_custom_ret)

    # 删除参数
    arc_welding.removeArcOnData("default", ec)
    print_log("removeArcOnData", ec)
    arc_welding.removeArcOnData(["remove1", "remove2"], ec)
    print_log("removeArcOnData", ec)


# 设置焊接参数示例
def set_arc_data_example(arc_welding: ArcWelding, ec):
    print_info("enter SetArcDataExample")
    # 下发ArcData默认值
    arc_data_default = arcwelding.ArcData()
    arc_welding.setArcData(arc_data_default, ec)
    print_log("setArcData", ec)

    # 下发ArcData自定义值
    arc_data_custom = arcwelding.ArcData()
    arc_data_custom.name = "Custom1_name"
    arc_data_custom.annotation = "Custom1_annotation"
    arc_data_custom.mode = "low_spatter"
    arc_data_custom.current_mode = "wire_feed"
    arc_data_custom.voltage_mode = "separate"
    arc_data_custom.current = 80
    arc_data_custom.voltage = 2
    arc_data_custom.weld_speed = 50
    arc_data_custom.ramp_time = 200
    arc_data_custom.arc_break_param.detect_time = 50
    arc_data_custom.arc_break_param.arc_break_option = "stop_and_alarm"
    arc_data_custom.arc_break_param.restart_back_distance = 0
    arc_welding.setArcData(arc_data_custom, ec)
    print_log("setArcData", ec)

    # 获取ArcData
    arc_data_default_ret = arc_welding.getArcData(arc_data_default.name, ec)
    print_log("getArcData", ec)
    arc_data_custom_ret = arc_welding.getArcData(arc_data_custom.name, ec)
    print_log("getArcData", ec)

    # 打印ArcData
    def print_arc_data(data: arcwelding.ArcData):
        print_info(f"Name: {data.name}")
        print_info(f"Annotation: {data.annotation}")
        print_info(f"Mode: {data.mode}")
        print_info(f"Current Mode: {data.current_mode}")
        print_info(f"Voltage Mode: {data.voltage_mode}")
        print_info(f"Current: {data.current}")
        print_info(f"Voltage: {data.voltage}")
        print_info(f"Weld Speed: {data.weld_speed}")
        print_info(f"Ramp Time: {data.ramp_time}")

        print_info("Arc Break Parameters:")
        print_info(f"  Detect Time: {data.arc_break_param.detect_time}")
        print_info(
            f"  Arc Break Option: {data.arc_break_param.arc_break_option}")
        print_info(
            f"  Restart Back Distance: {data.arc_break_param.restart_back_distance}"
        )

    print_arc_data(arc_data_default_ret)
    print_arc_data(arc_data_custom_ret)

    # 删除ArcData
    arc_welding.removeArcData("default", ec)
    print_log("removeArcData", ec)
    arc_welding.removeArcData(["remove1,remove2"], ec)
    print_log("removeArcData", ec)


# 设置收弧参数示例
def set_arc_off_data_example(arc_welding: ArcWelding, ec):
    print_info("SetArcOffDataExample")
    # 下发ArcOffData
    arc_off_data_default = arcwelding.ArcOffData()  # 默认值
    arc_welding.setArcOffData(arc_off_data_default, ec)
    print_log("setArcOffData", ec)

    arc_off_data_custom = arcwelding.ArcOffData()  # 自定义值
    arc_off_data_custom.name = "Custom1_name"
    arc_off_data_custom.annotation = "Custom1_annotation"
    arc_off_data_custom.mode = "low_spatter"
    arc_off_data_custom.current_mode = "wire_feed"
    arc_off_data_custom.voltage_mode = "separate"
    arc_off_data_custom.current = 160
    arc_off_data_custom.voltage = 5
    arc_off_data_custom.hold_time = 200
    arc_off_data_custom.delay_gasoff_time = 200
    arc_off_data_custom.detect_time = 100
    arc_off_data_custom.retract_time = 80
    arc_off_data_custom.wire_stick_detection_time = 80
    arc_off_data_custom.anti_wire_stick_param.enable = False
    arc_off_data_custom.anti_wire_stick_param.current = 0
    arc_off_data_custom.anti_wire_stick_param.voltage = 0
    arc_off_data_custom.anti_wire_stick_param.time = 100
    arc_welding.setArcOffData(arc_off_data_custom, ec)
    print_log("setArcOffData", ec)

    # 获取ArcOffData
    arc_off_data_default_ret = arc_welding.getArcOffData(
        arc_off_data_default.name, ec)
    print_log("getArcOffData", ec)
    arc_off_data_custom_ret = arc_welding.getArcOffData(
        arc_off_data_custom.name, ec)
    print_log("getArcOffData", ec)

    # 打印ArcOffData
    def print_arc_off_data(data: arcwelding.ArcOffData):
        print_info(f"Name: {data.name}")
        print_info(f"Annotation: {data.annotation}")
        print_info(f"Mode: {data.mode}")
        print_info(f"Current Mode: {data.current_mode}")
        print_info(f"Voltage Mode: {data.voltage_mode}")
        print_info(f"Current: {data.current}")
        print_info(f"Voltage: {data.voltage}")
        print_info(f"Hold Time: {data.hold_time}")
        print_info(f"Delay Gas Off Time: {data.delay_gasoff_time}")
        print_info(f"Detect Time: {data.detect_time}")
        print_info(f"Retract Time: {data.retract_time}")
        print_info(
            f"Wire Stick Detection Time: {data.wire_stick_detection_time}")

        print_info("Anti Wire Stick Parameters:")
        print_info(f"  Enable: {data.anti_wire_stick_param.enable}")
        print_info(f"  Current: {data.anti_wire_stick_param.current}")
        print_info(f"  Voltage: {data.anti_wire_stick_param.voltage}")
        print_info(f"  Time: {data.anti_wire_stick_param.time}")

    print_arc_off_data(arc_off_data_default_ret)
    print_arc_off_data(arc_off_data_custom_ret)

    # 删除ArcOffData
    arc_welding.removeArcOffData("default", ec)
    print_log("removeArcOffData", ec)
    arc_welding.removeArcOffData(["remove1,remove2"], ec)
    print_log("removeArcOffData", ec)


# 设置摆动参数
def set_weave_data_example(arc_welding: ArcWelding, ec):
    print_info("enter SetWeaveDataExample")
    # 下发WeaveData
    weave_data_default = arcwelding.WeaveData()  # 默认值
    arc_welding.setWeaveData(weave_data_default, ec)
    print_log("setWeaveData", ec)

    weave_data_custom = arcwelding.WeaveData()  # 自定义值
    weave_data_custom.name = "Custom_name"
    weave_data_custom.annotation = "Custom_annotation"
    weave_data_custom.weaving_reference = "cycle"
    weave_data_custom.pattern = "sine"
    weave_data_custom.weave_length_frequency = 1
    weave_data_custom.amplitude.left = 2
    weave_data_custom.amplitude.right = 2
    weave_data_custom.dwell_type = "weave_stop"
    weave_data_custom.dwell_time = [10, 0, 20]
    weave_data_custom.radius = 5
    weave_data_custom.phase_invert = True
    weave_data_custom.elevation_type = "v_pattern"
    weave_data_custom.elevation_angle.left = 0
    weave_data_custom.elevation_angle.right = 0
    weave_data_custom.inclination_angle = 0
    weave_data_custom.acc = 1
    weave_data_custom.jerk = 10
    arc_welding.setWeaveData(weave_data_custom, ec)
    print_log("setWeaveData", ec)

    # 获取WeaveData
    weave_data_default_ret = arc_welding.getWeaveData(weave_data_default.name,
                                                      ec)
    print_log("getWeaveData", ec)
    weave_data_custom_ret = arc_welding.getWeaveData(weave_data_custom.name,
                                                     ec)
    print_log("getWeaveData", ec)

    # 打印WeaveData
    def print_weave_data(data):
        print_info(f"Name: {data.name}")
        print_info(f"Annotation: {data.annotation}")
        print_info(f"Weaving Reference: {data.weaving_reference}")
        print_info(f"Pattern: {data.pattern}")
        print_info(f"Weave Length Frequency: {data.weave_length_frequency}")

        print_info("Amplitude:")
        print_info(f"  Left: {data.amplitude.left}")
        print_info(f"  Right: {data.amplitude.right}")

        print_info(f"Dwell Type: {data.dwell_type}")
        print_info(
            f"Dwell Time: {data.dwell_time[0]}, {data.dwell_time[1]}, {data.dwell_time[2]}"
        )
        print_info(f"Radius: {data.radius}")
        print_info(f"Phase Invert: {data.phase_invert}")
        print_info(f"Elevation Type: {data.elevation_type}")

        print_info("Elevation Angle:")
        print_info(f"  Left: {data.elevation_angle.left}")
        print_info(f"  Right: {data.elevation_angle.right}")

        print_info(f"Inclination Angle: {data.inclination_angle}")
        print_info(f"Acc: {data.acc}")
        print_info(f"Jerk: {data.jerk}")

    print_weave_data(weave_data_default_ret)
    print_weave_data(weave_data_custom_ret)

    # 删除WeaveData
    arc_welding.removeWeaveData("default", ec)
    print_log("removeWeaveData", ec)
    arc_welding.removeWeaveData(["remove1", "remove2"], ec)
    print_log("removeWeaveData", ec)

# 设置摆动自适应参数
def set_weave_adaptive_data_example(arc_welding: ArcWelding, ec):
    print_info("enter SetWeaveAdaptiveDataExample")
    # 下发WeaveAdaptiveData
    weave_adaptive_data_default = arcwelding.WeaveAdaptiveData()
    weave_adaptive_data_default.isAdaptive = True
    weave_adaptive_data_default.groove_width_standard = 10
    weave_adaptive_data_default.groove_width_ratio = 4
    weave_adaptive_data_default.max_groove_width = 15
    weave_adaptive_data_default.max_electric = 300
    weave_adaptive_data_default.max_speed = 6
    arc_welding.setWeaveAdaptiveData(weave_adaptive_data_default, ec)
    print_log("setWeaveAdaptiveData", ec)

    weave_adaptive_data_ret = arc_welding.getWeaveAdaptiveData(ec)
    print_log("getWeaveAdaptiveData", ec)

    # 打印WeaveAdaptiveData
    def print_weave_adaptive_data(data:arcwelding.WeaveAdaptiveData):
        print_info(f"Is Adaptive: {data.isAdaptive}")
        print_info(f"Groove Width Standard: {data.groove_width_standard}")
        print_info(f"Groove Width Ratio: {data.groove_width_ratio}")
        print_info(f"Max Groove Width: {data.max_groove_width}")
        print_info(f"Max Electric: {data.max_electric}")
        print_info(f"Max Speed: {data.max_speed}")

    print_weave_adaptive_data(weave_adaptive_data_ret)


# 设置间断焊参数示例
def set_seg_data_example(arc_welding: ArcWelding, ec):
    print_info("enter SetSegDataExample")
    # 下发SegData
    seg_data_default = arcwelding.SegData()  # 默认值
    arc_welding.setSegData(seg_data_default, ec)
    print_log("setSegData", ec)

    seg_data_custom = arcwelding.SegData()  # 自定义值
    seg_data_custom.name = "Custom_name"
    seg_data_custom.annotation = "Custom_annotation"
    seg_data_custom.seg_type = "normal"
    seg_data_custom.non_welded_speed = "v10"
    seg_data_custom.welded_distance = 10
    seg_data_custom.non_welded_distance = 20
    arc_welding.setSegData(seg_data_custom, ec)
    print_log("setSegData", ec)

    # 获取SegData
    seg_data_default_ret = arc_welding.getSegData("default", ec)
    print_log("getSegData", ec)
    seg_data_custom_ret = arc_welding.getSegData(seg_data_custom.name, ec)
    print_log("getSegData", ec)

    # 打印SegData
    def print_seg_data(data: arcwelding.SegData):
        print_info(f"Name: {data.name}")
        print_info(f"Annotation: {data.annotation}")
        print_info(f"Segment Type: {data.seg_type}")
        print_info(f"Non-Welded Speed: {data.non_welded_speed}")
        print_info(f"Welded Distance: {data.welded_distance}")
        print_info(f"Non-Welded Distance: {data.non_welded_distance}")

    print_seg_data(seg_data_default_ret)
    print_seg_data(seg_data_custom_ret)

    # 删除SegData
    arc_welding.removeSegData("default", ec)
    print_log("removeSegData", ec)
    arc_welding.removeSegData(["remove1", "remove2"], ec)
    print_log("removeSegData", ec)


# 设置激光跟踪参数示例
def set_laser_track_data_example(arc_welding: ArcWelding, ec):
    print_info("enter SetLaserTrackDataExample")
    # 下发LaserTrackData
    laser_track_data_default = arcwelding.LaserTrackData()  # 默认值
    arc_welding.setLaserTrackData(laser_track_data_default, ec)
    print_log("setLaserTrackData", ec)

    laser_track_data_custom = arcwelding.LaserTrackData()  # 自定义值
    laser_track_data_custom.name = "Custom_name"
    laser_track_data_custom.job_number = 2
    laser_track_data_custom.y_comp = True
    laser_track_data_custom.z_comp = True
    laser_track_data_custom.max_invalid_length = 20
    arc_welding.setLaserTrackData(laser_track_data_custom, ec)
    print_log("setLaserTrackData", ec)

    # 获取LaserTrackData
    laser_track_data_default_ret = arc_welding.getLaserTrackData("default", ec)
    print_log("getLaserTrackData", ec)
    laser_track_data_custom_ret = arc_welding.getLaserTrackData(
        laser_track_data_custom.name, ec)
    print_log("getLaserTrackData", ec)

    # 打印LaserTrackData
    def print_laser_track_data(data: arcwelding.LaserTrackData):
        print_info(f"Name: {data.name}")
        print_info(f"Job Number: {data.job_number}")
        print_info(f"Y Compensation: {data.y_comp}")
        print_info(f"Z Compensation: {data.z_comp}")
        print_info(f"max_invalid_length: {data.max_invalid_length}")

    print_laser_track_data(laser_track_data_default_ret)
    print_laser_track_data(laser_track_data_custom_ret)

    # 删除LaserTrackData
    arc_welding.removeLaserTrackData("default", ec)
    print_log("removeLaserTrackData", ec)
    arc_welding.removeLaserTrackData(["remove1", "remove2"], ec)
    print_log("removeLaserTrackData", ec)


# 设置激光寻位参数示例
def set_laser_search_data_example(arc_welding: ArcWelding, ec):
    print_info("enter SetLaserSearchDataExample")
    # 下发LaserSearchData
    laser_search_data_default = arcwelding.LaserSearchData()  # 默认值
    arc_welding.setLaserSearchData(laser_search_data_default, ec)
    print_log("setLaserSearchData", ec)

    laser_search_data_custom = arcwelding.LaserSearchData()  # 自定义值
    laser_search_data_custom.name = "Custom_name"
    laser_search_data_custom.job_number = 2
    laser_search_data_custom.search_type = "point"
    laser_search_data_custom.search_mode = "continuous"
    laser_search_data_custom.step_length = 3
    laser_search_data_custom.joint_type = "lap_joint"
    arc_welding.setLaserSearchData(laser_search_data_custom, ec)
    print_log("setLaserSearchData", ec)

    # 获取LaserSearchData
    laser_search_data_default_ret = arc_welding.getLaserSearchData(
        "default", ec)
    print_log("getLaserSearchData", ec)
    laser_search_data_custom_ret = arc_welding.getLaserSearchData(
        laser_search_data_custom.name, ec)
    print_log("getLaserSearchData", ec)

    # 打印LaserSearchData
    def print_laser_search_data(data: arcwelding.LaserSearchData):
        print_info(f"Name: {data.name}")
        print_info(f"Job Number: {data.job_number}")
        print_info(f"Search Type: {data.search_type}")
        print_info(f"Search Mode: {data.search_mode}")
        print_info(f"Step Length: {data.step_length}")
        print_info(f"Joint Type: {data.joint_type}")

    print_laser_search_data(laser_search_data_default_ret)
    print_laser_search_data(laser_search_data_custom_ret)

    # 删除LaserSearchData
    arc_welding.removeLaserSearchData("default", ec)
    print_log("removeLaserSearchData", ec)
    arc_welding.removeLaserSearchData(["remove1", "remove2"], ec)
    print_log("removeLaserSearchData", ec)


def set_io_setting_example(arc_welding: ArcWelding, ec):
    print_info("enter SetIOSettingExample")
    # 下发IOSetting
    io_setting = arcwelding.IOSetting()
    io_setting.arc_on = arcwelding.IOData()
    io_setting.arc_on.name = "DO0_1"
    io_setting.arc_on.type = 2
    io_setting.arc_on.bias = -1
    io_setting.arc_on.enable = True
    io_setting.wire_feed = arcwelding.IOData()
    io_setting.wire_feed.name = "DO0_2"
    io_setting.wire_feed.type = 2
    io_setting.wire_feed.bias = -1
    io_setting.wire_feed.enable = True
    io_setting.wire_feed_back = arcwelding.IOData()
    io_setting.wire_feed_back.name = "DO0_0"
    io_setting.wire_feed_back.type = 2
    io_setting.wire_feed_back.bias = -1
    io_setting.wire_feed_back.enable = False
    io_setting.gas_test = arcwelding.IOData()
    io_setting.gas_test.name = "DO0_0"
    io_setting.gas_test.type = 2
    io_setting.gas_test.bias = -1
    io_setting.gas_test.enable = False
    io_setting.positioning_enable = arcwelding.IOData()
    io_setting.positioning_enable.name = "DO0_0"
    io_setting.positioning_enable.type = 2
    io_setting.positioning_enable.bias = -1
    io_setting.positioning_enable.enable = False
    io_setting.arc_on_success = arcwelding.IOData()
    io_setting.arc_on_success.name = "DI0_0"
    io_setting.arc_on_success.type = 1
    io_setting.arc_on_success.bias = -1
    io_setting.arc_on_success.enable = False
    io_setting.positioning_feedback = arcwelding.IOData()
    io_setting.positioning_feedback.name = "DI0_0"
    io_setting.positioning_feedback.type = 1
    io_setting.positioning_feedback.bias = -1
    io_setting.positioning_feedback.enable = False
    io_setting.current_set = arcwelding.IOData()
    io_setting.current_set.name = "register3"
    io_setting.current_set.type = 5
    io_setting.current_set.bias = 0
    io_setting.current_set.enable = True
    io_setting.voltage_set = arcwelding.IOData()
    io_setting.voltage_set.name = "register4"
    io_setting.voltage_set.type = 5
    io_setting.voltage_set.bias = 0
    io_setting.voltage_set.enable = True
    io_setting.current_get = arcwelding.IOData()
    io_setting.current_get.name = "register0"
    io_setting.current_get.type = 5
    io_setting.current_get.bias = 0
    io_setting.current_get.enable = True
    io_setting.voltage_get = arcwelding.IOData()
    io_setting.voltage_get.name = "register2"
    io_setting.voltage_get.type = 5
    io_setting.voltage_get.bias = -1
    io_setting.voltage_get.enable = False
    io_setting.robot_ready = arcwelding.IOData()
    io_setting.robot_ready.name = "DO0_0"
    io_setting.robot_ready.type = 2
    io_setting.robot_ready.bias = -1
    io_setting.robot_ready.enable = True
    io_setting.error = arcwelding.IOData()
    io_setting.error.name = "DI1_1"
    io_setting.error.type = 1
    io_setting.error.bias = 1
    io_setting.error.enable = False
    arc_welding.setIOSetting(io_setting, ec)
    print_log("setIOSetting", ec)

    # 获取IOSetting
    io_setting_ret = arc_welding.getIOSetting(ec)
    print_log("setIOSetting", ec)

    # 打印IOSetting
    def print_io_setting(data: arcwelding.IOSetting):
        print_info("IO Setting:")
        print_io_config("Arc On", data.arc_on)
        print_io_config("Wire Feed", data.wire_feed)
        print_io_config("Wire Feed Back", data.wire_feed_back)
        print_io_config("Gas Test", data.gas_test)
        print_io_config("Positioning Enable", data.positioning_enable)
        print_io_config("Arc On Success", data.arc_on_success)
        print_io_config("Positioning Feedback", data.positioning_feedback)
        print_io_config("Current Set", data.current_set)
        print_io_config("Voltage Set", data.voltage_set)
        print_io_config("Current Get", data.current_get)
        print_io_config("Voltage Get", data.voltage_get)
        print_io_config("Robot Ready", data.robot_ready)
        print_io_config("Error", data.error)

    def print_io_config(label, config: arcwelding.IOData):
        print_info(f"  {label}:")
        print_info(f"    Name: {config.name}")
        print_info(f"    Type: {config.type}")
        print_info(f"    Bias: {config.bias}")
        print_info(f"    Enable: {config.enable}")

    print_io_setting(io_setting_ret)


# 设置模拟量特性曲线示例
def set_characteristic_curve_data_example(arc_welding: ArcWelding, ec):
    print_info("enter SetCharacteristicCurveDataExample")

    def print_characteristic_curve_data(
            data: arcwelding.CharacteristicCurveData):
        print_info(f"Name: {data.name}")
        print_info(f"Intercept: {data.intercept}")
        print_info(f"Slope: {data.slope}")
        print_info("Points:")

        for point in data.points:
            print_info(f"  ({point[0]}, {point[1]})")

    # 下发电流特性曲线参数
    current_curve_data = arcwelding.CharacteristicCurveData()
    current_curve_data.name = "current"
    current_curve_data.points = [(1.0, 200.0), (3.0, 300.0), (4.0, 350.0)]
    arc_welding.setCurrentCharacteristicCurveData(current_curve_data, ec)
    print_log("setCurrentCharacteristicCurveData", ec)

    # 读取电流特性曲线参数
    current_curve_data_ret = arc_welding.getCurrentCharacteristicCurveData(
        current_curve_data.name, ec)
    print_log("getCurrentCharacteristicCurveData", ec)
    # 打印电流特性曲线参数
    print_characteristic_curve_data(current_curve_data_ret)

    # 下发电压特性曲线参数
    voltage_curve_data = arcwelding.CharacteristicCurveData()
    voltage_curve_data.name = "voltage"
    voltage_curve_data.points = [(1.0, 200.0), (3.0, 300.0)]
    arc_welding.setVoltageCharacteristicCurveData(voltage_curve_data, ec)
    print_log("setVoltageCharacteristicCurveData", ec)

    # 读取电压特性曲线参数
    voltage_curve_data_ret = arc_welding.getVoltageCharacteristicCurveData(
        voltage_curve_data.name, ec)
    print_log("getVoltageCharacteristicCurveData", ec)
    # 打印电压特性曲线参数
    print_characteristic_curve_data(voltage_curve_data_ret)

    # 计算电流特性曲线，不保存
    current_curve_data_calculated = arc_welding.calculateCurrentCurve(
        current_curve_data, ec)
    print_log("calculateCurrentCurve", ec)
    print_characteristic_curve_data(current_curve_data_calculated)

    # 计算电压特性曲线，不保存
    voltage_curve_data_calculated = arc_welding.calculateVoltageCurve(
        voltage_curve_data, ec)
    print_log("calculateVoltageCurve", ec)
    print_characteristic_curve_data(voltage_curve_data_calculated)


# 设置运行参数示例
def set_running_param_example(arc_welding: ArcWelding, ec):
    print_info("enter SetRunningParamExample")
    # 下发运行参数
    running_param = arcwelding.ArcWeldRunningParam()
    running_param.test_run_speed = 200
    running_param.wire_feed_speed = 2
    running_param.gas_detect_time = 10
    arc_welding.setRunningParam(running_param, ec)
    print_log("setRunningParam", ec)

    # 读取运行参数
    running_param_ret = arc_welding.getRunningParam(ec)
    print_log("getRunningParam", ec)
    print_info(f"test_run_speed: {running_param_ret.test_run_speed}")
    print_info(f"wire_feed_speed: {running_param_ret.wire_feed_speed}")
    print_info(f"gas_detect_time: {running_param_ret.gas_detect_time}")


# 设置焊机选项和连接焊机示例
def set_welder_and_connect_example(arc_welding: ArcWelding, ec):
    print_info("enter SetWelderAndConnectExample")
    # 设置焊机（方式一）
    arc_welding.setWelder("ethercat", "aotai", "RL/RPL", 500, ec)
    print_log("setWelder", ec)

    # 设置焊机（方式二）
    welder_setting = arcwelding.WelderSetting()
    welder_setting.mfr = "aotai"
    welder_setting.model = "RL/RPL"
    welder_setting.protocol = "ethercat"
    welder_setting.current_type = 500
    welder_setting.current_file = "current1"  # 用于模拟量连接
    welder_setting.voltage_file = "voltage1"  # 用于模拟量连接
    arc_welding.setWelder(welder_setting, ec)
    print_log("setWelder", ec)

    # 读取焊机设置
    welder_setting_ret = arc_welding.getWelderSetting(ec)
    print_log("getWelderSetting", ec)
    print_info(f"mfr: {welder_setting_ret.mfr}")
    print_info(f"model: {welder_setting_ret.model}")
    print_info(f"protocol: {welder_setting_ret.protocol}")
    print_info(f"current_type: {welder_setting_ret.current_type}")
    print_info(f"current_file: {welder_setting_ret.current_file}")
    print_info(f"voltage_file: {welder_setting_ret.voltage_file}")

    # 连接焊机
    arc_welding.connectToWelder(ec)
    print_log("connectToWelder", ec)

    # 断开焊机
    arc_welding.disconnectFromWelder(ec)
    print_log("disconnectFromWelder", ec)


# 切换ENI文件示例
def set_eni_have_weld_example(arc_welding: ArcWelding, ec):
    print_info("enter SetEniHaveWeldExample")
    # 读取是否连接物理焊机（ENI文件）
    eni_have_weld = arc_welding.isEniHaveWeld(ec)
    print_log("isEniHaveWeld", ec)
    print_info(f"eniHaveWeld: {eni_have_weld}")

    # 设置是否连接物理焊机
    arc_welding.setIsEniHaveWeld(True, ec)
    print_log("setIsEniHaveWeld", ec)


# 生效焊接参数
def enable_arc_data(arc_welding: ArcWelding, ec):
    print_info("enter EnableArcData")
    # 不能为虚拟机, 并且需要连接焊机
    arc_data_custom = arcwelding.ArcData()
    arc_data_custom.name = "Custom1_name"
    arc_data_custom.annotation = "Custom1_annotation"
    arc_data_custom.mode = "low_spatter"
    arc_data_custom.current_mode = "wire_feed"
    arc_data_custom.voltage_mode = "separate"
    arc_data_custom.current = 80
    arc_data_custom.voltage = 2
    arc_data_custom.weld_speed = 50
    arc_data_custom.ramp_time = 200
    arc_data_custom.arc_break_param = arcwelding.ArcBreakParam()
    arc_data_custom.arc_break_param.detect_time = 50
    arc_data_custom.arc_break_param.arc_break_option = "stop_and_alarm"
    arc_data_custom.arc_break_param.restart_back_distance = 0
    arc_welding.enableArcData(arc_data_custom, ec)
    print_log("enableArcData", ec)


# 送丝
def feed_on_wire_example(arc_welding: ArcWelding, ec):
    # 需要在启用焊机后执行
    print_info("enter FeedOnWireExample")
    time = 10
    # 送丝
    arc_welding.feedOnWire(time, True, ec)  # 送丝和停止送丝时间参数都要大于0.1
    print_log("feedOnWire", ec)

    # 停止送丝
    arc_welding.feedOnWire(time, False, ec)
    print_log("feedOnWire", ec)


# 退丝
def feed_back_wire_example(arc_welding: ArcWelding, ec):
    # 需要在启用焊机后执行
    print_info("enter FeedBackWireExample")
    time = 10
    # 退丝
    arc_welding.feedBackWire(time, True, ec)  # 退丝和停止退丝时间都要大于0.1
    print_log("feedBackWire", ec)
    # 停止退丝
    arc_welding.feedBackWire(time, False, ec)
    print_log("feedBackWire", ec)


# 检气
def detect_gas_example(arc_welding: ArcWelding, ec):
    # 需要在启用焊机后执行
    print_info("enter DetectGasExample")
    time = 10
    # 检气
    arc_welding.detectGas(time, True, ec)  # 检气和停止检气时间参数都要大于0
    print_log("detectGas", ec)
    # 停止检气
    arc_welding.detectGas(time, False, ec)
    print_log("detectGas", ec)


# 获取焊机状态
def get_welder_state_example(arc_welding: ArcWelding, ec):
    print_info("enter GetWelderStateExample")
    welder_state = arc_welding.getWelderStatus(ec)
    print_log("getWelderStatus", ec)
    print_info(f"state: {welder_state.state}")
    print_info(f"current: {welder_state.current}")
    print_info(f"voltage: {welder_state.voltage}")
    print_info(f"speed: {welder_state.speed}")
    print_info(f"welding_name: {welder_state.welding_name}")
    print_info(f"arc_welding: {welder_state.arc_welding}")
    print_info(f"running_error: {welder_state.running_error['message']}")


def PrintWeldState(info:dict):
    print_info("enter PrintWeldState")
    if (len(info) == 0):
        return
    current = info[ArcWeldState.Current]
    voltage = info[ArcWeldState.Voltage]
    state = info[ArcWeldState.State]
    speed = info[ArcWeldState.Speed]
    error = info[ArcWeldState.RunningError]
    welding_name = info[ArcWeldState.WeldingName]
    arc_welding = info[ArcWeldState.ArcWelding]
    print_info("[焊接状态] current: " + str(current) + ", voltage: " +
               str(voltage) + ", state: " + state + ", speed: " + str(speed))
    print_info("weldingName: " + welding_name + ", arc_welding: " +
               str(arc_welding))
    if info.get(ArcWeldState.WeldingDistance) is not None:
        distance = info[ArcWeldState.WeldingDistance]
        print_info("distance: "+  str(distance))
    if info.get(ArcWeldState.WeldingPathNum) is not None:
        pathNumber = info[ArcWeldState.WeldingPathNum]
        print_info("pathNumber: "+  str(pathNumber))
    print_info("error: " + error["message"])


# 设置焊接状态监视
def set_arc_weld_state_watcher(robot: xCoreSDK_python.BaseRobot, ec):
    print_info("enter SetArcWeldStateWatcher")
    robot.setEventWatcher(xCoreSDK_python.Event.arcWeldState, PrintWeldState,
                          ec)
    print_log("setEventWatcher", ec)


def query_weld_state_example(robot: xCoreSDK_python.BaseRobot, ec):
    # 先调用robot.setEventWatcher(xCoreSDK_python.Event.arcWeldState, PrintWeldState,ec)
    # 与焊接状态监视一起用，容易为空
    print_info("enter QueryWeldStateExample")
    info = robot.queryEventInfo(xCoreSDK_python.Event.arcWeldState, ec)
    print_log("queryEventInfo", ec)
    PrintWeldState(info)


def PrintMoveState(info):
    print_info("enter PrintMoveState")
    print(f"{MoveExecution.ID}:{info[MoveExecution.ID]}")
    print(f"{MoveExecution.ReachTarget}:{info[MoveExecution.ReachTarget]}")
    print(f"{MoveExecution.WaypointIndex}:{info[MoveExecution.WaypointIndex]}")
    print(f"{MoveExecution.Error}:{info[MoveExecution.Error]}")
    print(f"{MoveExecution.Remark}:{info[MoveExecution.Remark]}")


# 设置运动状态监视
def set_move_state_watcher(robot: xCoreSDK_python.BaseRobot, ec):
    print_info("enter setMoveStateWatcher")
    robot.setEventWatcher(xCoreSDK_python.Event.moveExecution, PrintMoveState,
                          ec)
    print_log("setEventWatcher", ec)


# 修改和保存电流电压
def set_and_save_current_voltage_example(arc_welding: ArcWelding, ec):
    print_info("enter SetAndSaveCurrentVoltageExample")
    arc_welding.setCurrentAndVoltage(100, 20, ec)  # 只修改不保存
    print_log("setCurrentAndVoltage", ec)

    arc_welding.saveCurrentAndVoltage(100, 20, ec)  # 只保存不修改
    print_log("saveCurrentAndVoltage", ec)


# 铆焊
def example_welding(arc_welding: ArcWelding, ec):
    print_info("enter ExampleWelding")
    arc_welding.startWelding(100, 0, "unified", ec)  # 一元化模式
    print_log("startWelding", ec)

    arc_welding.startWelding(100, 0, "separate", ec)  # 分别模式
    print_log("startWelding", ec)

    arc_welding.stopWelding(ec)
    print_log("stopWelding", ec)


# 焊接指令
def example_command(robot: xCoreSDK_python.BaseRobot, arc_welding: ArcWelding,
                    ec):
    print_info("enter ExampleCommand")
    # 以下点位基于CR7
    # 需要先启用焊机
    arc_welding.setWelder("ethercat", "aotai", "RL/RPL", 500, ec)  # 设置焊机
    print_log("setWelder", ec)
    arc_welding.connectToWelder(ec)  # 启用和连接焊机
    print_log("connectToWelder", ec)

    arc_welding.setArcOnData(arcwelding.ArcOnData(), ec)
    arc_welding.setArcData(arcwelding.ArcData(), ec)
    arc_welding.setArcOffData(arcwelding.ArcOffData(), ec)

    arcon = arcwelding.ArcOnCommand("default", "default")
    arcoff = arcwelding.ArcOffCommand("default")

    target = xCoreSDK_python.CartesianPosition(
        [0.315189, -0.15, 0.414397, -math.pi, 0.0, math.pi])
    wml = arcwelding.WMoveLCommand(target, 10, 1, "default")  # 直线摆动

    targetMC = xCoreSDK_python.CartesianPosition()
    targetMC.trans = [0.615167, 0.141585, 0.507386]
    targetMC.rpy = [180.000 * math.pi / 180, 0.0, -167.039 * math.pi / 180]

    auxMC = xCoreSDK_python.CartesianPosition()
    auxMC.trans = [0.583553, 0.134309, 0.628928]
    auxMC.rpy = [
        180.000 * math.pi / 180, 11.286 * math.pi / 180,
        -167.039 * math.pi / 180
    ]
    wmc = arcwelding.WMoveCCommand(targetMC, auxMC, 10, 1, "default")  # 圆弧摆动

    weave_data_default = arcwelding.WeaveData()  # 设置摆动参数
    weave_data_default.amplitude.left = 2
    weave_data_default.amplitude.right = 2
    weave_data_default.weave_length_frequency = 2
    arc_welding.setWeaveData(weave_data_default, ec)

    weaveon = arcwelding.WeaveOnCommand("default")
    weaveoff = arcwelding.WeaveOffCommand()

    robot.setMotionControlMode(
        xCoreSDK_python.MotionControlMode.NrtCommandMode, ec)
    print_log("setMotionControlMode", ec)

    id = xCoreSDK_python.PyString()
    absj = xCoreSDK_python.MoveAbsJCommand(
        target=xCoreSDK_python.JointPosition(
            [PI / 2, PI / 6, -PI / 2, 0, -PI / 3, 0]))
    robot.moveAppend(absj, id, ec)
    robot.moveStart(ec)
    wait_robot(robot, ec)

    robot.moveAppend(arcon, id, ec)
    print_log("moveAppend", ec)

    robot.moveAppend(weaveon, id, ec)
    print_log("moveAppend", ec)

    robot.moveAppend(wml, id, ec)
    print_log("moveAppend", ec)

    robot.moveAppend(weaveoff, id, ec)
    print_log("moveAppend", ec)

    robot.moveAppend(arcoff, id, ec)
    print_log("moveAppend", ec)

    robot.setPowerState(True, ec)
    print_log("setPowerState", ec)

    robot.moveStart(ec)
    print_log("moveStart", ec)

    robot.stop(ec)  # 暂停
    print_log("stop", ec)

    robot.moveStart(ec)  # 继续
    print_log("moveStart", ec)

# 整圆焊接示例
def wmovecf_example(robot: xCoreSDK_python.BaseRobot, arc_welding: ArcWelding, ec):
    print_info("enter WMoveCFExample")
    # 点位机型 XMC7-R850-W7G3B4C
    arcon = arcwelding.ArcOnCommand ("arcondata1", "arcdata1")
    arcoff = arcwelding.ArcOffCommand ("arcoffdata1")
    segon = arcwelding.SegOnCommand ("segdata1")
    segooff = arcwelding.SegOffCommand ()
    weaveon = arcwelding.WeaveOnCommand ("weavedata1")
    weaveoff = arcwelding.WeaveOffCommand ()
    p1point = [556.769126, 101.641184, 358.852436, 158.661084, -17.184105, -148.826026]
    p2point = [590.049781, 101.641177, 358.852421, 158.66108, -17.184102, -148.826024]
    p3point = [556.769146, 17.242862, 358.852448, 179.999964, -0.000009, -179.999957]
    p4point = [556.769126, 101.641184, 358.852436, 179.999964, -0.000009, -179.999957]
    p5point = [590.049781, 101.641177, 358.852421, 179.999964, -0.000009, -179.999957]
    p1 = xCoreSDK_python.CartesianPosition(rlPoint2sdkPoint(p1point))
    p2 = xCoreSDK_python.CartesianPosition(rlPoint2sdkPoint(p2point))
    p3 = xCoreSDK_python.CartesianPosition(rlPoint2sdkPoint(p3point))
    p4 = xCoreSDK_python.CartesianPosition(rlPoint2sdkPoint(p4point))
    p5 = xCoreSDK_python.CartesianPosition(rlPoint2sdkPoint(p5point))
    wml = arcwelding.WMoveLCommand(p3, 200, 1)
    wmcf = arcwelding.WMoveCFCommand(p2, p1, 300 / 180.0 * PI)

    # 设置旋转类型
    wmcf.rotType = xCoreSDK_python.MoveCFCommandRotType.constPose
    # wmcf.rotType = xCoreSDK_python.MoveCFCommandRotType.rotAxis
    # wmcf.rotType = xCoreSDK_python.MoveCFCommandRotType.fixedAxis

    id = xCoreSDK_python.PyString()

    # 单独整圆运动
    # robot.moveAppend(arcon, id, ec)
    # robot.moveAppend(wmcf, id, ec)
    # robot.moveAppend(arcoff, id, ec)
    # robot.moveStart(ec)

    # 搭配摆动运动
    # wmcf.setWeaveData("weavedata1", ec)
    # robot.moveAppend(arcon, id, ec)
    # robot.moveAppend(weaveon, id, ec)
    # robot.moveAppend(wmcf, id, ec)
    # robot.moveAppend(weaveoff, id, ec)
    # robot.moveAppend(arcoff, id, ec)
    # robot.moveStart(ec)

    # 搭配间断焊运动
    # robot.moveAppend(arcon, id, ec)
    # robot.moveAppend(segon, id, ec)
    # robot.moveAppend(wmcf, id, ec)
    # robot.moveAppend(segooff, id, ec)
    # robot.moveAppend(arcoff, id, ec)
    # robot.moveStart(ec)

    # 搭配电弧跟踪，需要搭配摆动
    # wmcf.setWeaveData("weavedata1", ec)
    # wmcf.setTrackData("arctrackdata1", ec)
    # robot.moveAppend(arcon, id, ec)
    # robot.moveAppend(weaveon, id, ec)
    # robot.moveAppend(wmcf, id, ec)
    # robot.moveAppend(weaveoff, id, ec)
    # robot.moveAppend(arcoff, id, ec)
    # robot.moveStart(ec)

    # arcdata中设置了断弧回退距离，暂停后继续运动会回退，需要有前置轨迹
    # robot.moveAppend(arcon, id, ec)
    # robot.moveAppend(wml, id, ec)
    # robot.moveAppend(wmcf, id, ec)
    # robot.moveAppend(arcoff, id, ec)
    # robot.moveStart(ec)
    # # time.sleep(3)
    # robot.stop(ec)  # 暂停
    # time.sleep(1)
    # robot.moveStart(ec)  # 继续


def PrintLaserSensorState(info):
    print_info("enter PrintLaserSensorState")
    device_name = info["device_name"]
    connect = info["connect"]
    laser_on = info["laser_state"]
    power_on = info["power_state"]  # 注意：明图传感器没有使能状态，这里的使能状态无效

    print_info("[激光跟踪器状态信息] 设备名称: " + device_name + " 连接:" +
               ("YES " if connect else "NO ") + "激光开启:" +
               ("YES " if laser_on else "NO ") + "使能开启:" +
               ("YES " if power_on else "NO "))


# 激光跟踪器状态监控watch
def set_laser_sensor_state_watcher(robot: xCoreSDK_python.BaseRobot, ec):
    print_info("enter SetLaserSensorStateWatcher")
    robot.setEventWatcher(xCoreSDK_python.Event.lasertrackState,
                          PrintLaserSensorState, ec)
    print_log("setEventWatcher", ec)


# 激光器设置
def laser_track_example(robot: xCoreSDK_python.BaseRobot,
                        arc_welding: ArcWelding, ec):
    print_info("enter LaserTrackExample")
    # 设置激光跟踪器配置信息
    cfg = arcwelding.LaserSensorCfg()
    cfg.name = "sensor1"
    cfg.ip = "192.168.110.92"
    cfg.port = 502
    cfg.overtime = 800
    cfg.communication_cycle = 60
    cfg.type = arcwelding.LaserSensorType.CRNT  # 创想传感器
    # cfg.type = arcwelding.LaserSensorType.SMART_IMAGE  # 明图传感器

    # 发送指令设置AddLaserSensorCfg
    arc_welding.setLaserSensorCfg(cfg, ec)
    print_log("setLaserSensorCfg", ec)

    # 查询设备配置信息
    cfg_get = arc_welding.getLaserSensorCfg(cfg.name, ec)
    print_log("getLaserSensorCfg", ec)
    print_info("name: " + cfg_get.name + "  ip:" + cfg_get.ip)

    # 设置传感器状态监控watch
    set_laser_sensor_state_watcher(robot, ec)

    # 连接激光跟踪器ConnLaserTrack
    arc_welding.connLaserSensorDev(cfg.name, ec)
    print_log("connLaserSensorDev", ec)

    # 开启焊缝跟踪器，开始获取激光传感器数据OpenLaserTrack
    arc_welding.openLaserTrack(cfg.name, ec)
    print_log("openLaserTrack", ec)

    # 关闭焊缝跟踪器CloseLaserTrack
    arc_welding.closeLaserTrack(cfg.name, ec)
    print_log("closeLaserTrack", ec)

    # 断开连接DisConnLaserTrack
    arc_welding.disconnLaserSensorDev(cfg.name, ec)
    print_log("disconnLaserSensorDev", ec)

    # 删除设备配置信息RemoveLaserSensorCfg
    arc_welding.removeLaserSensorCfg(cfg.name, ec)
    print_log("removeLaserSensorCfg", ec)

    # 设置手眼标定结果
    handeyedata0 = arcwelding.HandeyeData()
    handeyedata0.mode = True
    handeyedata0.xyz_abc = [
        29.456, -14.151, 70.047, 4.5006 / 180.0 * math.pi,
        4.0438 / 180.0 * math.pi, -97.358 / 180.0 * math.pi
    ]
    handeyedata0.name = "handeyedata0"
    arc_welding.setHandeyeData(handeyedata0, ec)
    print_log("setHandeyeData", ec)

    # 查询手眼标定结果
    name = "handeyedata0"
    handeyedata0_get = arc_welding.getHandeyeData(name, ec)
    print_log("getHandeyeData", ec)
    print_info(
        f"name: {handeyedata0_get.name}  xyz_abc: {handeyedata0_get.xyz_abc[0]},"
        f"{handeyedata0_get.xyz_abc[2]},{handeyedata0_get.xyz_abc[3]},"
        f"{handeyedata0_get.xyz_abc[4]},{handeyedata0_get.xyz_abc[5]}")

    # 删除手眼标定结果
    arc_welding.removeHandeyeData(name, ec)
    print_log("removeHandeyeData", ec)


def laser_auto_cali_example(robot: xCoreSDK_python.BaseRobot,
                            arc_welding: ArcWelding, ec):
    print_info("enter LaserAutoCali")
    arc_welding.startHandeyeCalibration("handeyedata0", 6, ec)
    print_log("startHandeyeCalibration", ec)

    def print_cali_result(result: arcwelding.CalibrationResult):
        print(f"ID: {result.id}")
        print("Robot Coordinates:", ",".join(map(str, result.p_robot)))
        print("Laser Coordinates:", ",".join(map(str, result.p_laser)))

    # 采集尖端坐标（索引0）
    ret = arc_welding.calibratePoint(0, ec)
    print_log("calibratePoint", ec)
    print_cali_result(ret)

    # 采集1-6号点位坐标
    for i in range(1, 7):
        ret = arc_welding.calibratePoint(i, ec)
        print_log(f"calibratePoint[{i}]", ec)
        print_cali_result(ret)

    # 终止标定并获取结果
    loss = []
    handeyedata = arc_welding.calibrateEnd(loss, ec)
    print_log("calibrateEnd", ec)
    print(f"loss: {','.join(map(str, loss))}")
    print(f"name:{handeyedata.name}")
    print(f"mode:{handeyedata.mode}")
    print(f"xyz_abc {{{','.join(map(str, handeyedata.xyz_abc))}}}")
    print(f"trans {{{','.join(map(str, handeyedata.transVector))}}}")
    print(f"rot {{{','.join(map(str, handeyedata.rotMatrix))}}}")


# 激光寻位
def laser_search_example(robot: xCoreSDK_python.BaseRobot,
                            arc_welding: ArcWelding, ec):
    # 保存手眼标定参数
    handeyedata0 = arcwelding.HandeyeData()
    handeyedata0.mode = True
    handeyedata0.xyz_abc = [29.456, -14.151, 70.047, 4.5006 / 180.0 * math.pi, 4.0438 / 180.0 * math.pi, -97.358 / 180.0 * math.pi]
    handeyedata0.name = "laserhandeyedata1"
    arc_welding.setHandeyeData(handeyedata0, ec)
    print(f"ec: {ec["ec"]}, {ec["message"]}")
    # 保存寻位参数
    laser_search_data = arcwelding.LaserSearchData()
    laser_search_data.name = "lasersearchdata1"
    laser_search_data.job_number =2
    laser_search_data.search_type ="point"
    laser_search_data.search_mode ="continuous"
    laser_search_data.step_length = 3
    laser_search_data.joint_type = "lap_joint"
    arc_welding.setLaserSearchData(laser_search_data, ec)
    print(f"ec: {ec["ec"]}, {ec["message"]}")

    laser_search_pos = xCoreSDK_python.CartesianPosition()
    laser_search_pos.rpy = [3.14, 0, 3.14]
    laser_search_pos.trans = [0.563, 0.3, 0.43]
    laser_search_cmd = arcwelding.LaserSearchCommand("laserhandeyedata1", "lasersearchdata1", laser_search_pos, 10, 0)
    is_found = False
    pos = xCoreSDK_python.CartesianPosition()
    ret = None
    robot.setPowerState(True, ec)

    # 示例中选择同步等待寻位结果，设置超时时间为 30 秒。可根据轨迹速度和长度来设置超时时间。
    timeout = 30
    # 二、寻位并运动
    robot.moveReset(ec)
    ret = arc_welding.executeLaserSearch(laser_search_cmd, True, timedelta(seconds=timeout), ec)
    print(f"ec: {ec["ec"]}, {ec["message"]}")
    is_found = ret[0]
    pos = ret[1]
    print(f"isFound: {is_found}, pos: {', '.join(map(str, pos.trans))}, rpy: {', '.join(map(str, pos.rpy))}")

# 示例 - 电弧跟踪，点位适配机型NB4h-R580-XX
def arc_track_example(robot: xCoreSDK_python.BaseRobot,
                            arc_welding: ArcWelding, ec): 
    # 设置电弧跟踪参数
    param = arcwelding.ArcTrackParam()
    param.name = "arctrackdata1"
    param.annotation = "test1"
    param.delay_time = 5 # 其他的值类似设置就行，这里直接使用默认值
    arc_welding.setArcTrackParam(param,ec)

    # 获取对应的电弧跟踪参数
    param_get = arc_welding.getArcTrackParam(param.name, ec)
    print(f"name: {param_get.name} annotation: {param_get.annotation} delay_time: {param_get.delay_time}")

    # 本例验证时运行于NB4h-R580-3B(注意点位匹配)
    p0 = [0.357487, 0.000633967, 0.222628, 3.0, 0.0685018, 3.12448] 
    p1 = [0.357487, 0.143835, 0.222628, 3.13197, 0.0685018, 3.12448] 
    p2 = [0.456268, 0.000634313, 0.222628, 3.13197, 0.0685026, 3.12448] 
    p3 = [0.456268, 0.143835, 0.222628, 3.13197, 0.0685024, 3.12448] 
    p4 = [0.456268, -0.103198, 0.222628, 3.13197, 0.068502, 3.12448] 

    arcon = arcwelding.ArcOnCommand("arcondata1", "arcdata1")
    arcoff = arcwelding.ArcOffCommand("arcoffdata1")
    mj = xCoreSDK_python.MoveJCommand(p0, 100, 1)

    # 第一条，开启电弧跟踪，用跟踪参数arctrackdata1
    wml1 = arcwelding.WMoveLCommand(p1, 20, 1, "weavedata1", "arctrackdata1")
    # 第二条，开启电弧跟踪，用跟踪参数arctrackdata2
    wml2=arcwelding.WMoveLCommand (p2, 20, 1, "weavedata1", "arctrackdata2")
    # 第三条，电弧跟踪参数为空，不跟踪
    wml3=arcwelding.WMoveLCommand (p3, 20, 1, "weavedata1")
    # 第四条和第五条，开启电弧跟踪，用跟踪参数arctrackdata2
    wml4=arcwelding.WMoveLCommand (p4, 20, 1, "weavedata1", "arctrackdata2")
    wml5=arcwelding.WMoveLCommand (p3, 20, 1, "weavedata1", "arctrackdata2")
    # 第六条，不跟踪
    wml6=arcwelding.WMoveLCommand (p2, 20, 1, "weavedata1") # 直线摆动
    weaveon=arcwelding.WeaveOnCommand ("weavedata1")
    weaveoff=arcwelding.WeaveOffCommand()
    wmove_list = [wml1, wml2, wml3, wml4, wml5, wml6]

    id = xCoreSDK_python.PyString()
    move_id = xCoreSDK_python.PyString()
    robot.setPowerState(True, ec)
    robot.moveAppend(mj, move_id, ec)
    robot.moveAppend(arcon, id, ec) 
    if(ec["ec"]!=0):
        print(f"{inspect.currentframe().f_lineno}: {ec["message"]}")
    robot.moveAppend(weaveon, id, ec)
    if(ec["ec"]!=0):
        print(f"{inspect.currentframe().f_lineno}: {ec["message"]}")
    robot.moveAppend(wmove_list, move_id, ec)
    if(ec["ec"]!=0):
        print(f"{inspect.currentframe().f_lineno}: {ec["message"]}")
    robot.moveAppend(weaveoff, id, ec)
    if(ec["ec"]!=0):
        print(f"{inspect.currentframe().f_lineno}: {ec["message"]}")
    robot.moveAppend(arcoff, id, ec)
    if(ec["ec"]!=0):
        print(f"{inspect.currentframe().f_lineno}: {ec["message"]}")
    robot.moveStart(ec)
    if(ec["ec"]!=0):
        print(f"{inspect.currentframe().f_lineno}: {ec["message"]}")

    from move_example import waitForFinish
    waitForFinish(robot, move_id.content(), len(wmove_list) - 1)
    while -1 != robot.queryEventInfo(xCoreSDK_python.Event.arcWeldState)[xCoreSDK_python.EventInfoKey.ArcWeldState.ArcWelding]:
        # waiting for arc off
        time.sleep(0.01)  # 10 milliseconds
    print("Finish running")


# 动态修改焊接参数
def arc_set_example(robot: xCoreSDK_python.BaseRobot, ec):
    print_info("enter ArcSetExample")
    # 以下点位基于SR5
    cmd_id = xCoreSDK_python.PyString()
    arc_on_command = arcwelding.ArcOnCommand()
    arc_off_command = arcwelding.ArcOffCommand()
    absj = xCoreSDK_python.MoveAbsJCommand(
        target=xCoreSDK_python.JointPosition(
            [0, math.pi / 6, -math.pi / 2, 0, -math.pi / 3, 0]),
        speed=1000)

    l = xCoreSDK_python.MoveLCommand(target=xCoreSDK_python.CartesianPosition(
        [0.614, 0.136, 0.389, -math.pi, 0, math.pi]),
                                     speed=500)
    wml_target1 = xCoreSDK_python.CartesianPosition(
        [0.553, -0.107, 0.309, -math.pi, 0, math.pi])
    wmovel1 = arcwelding.WMoveLCommand(target=wml_target1, speed=500)
    wml_target2 = xCoreSDK_python.CartesianPosition(
        [0.553, 0.107, 0.309, -math.pi, 0, math.pi])
    wmovel2 = arcwelding.WMoveLCommand(target=wml_target2, speed=500)
    wmovel2.arc_set_opt.arc_data = "arcdata1"
    wmovel2.arc_set_opt.ref_start = True
    wmovel2.arc_set_opt.distance = 80

    robot.setPowerState(True, ec)
    print_log("setPowerState", ec)

    robot.moveAppend(absj, cmd_id, ec)
    print_log("moveAppend", ec)

    robot.moveAppend(l, cmd_id, ec)
    print_log("moveAppend", ec)

    robot.moveAppend(arc_on_command, cmd_id, ec)
    print_log("moveAppend", ec)

    wmls = [wmovel1, wmovel2]
    robot.moveAppend(wmovel1, cmd_id, ec)
    robot.moveAppend(wmls, cmd_id, ec)
    print_log("moveAppend", ec)

    robot.moveAppend(arc_off_command, cmd_id, ec)
    print_log("moveAppend", ec)

    robot.moveStart(ec)
    print_log("moveStart", ec)

    input()
    robot.setPowerState(False, ec)
    print_log("setPowerState", ec)


# 间断焊
def seg_on_example(robot: xCoreSDK_python.BaseRobot, arc_welding: ArcWelding,
                   ec):
    print_info("enter segOnExample")
    # 以下点位基于SR5
    # 根据起始轴角度，计算笛卡尔位姿
    drag_posture = [0, math.pi / 6, -math.pi / 2, 0, -math.pi / 3, 0]
    p_start = robot.model().calcFk(drag_posture, ec)
    print_info(f"start pose: {p_start}")

    # 设置间断焊参数
    seg_data = arcwelding.SegData()
    seg_data.name = "segdata1"
    seg_data.annotation = "segannotation"
    seg_data.seg_type = "normal"
    seg_data.non_welded_speed = "v5"
    seg_data.welded_distance = 15
    seg_data.non_welded_distance = 30
    arc_welding.setSegData(seg_data, ec)
    # 开始间断焊指令，设置间断焊参数为segdata1
    seg_on_cmd = arcwelding.SegOnCommand("segdata1")
    seg_off_cmd = arcwelding.SegOffCommand()
    # 几条焊接运动指令
    seg_wmovel0 = arcwelding.WMoveLCommand(target=p_start, speed=2000, zone=0)
    seg_wmovel0.offset.type = xCoreSDK_python.CartesianPositionOffsetType.offs
    seg_wmovel0.offset.frame.trans = [0, -0.11, -0.12]
    seg_wmovel1 = arcwelding.WMoveLCommand(target=p_start, speed=20, zone=0)
    seg_wmovel1.offset.type = xCoreSDK_python.CartesianPositionOffsetType.offs
    seg_wmovel1.offset.frame.trans = [0, 0.08, -0.02]
    seg_wmc = arcwelding.WMoveCCommand(target=p_start,
                                       aux=p_start,
                                       speed=10,
                                       zone=0)
    seg_wmc.targetOffset.type = xCoreSDK_python.CartesianPositionOffsetType.offs
    seg_wmc.targetOffset.frame.trans = [0, -0.05, 0.01]
    seg_wmc.auxOffset.type = xCoreSDK_python.CartesianPositionOffsetType.offs
    seg_wmc.auxOffset.frame.trans = [0, 0.070, 0]

    non_seg_wmovl = arcwelding.WMoveLCommand(target=p_start, speed=20, zone=1)
    non_seg_wmovl.offset.type = xCoreSDK_python.CartesianPositionOffsetType.offs
    non_seg_wmovl.offset.frame.trans = [-0.05, 0, 0]

    arc_on_cmd = arcwelding.ArcOnCommand("arcondata1", "arcdata1")
    arc_off_cmd = arcwelding.ArcOffCommand("arcoffdata1")
    absj = xCoreSDK_python.MoveAbsJCommand(
        target=xCoreSDK_python.JointPosition(
            [0, math.pi / 6, -math.pi / 2, 0, -math.pi / 3, 0]),
        speed=500)
    weave_on_command = arcwelding.WeaveOnCommand("weavedata1")
    weave_off_cmd = arcwelding.WeaveOffCommand()

    id = xCoreSDK_python.PyString()
    robot.setPowerState(True, ec)
    robot.moveAppend(absj, id, ec)
    robot.moveStart(ec)
    while True:
        time.sleep(1)
        st = robot.operationState(ec)
        if st == xCoreSDK_python.OperationState.idle or st == xCoreSDK_python.OperationState.unknown:
            break
    print_info("运动到初始点")

    robot.moveAppend(arc_on_cmd, id, ec)
    robot.moveAppend(weave_on_command, id, ec)
    robot.moveAppend(seg_on_cmd, id, ec)
    wmovels = [seg_wmovel0, seg_wmovel1]
    robot.moveAppend(wmovels, id, ec)
    robot.moveAppend(seg_wmc, id, ec)
    robot.moveAppend(seg_off_cmd, id, ec)
    robot.moveAppend(non_seg_wmovl, id, ec)
    robot.moveAppend(weave_off_cmd, id, ec)
    robot.moveAppend(arc_off_cmd, id, ec)
    robot.moveStart(ec)


def laser_track_command_example(robot: xCoreSDK_python.BaseRobot,
                                arc_welding: ArcWelding, ec):
    # 先连接激光器
    # 设置激光跟踪器配置信息
    cfg = arcwelding.LaserSensorCfg()
    cfg.name = "sensor1"
    cfg.ip = "192.168.110.92"
    cfg.port = 502
    cfg.overtime = 800
    cfg.communication_cycle = 60
    cfg.type = arcwelding.LaserSensorType.CRNT  # 创想传感器

    arc_welding.setLaserSensorCfg(cfg, ec)
    print_log("setLaserSensorCfg", ec)

    # 设置传感器状态监控watch
    set_laser_sensor_state_watcher(robot, ec)

    arc_welding.connLaserSensorDev(cfg.name, ec)
    print_log("connLaserSensorDev", ec)
    time.sleep(2)

    laser_track_on_cmd = arcwelding.LaserTrackOnCommand(
    )  # 默认手眼标定参数和激光跟踪参数名为"default"
    laser_track_off_cmd = arcwelding.LaserTrackOffCommand()
    id = xCoreSDK_python.PyString()
    robot.setPowerState(True, ec)

    robot.moveAppend(laser_track_on_cmd, id, ec)
    robot.moveAppend(laser_track_off_cmd, id, ec)
    robot.moveStart(ec)
    print_log("moveStart", ec)


# 送丝/退丝
def FeedOnOrBackWireExample(robot: xCoreSDK_python.BaseRobot,
                      arc_welding: ArcWelding, ec):
    robot.setPowerState(True, ec)

    ftime = xCoreSDK_python.PyTypeDouble()
    fspeed = xCoreSDK_python.PyTypeDouble()
    fenable = xCoreSDK_python.PyTypeBool()
    id = xCoreSDK_python.PyString()

    feed_on_cmd = arcwelding.FeedOnWireCommand(0.1)    # 送丝指令 时间单位为秒，送丝速度单位为m/min 默认送丝速度为1.0 m/min, 送丝默认生效
    feed_on_cmd.setFeedOnWireData(0.2, 1.2, True, ec)    # 设置送丝参数
    feed_on_cmd.getFeedOnWireData(ftime, fspeed, fenable) # 获取送丝参数
    print_info(f"Feed On Wire, time: {ftime.content()}, speed: {fspeed.content()}, isFeed: {fenable.content()}")

    feed_back_cmd = arcwelding.FeedBackWireCommand(0.1)     # 退丝指令 时间单位为秒，送丝速度单位为m/min 默认退丝速度为1.0 m/min, 退丝默认生效
    feed_back_cmd.setFeedBackWireData(0.3, 1.3, True, ec)     # 设置退丝参数
    feed_back_cmd.getFeedBackWireData(ftime, fspeed, fenable)  # 获取退丝参数
    print_info(f"Feed Back Wire, time: {ftime.content()}, speed: {fspeed.content()}, isReverse: {fenable.content()}")

    robot.moveAppend(feed_on_cmd, id, ec)
    robot.moveAppend(feed_back_cmd, id, ec)
    robot.moveStart(ec)
    print_log("moveStart", ec)

    robot.setPowerState(False, ec)
    

def PrintAnticollisionState(info):
    print_info("enter PrintAnticollisionState")
    signal = info["signal"]
    enable = info["enable"]
    block = info["block"]
    countdown = info["countdown"]
    print_info("anticollision: \n" + f"signale: {signal}\n" +
               f"enable: {enable}\n" + f"block: {block}\n" +
               f"countdown: {countdown}")


# 设置防撞器
def set_anticollision(robot: xCoreSDK_python.BaseRobot,
                      arc_welding: ArcWelding, ec):
    robot.setEventWatcher(xCoreSDK_python.Event.anticollisionState,
                          PrintAnticollisionState, ec)
    print_log("setEventWatcher", ec)

    arc_welding.setAnticollision("DI0_2", True, False, 30, ec)
    print_log("setAnticollision", ec)

    ret = arc_welding.getAnticollisionState(ec)
    print_log("getAnticollisionState", ec)

    print_info("anticollision: \n" + f"signale: {ret.signal}\n" +
               f"enable: {ret.enable}\n" + f"block: {ret.block}\n" +
               f"countdown: {ret.countdown}")

    while True:
        pass


def print_info(info):
    print(info)

def rlPoint2sdkPoint(rlpoint: list) -> list:
    """将机器人坐标系下的点转换为SDK坐标系下的点"""
    sdkpoint = [rlpoint[i] / 1000.0 if i < 3 else rlpoint[i] * math.pi / 180.0 for i in range(6)]
    return sdkpoint


if __name__ == '__main__':
    try:
        # 连接机器人
        # 不同的机器人对应不同的类型
        ip = "192.168.0.160"
        robot = xCoreSDK_python.xMateRobot(ip)
        ec = {}
        arc_welding = robot.arcwelding()
        arcwelding_op(robot, arc_welding, ec)
        # 结束时需要关闭打开的监视器
        robot.setNoneEventWatcher(xCoreSDK_python.Event.moveExecution, ec)
        robot.setNoneEventWatcher(xCoreSDK_python.Event.anticollisionState, ec)
        robot.setNoneEventWatcher(xCoreSDK_python.Event.arcWeldState, ec)
        robot.setNoneEventWatcher(xCoreSDK_python.Event.lasertrackState, ec)
    except Exception as e:
        print(f"An error occurred: {e}")
