# Copyright 2015 - RoboDK Global, SLU - https://robodk.com/
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# ----------------------------------------------------
# This file is a POST PROCESSOR for Robot Offline Programming to generate programs
#
# To edit/test this POST PROCESSOR script file:
# Select "Program"->"Add/Edit Post Processor", then select your post or create a new one.
# You can edit this file using any text editor or Python editor. Using a Python editor allows to quickly evaluate a sample program at the end of this file.
# Python should be automatically installed with RoboDK
#
# You can also edit the POST PROCESSOR manually:
#    1- Open the *.py file with Python IDLE (right click -> Edit with IDLE)
#    2- Make the necessary changes
#    3- Run the file to open Python Shell: Run -> Run module (F5 by default)
#    4- The "test_post()" function is called automatically
# Alternatively, you can edit this file using a text editor and run it with Python
#
# To use a POST PROCESSOR file you must place the *.py file in "C:/RoboDK/Posts/"
# To select one POST PROCESSOR for your robot in RoboDK you must follow these steps:
#    1- Open the robot panel (double click a robot)
#    2- Select "Parameters"
#    3- Select "Unlock advanced options"
#    4- Select your post as the file name in the "Robot brand" box
#
# To delete an existing POST PROCESSOR script, simply delete this file (.py file)
#
# ----------------------------------------------------
# More information about RoboDK Post Processors and Offline Programming here:
#     https://robodk.com/help#PostProcessor
#     https://robodk.com/doc/en/PythonAPI/postprocessor.html
# ----------------------------------------------------


# ----------------------------------------------------
# Description
# Generates a standalone Python script that connects to a Comau e.DO robot
# (websocket / rosbridge) and runs the program using the pyedo library.
#
# Supported Controllers
# Comau e.DO (6 axes + gripper) through pyedo (pip install pyedo roslibpy pynput)
# ----------------------------------------------------

# ----------------------------------------------------
# Special commands for RoboDK before post processing
# Use the same commands available with "RDK.Command()"
# Do not use multi-line! RDK_COMMANDS = {} must be a single line!
#
# Example:
#
# RDK_COMMANDS = {
#     "ProgMoveNames": "1",  # Tools->Options->Program->Export target names
#     "ProgMoveExtAxesPoses": "1",  # Tools->Options->Program->Export external axes poses
#     "MoveLSplitMM": "2", # Force-split linear movements into smaller joint movements
#     "MoveCSplitMM": "2",
#     "MoveCSplitDeg": "90",
#     "MoveCSplitMinMM": "0",
#     "ProgMoveJType": "0", # Tools->Options->Programs->Output for joint movements (index = dropbox index, eg. 0 -> Default)
#     "ProgMoveLType": "1", # Tools->Options->Programs->Output for linear movements (index = dropbox index, eg. 1 -> Joint)
#     "ProgMoveCType": "2"  # Tools->Options->Programs->Output for circular movements (index = dropbox index, eg. 2 -> Cartesian)
# }
RDK_COMMANDS = {"ProgMoveNames": "1"}  # Ask RoboDK to export target names (optional: used by ADD_TARGET_NAME and limit warnings when available)

# Import RoboDK tools
from robodk import robomath
from robodk import robodialogs
from robodk import robofileio

from typing import List, Optional, Union


# ----------------------------------------------------
def values_2_str(values: List[float], decimals: int = 3) -> str:
    """Formats a list of numbers as comma separated values: [1, 2.5] -> '1.000, 2.500'"""
    return ', '.join('%.*f' % (decimals, v) for v in values)


# ----------------------------------------------------
# Header of the generated program: written once at the top of the file.
# {ip}, {port} and {calibrate} are filled in by the post. Braces of the generated code are doubled: {{ }}
EDO_HEADER = """\
# Program generated by RoboDK for the Comau e.DO (post processor: Comau_eDO)
# Run it with Python 3 on a PC connected to the e.DO network. Requires: pip install pyedo roslibpy pynput
import sys
import time

try:
    from pyedo import edo
except ImportError:
    sys.exit('pyedo is not installed. Install it with: pip install pyedo roslibpy pynput')

ROBOT_IP = '{ip}'
ROBOT_PORT = {port}
CALIBRATE = {calibrate}  # calib_axes() needs the joint notches aligned by hand
START_UP_DELAY = 2  # s, time given to the controller to process each start-up command
MOVE_TIMEOUT = 60  # s, maximum time to wait for one movement

# --- Connect --------------------------------------------------------------------
print('Connecting to the e.DO at %s:%d ...' % (ROBOT_IP, ROBOT_PORT))
try:
    myedo = edo(ROBOT_IP, ROBOT_PORT)
except Exception as e:
    sys.exit('Could not connect to the e.DO: %s' % e)
if not hasattr(myedo, 'MovementCommand'):  # pyedo only creates its topics when connected
    sys.exit('Could not connect to the e.DO (websocket busy? close the e.DO App)')

# --- Start-up ---------------------------------------------------------------------
myedo.init_7Axes()  # 6 joints + gripper (move_joint always sends 7 values)
time.sleep(START_UP_DELAY)
myedo.disengage_std()
time.sleep(START_UP_DELAY)
if CALIBRATE:
    myedo.calib_axes()
    time.sleep(START_UP_DELAY)

# --- Wait for the end of each movement ---------------------------------------------
# /machine_movement_ack: type 2 = movement executed, type -1 = error (data = error code)
_ack = {{'type': None, 'data': None}}
myedo.MovementFeedback.subscribe(lambda msg: _ack.update(msg))


def wait_move():
    t0 = time.time()
    while _ack['type'] != 2:
        if _ack['type'] == -1:
            sys.exit('e.DO movement error, code %s' % _ack['data'])
        if time.time() - t0 > MOVE_TIMEOUT:
            sys.exit('Timeout waiting for the e.DO movement')
        time.sleep(0.01)
    _ack['type'] = None  # consume the ack: the next wait needs a new one
"""


# ----------------------------------------------------
# Object class that handles the robot instructions/syntax
class RobotPost(object):
    """RoboDK Post Processor object.

    As Post processors can be compiled (.pyc), class variables can be exposed to the user for further customization.

    More information on how users can modify variables of a RoboDK Post Processor here:

        - https://robodk.com/doc/en/Post-Processors.html#PPEditor
        - https://robodk.com/doc/en/Post-Processors.html#EditPost

    .. code-block:: python

        class RobotPost(object):

            # Public: define variables that can be edited by the user below

            MY_PUBLIC_VAR = TRUE

            # ----------------------------------------------------
            # Private: define internal variables that cannot be edited by the user below (note the "# ---------..." splitter)

            MY_PRIVATE_VAR = False

    """

    # Public: define variables that can be edited by the user below
    #
    # More information on how users can modify variables of a RoboDK Post Processor here:
    #     https://robodk.com/doc/en/Post-Processors.html#PPEditor
    #     https://robodk.com/doc/en/Post-Processors.html#EditPost

    # Set the output program extension: the e.DO has no language, we generate a Python script
    PROG_EXT = 'py'
    # --- Connection (pyedo uses a rosbridge websocket) ---------------------------------
    # IP used when RoboDK does not provide one (Connect to robot dialog). 192.168.12.1 = e.DO Wi-Fi hotspot
    DEFAULT_ROBOT_IP = '192.168.12.1'
    # rosbridge websocket port (pyedo default)
    ROBOT_PORT = 9090

    # --- Robot start-up --------------------------------------------------------------
    # calib_axes() requires the joint notches to be aligned by hand: operator decision, off by default
    CALIBRATE = False

    # --- Kinematic convention: RoboDK model -> e.DO controller -------------------------
    # J3 turns the opposite way in the RoboDK model and in the e.DO (verified with the e.DO URDF)
    JOINT_SIGNS = [1, 1, -1, 1, 1, 1]

    # Real joint limits in degrees (e.DO URDF: "determined by jogging, TechSheet is wrong")
    JOINT_LIMITS = [(-178, 178), (-98, 98), (-98, 98), (-178, 178), (-103, 103), (-270, 270)]

    # --- Speed: pyedo has no speed command, each move carries an override 'ovr' (1-100 %) ---
    # Max joint speed in deg/s (e.DO URDF: velocity = 1.5 rad/s)
    MAX_SPEED_JOINTS = 86.0
    # Max linear speed in mm/s. ASSUMPTION: not documented, must be measured on the real robot
    MAX_SPEED_LINEAR = 250.0
    # Override used until RoboDK sets a speed (pyedo default)
    DEFAULT_OVR = 30

    # Add the RoboDK target name as a comment in the output program (when RoboDK exports target names)
    ADD_TARGET_NAME = False

    # ----------------------------------------------------
    # Private: define internal variables that cannot be edited by the user below (note the "# ---------..." splitter)

    # Always one file: the generated script must contain all its subprograms to run on its own.
    # The line limit of the template is not used (Python has no program length limit)
    DEFAULT_MAX_LINES_X_PROG = None

    # Minimum number of lines required to define at least 1 instruction in an output file
    MIN_LINES_X_PROG = 10

    def __init__(self, robotpost: str = '', robotname: str = '', robot_axes: int = 6, **kwargs) -> None:
        """Create a new post processor.

        **Tip**: Avoid using instances of :meth:`robodk.robolink.Robolink` and/or :meth:`robodk.robolink.Item` in the post processor unless absolutely necessary.

        :param robotpost: Name of the post processor
        :type robotpost: str
        :param robotname: Name of the robot
        :type robotname: str
        :param robot_axes: Number of axes of the robot, including synchronized axes
        :type robot_axes: int
        :param axes_type: Type of each axes of the robot ('R': Robot rotative, 'T': Robot translation, 'J': Ext. axis rotative, 'L': Ext. axis linear)
        :type axes_type: list of str, optional
        :param native_name: Native name of the robot (before any rename)
        :type native_name: str, optional
        :param ip_com: IP address of the robot ("Connect" tab in RoboDK)
        :type ip_com: str, optional
        :param api_port: RoboDK API port to the RoboDK instance
        :type api_port: int, optional
        :param prog_ptr: RoboDK Item pointer to the program generated
        :type prog_ptr: int, optional
        :param robot_ptr: RoboDK Item pointer to the robot associated with the program generated
        :type robot_ptr: int, optional
        :param pose_turntable: Pose of the synchronized turn table
        :type pose_turntable: :meth:`robodk.robomath.PosePP`, optional
        :param pose_rail: Pose of the synchronized linear rail
        :type pose_rail: :meth:`robodk.robomath.PosePP`, optional
        :param lines_x_prog: Maximum number of lines per program (to generate multiple files). This setting can be overridden by in RoboDK (Tools-Options-Program)
        :type lines_x_prog: int, optional
        :param pulses_x_deg: Pulses per degree (provided in the robot parameters of RoboDK)
        :type pulses_x_deg: list of int, optional

        Example for a program using the KUKA KRC2 post processor and a KUKA KR 500 3 robot with synchronized linear rail and turn table:

        .. code-block:: python

            RobotPost(r\"\"\"KUKA_KRC2\"\"\",r\"\"\"KUKA KR 500 3\"\"\",9, axes_type=['R','R','R','R','R','R','T','J','J'], native_name=r\"\"\"KUKA KR 500 3\"\"\", ip_com=r\"\"\"192.168.241.127\"\"\", api_port=20500, prog_ptr=2109546424992, robot_ptr=2109347059584, pose_turntable=p(1890.627070,1670.706012,-504.767930,-0.060103,0.046410,-0.246888), pose_rail=p(0.000000,0.000000,0.000000,90.000000,0.000000,0.000000))

        """

        # Constructor parameters (mandatory)
        self.ROBOT_POST = robotpost  # Name of the robot post processor (provided by RoboDK in the constructor)
        self.ROBOT_NAME = robotname  # Name of the robot (provided by RoboDK in the constructor)
        self.ROBOT_AXES = robot_axes  # Number of axes for the robot, including synchronized axes (provided by RoboDK in the constructor)

        # Optional constructor parameters (added later, backward compatibility)
        self.AXES_TYPE = None  # Optional, type of each axes of the robot ('R': Robot rotative, 'T': Robot translation, 'J': Ext. axis rotative, 'L': Ext. axis linear) (provided by RoboDK in the constructor)
        self.NATIVE_NAME = robotname  # Optional, native/original name of the robot (provided by RoboDK in the constructor)
        self.IP_COM = None  # Optional, IP address of the robot ("Connect" tab in RoboDK) (provided by RoboDK in the constructor)
        self.API_PORT = None  # Optional, RoboDK API port to the RoboDK instance (provided by RoboDK in the constructor)
        self.PROG_PTR = None  # Optional, RoboDK Item pointer to the program generated (provided by RoboDK in the constructor)
        self.ROBOT_PTR = None  # Optional, RoboDK Item pointer to the robot associated with the program generated (provided by RoboDK in the constructor)
        self.POSE_TURNTABLE = None  #  Optional, offset pose of the synchronized turn table (provided by RoboDK in the constructor)
        self.POSE_RAIL = None  # Optional, offset pose of the synchronized linear rail (provided by RoboDK in the constructor)
        self.MAX_LINES_X_PROG = max(self.MIN_LINES_X_PROG, self.DEFAULT_MAX_LINES_X_PROG) if self.DEFAULT_MAX_LINES_X_PROG else None  # Optional, maximum number of lines per program (to generate multiple files). This setting can be overridden in RoboDK (Tools-Options-Program) (provided by RoboDK in the constructor)
        self.PULSES_X_DEG = None  # Optional, pulses per degree (provided in the robot parameters of RoboDK) (provided by RoboDK in the constructor)

        # Optional constructor parameters, you may or may not use those
        for k, v in kwargs.items():
            if k == 'axes_type':
                self.AXES_TYPE = v
            elif k == 'native_name' and v:  # Could be empty for older robots
                self.NATIVE_NAME = v
            elif k == 'ip_com':
                self.IP_COM = v
            elif k == 'api_port':
                self.API_PORT = v
            elif k == 'prog_ptr':
                self.PROG_PTR = v
            elif k == 'robot_ptr':
                self.ROBOT_PTR = v
            elif k == 'pose_turntable':
                self.POSE_TURNTABLE = v
            elif k == 'pose_rail':
                self.POSE_RAIL = v
            elif k == 'lines_x_prog':
                self.MAX_LINES_X_PROG = max(self.MIN_LINES_X_PROG, v)
            elif k == 'pulses_x_deg':
                self.PULSES_X_DEG = v

        self.ROBOT_EXT_AXES = 0  # Number of synchronized external axes for the robot
        if self.AXES_TYPE:
            self.ROBOT_EXT_AXES = self.AXES_TYPE.count('T') + self.AXES_TYPE.count('J')

        # Optional TEMP parameter (depends on RoboDK settings)
        self._TargetName = None  # Optional, target name (Tools->Options->Program->Export target names) (provided by RoboDK in the TEMP file)
        self._TargetNameVia = None  # Optional, intermediary target name (MoveC) (Tools->Options->Program->Export target names) (provided by RoboDK in the TEMP file)
        self._PoseTrack = None  # Optional, current pose of the synchronized linear axis (Tools->Options->Program->Export external axes poses) (provided by RoboDK in the TEMP file)
        self._PoseTurntable = None  # Optional, current pose of the synchronized turn table (Tools->Options->Program->Export external axes poses) (provided by RoboDK in the TEMP file)

        # Initialize internal non-constant variables (caps kept for legacy)
        self.PROG = []  # Current program content (list of str)
        self.PROG_LIST = []  # List of parsed programs (list of parsed "PROG")
        self.PROG_NAMES = []  # List of parsed program names
        self.PROG_FILES = []  # Local files generated by the post processor
        self.PROG_NAME = ''  # Active program name
        self.LOG = ''  # Current log content (str)
        self.ONETAB = '    '  # Tab character(s): 4 spaces, the generated program is Python
        self.TAB = ''  # Current tabulation

        # Robot state
        self._frame_name = None  # Current reference frame name, from setFrame
        self._frame_pose = robomath.eye(4)  # Current reference frame pose w.r.t. robot base, from setFrame
        self._frame_id = 0  # Current reference frame ID, from setFrame

        self._tool_name = None  # Current tool name, from setTool
        self._tool_pose = robomath.eye(4)  # Current tool pose w.r.t. robot flange, from setTool
        self._tool_id = 0  # Current tool ID, from setTool

        self._target_name = None  # Last target name, from MoveL/J/C
        self._target_pose = None  # Last target pose, from MoveL/J/C
        self._target_joints = None  # Last target joints, from MoveL/J/C

        # Speed as pyedo override 'ovr' (%). setSpeed / setSpeedJoints STORE it, each move READS it
        self._ovr_linear = self.DEFAULT_OVR  # Used by MoveL / MoveC
        self._ovr_joints = self.DEFAULT_OVR  # Used by MoveJ

        # IP of the robot: the one from RoboDK's "Connect to robot" dialog, or the default
        self.ROBOT_IP = self.IP_COM if self.IP_COM else self.DEFAULT_ROBOT_IP

        # The connection header is written only once, even if there are several programs
        self._header_written = False

        # Log messages already shown once (to avoid repeating the same warning)
        self._logged = set()

    # ------------------ program structure ----------------------

    def ProgStart(self, progname: str, *args, **kwargs) -> None:
        """Start a new program. Each RoboDK program (main or subprogram) becomes a Python function.

        :param progname: Name of the program
        :type progname: str
        """
        self.PROG_NAME = robofileio.FilterName(progname)  # Create a valid program name
        self.PROG_NAMES.append(self.PROG_NAME)  # Keep track of parsed programs

        self.TAB = ''
        if not self._header_written:
            # Connection + start-up, only once at the top of the file (even with subprograms)
            self.addline(EDO_HEADER.format(ip=self.ROBOT_IP, port=self.ROBOT_PORT, calibrate=self.CALIBRATE))
            self._header_written = True

        self.addline('')
        self.addline('def %s():' % self.PROG_NAME)
        self.TAB = self.ONETAB

    def ProgFinish(self, progname: str, *args, **kwargs) -> None:
        """End of a program (function).

        :param progname: Name of the program
        :type progname: str
        """
        if self.PROG and self.PROG[-1].strip().startswith('def '):
            self.addline('pass')  # A Python function cannot be empty
        self.TAB = ''

        self.PROG_LIST.append(self.PROG)  # Add the program to the list of parsed programs
        self.PROG = []  # Reset the program buffer for the next program

    def ProgSave(self, folder: str, progname: str, ask_user: bool = False, show_result: Union[bool, str, List[str]] = False, *args, **kwargs) -> None:
        """Saves all the programs in one Python script and calls the main program at the end.

        :param folder: Folder hint to save the program
        :type folder: str
        :param progname: Program name as a hint to save the program
        :type progname: str
        :param ask_user: True if RoboDK is set to prompt the user to select the folder
        :type ask_user: bool, str
        :param show_result: False, True or the path of the preferred text editor
        :type show_result: bool, str, list
        """
        import os

        if not self.PROG_NAMES:
            return
        main_prog = self.PROG_NAMES[0]

        # One file: the script must contain all its subprograms to run on its own
        filename = main_prog + '.' + self.PROG_EXT
        if robofileio.DirExists(folder):
            # Save directly in the folder provided by RoboDK. The save dialog is not used even if ask_user is set:
            # on macOS the Tk dialog is unreliable when called from RoboDK (see README)
            filesave = os.path.join(folder, filename)
        else:
            filesave = robodialogs.getSaveFileName(folder, filename, 'Save program as...')
            if not filesave:
                print('Program not saved: no file selected')
                return

        with open(filesave, 'w', encoding='utf-8') as fid:
            if self.LOG:
                # Warnings also at the very top of the script: the LOG pop-up is gone once closed,
                # the file keeps them for whoever runs the program later
                fid.write('# ' + '-' * 70 + '\n')
                fid.write('# PROGRAM GENERATION WARNINGS (review before running on the robot):\n')
                for msg in self.LOG.strip().split('\n'):
                    fid.write('#   - %s\n' % msg)
                fid.write('# ' + '-' * 70 + '\n')
            for prog in self.PROG_LIST:
                for line in prog:
                    fid.write(line + '\n')
            # Entry point: run the main program when the script is executed
            fid.write('\n\n')
            fid.write("if __name__ == '__main__':\n")
            fid.write('%s%s()\n' % (self.ONETAB, main_prog))
            fid.write("%sprint('Program %s finished')\n" % (self.ONETAB, main_prog))

        print('SAVED: %s\n' % filesave)
        self.PROG_FILES.append(filesave)

        if self.LOG:
            print('Program generation LOG:\n' + self.LOG)

        if show_result:
            self._open_file(filesave, show_result)
            if self.LOG:
                self._show_message('Program generation LOG:\n\n' + self.LOG)

    def ProgSendRobot(self, robot_ip: str, remote_path: str, ftp_user: str, ftp_pass: str, *args, **kwargs) -> None:
        """Not applicable: the e.DO has no program storage. The generated script runs on the PC and connects to the robot."""
        self._show_message('Sending programs is not applicable to the Comau e.DO.\n'
                           'Run the generated Python script on a PC connected to the robot network.')

    # ------------------ motion ----------------------

    def MoveJ(self, pose: Optional[robomath.Mat], joints: List[float], conf_RLF: Optional[List[int]] = None, *args, **kwargs) -> None:
        """Joint move: the joints computed by RoboDK are sent with the e.DO joint convention.

        :param pose: Pose of the tool w.r.t. the reference frame (None for joint targets, not used)
        :param joints: Robot joints in degrees (always provided)
        :param conf_RLF: Robot configuration (not used: joints are unambiguous)
        """
        self._target_pose = pose
        self._target_joints = joints
        self._add_target_name()

        edo_joints = self._joints_2_edo(joints)
        self._check_joint_limits(edo_joints)
        # 7th value = gripper, kept at 0 (the gripper is not modelled in RoboDK)
        self.addline('myedo.move_joint(%d, %s, 0)' % (self._ovr_joints, values_2_str(edo_joints)))
        self.addline('wait_move()')

    def MoveL(self, pose: Optional[robomath.Mat], joints: List[float], conf_RLF: Optional[List[int]] = None, *args, **kwargs) -> None:
        """Linear move: the target pose is sent in Comau XYZ + ZYZ (move_cartesian is a linear move in pyedo).

        :param pose: Pose of the tool w.r.t. the reference frame (None for joint targets)
        :param joints: Robot joints at the target, in degrees (used to check the real joint limits)
        :param conf_RLF: Robot configuration (not used)
        """
        self._target_pose = pose
        self._target_joints = joints
        if pose is None:
            msg = '%s: linear move to a joint target is not supported: use a cartesian target or a joint move.' % self.PROG_NAME
            self.addlog(msg)
            self.RunMessage(msg, True)
            return
        self._add_target_name()

        self._check_joint_limits(self._joints_2_edo(joints))
        self.addline('myedo.move_cartesian(%d, %s)' % (self._ovr_linear, values_2_str(self._pose_2_edo(pose))))
        self.addline('wait_move()')

    def MoveC(self, pose1: Optional[robomath.Mat], joints1: List[float], pose2: Optional[robomath.Mat], joints2: List[float], conf_RLF_1: Optional[List[int]] = None, conf_RLF_2: Optional[List[int]] = None, *args, **kwargs) -> None:
        """Circular move through pose1 (via point) ending at pose2.

        Note: pyedo move_circular(ovr, x1..r1, x2..r2) expects the END point first and the VIA point second.
        """
        if pose1 is None or pose2 is None:
            msg = '%s: circular move to joint targets is not supported: use cartesian targets.' % self.PROG_NAME
            self.addlog(msg)
            self.RunMessage(msg, True)
            return
        self._add_target_name()

        self._check_joint_limits(self._joints_2_edo(joints1))
        self._check_joint_limits(self._joints_2_edo(joints2))
        via = values_2_str(self._pose_2_edo(pose1))
        end = values_2_str(self._pose_2_edo(pose2))
        self.addline('myedo.move_circular(%d, %s, %s)' % (self._ovr_linear, end, via))
        self.addline('wait_move()')

    # ------------------ frames and tools: stored, applied to every cartesian move ----------------------

    def setFrame(self, pose: robomath.Mat, frame_id: Optional[int] = None, frame_name: Optional[str] = None, *args, **kwargs) -> None:
        """Reference frame w.r.t. the robot base. Stored: cartesian targets are converted to the robot base."""
        self._frame_pose = pose
        self._frame_id = frame_id
        self._frame_name = frame_name

    def setTool(self, pose: robomath.Mat, tool_id: Optional[int] = None, tool_name: Optional[str] = None, *args, **kwargs) -> None:
        """Tool (TCP) w.r.t. the robot flange. Stored: cartesian targets are converted to the flange."""
        self._tool_pose = pose
        self._tool_id = tool_id
        self._tool_name = tool_name

    # ------------------ speed: stored, every move carries its own override ----------------------

    def setSpeed(self, speed_mms: float, *args, **kwargs) -> None:
        """Linear speed in mm/s -> override (%) of the following linear and circular moves."""
        self._ovr_linear = self._speed_2_ovr(speed_mms, self.MAX_SPEED_LINEAR, 'mm/s')

    def setSpeedJoints(self, speed_degs: float, *args, **kwargs) -> None:
        """Joint speed in deg/s -> override (%) of the following joint moves."""
        self._ovr_joints = self._speed_2_ovr(speed_degs, self.MAX_SPEED_JOINTS, 'deg/s')

    def setAcceleration(self, accel_mmss: float, *args, **kwargs) -> None:
        """Not available in pyedo: the controller uses its own acceleration."""
        self._log_once('setAcceleration', 'Acceleration is not supported by pyedo: ignored.')

    def setAccelerationJoints(self, accel_degss: float, *args, **kwargs) -> None:
        """Not available in pyedo: the controller uses its own acceleration."""
        self._log_once('setAccelerationJoints', 'Joint acceleration is not supported by pyedo: ignored.')

    def setZoneData(self, zone_mm: float, *args, **kwargs) -> None:
        """Not available in pyedo: every move stops at its target (no blending)."""
        self._log_once('setZoneData', 'Rounding/blending is not supported by pyedo: every move stops at its target.')

    # ------------------ other instructions ----------------------

    def Pause(self, time_ms: float, *args, **kwargs) -> None:
        """Pause in ms. A negative value means: stop until the operator continues."""
        if time_ms < 0:
            self.addline("input('Program paused. Press Enter to continue...')")
        else:
            self.addline('time.sleep(%.3f)' % (time_ms * 0.001))

    def setDO(self, io_var: Union[int, str], io_value: Union[int, float, str], *args, **kwargs) -> None:
        """Not available in pyedo (no I/O API)."""
        self._unsupported('setDO(%s, %s)' % (io_var, io_value))

    def setAO(self, io_var: Union[int, str], io_value: Union[int, float, str], *args, **kwargs) -> None:
        """Not available in pyedo (no I/O API)."""
        self._unsupported('setAO(%s, %s)' % (io_var, io_value))

    def waitDI(self, io_var: Union[int, str], io_value: Union[int, float, str], timeout_ms: float = -1, *args, **kwargs) -> None:
        """Not available in pyedo (no I/O API)."""
        self._unsupported('waitDI(%s, %s, %s)' % (io_var, io_value, timeout_ms))

    def RunCode(self, code: str, is_function_call: bool = False, *args, **kwargs) -> None:
        """Call a subprogram (Python function) or insert raw Python code."""
        if is_function_call:
            code = robofileio.FilterName(code)
            if not code.endswith(')'):
                code = code + '()'
        self.addline(code)

    def RunMessage(self, message: str, iscomment: bool = False, *args, **kwargs) -> None:
        """Comment in the script, or message printed on the PC console."""
        if iscomment:
            self.addline('# ' + message)
        else:
            self.addline('print(%r)' % message)

    # ------------------ private ----------------------

    def _joints_2_edo(self, joints: List[float]) -> List[float]:
        """RoboDK joints -> e.DO joints: first 6 values with the e.DO sign convention (JOINT_SIGNS)."""
        if len(joints) > 6:
            self._log_once('extaxes', 'Only the 6 robot joints are sent: external axes are ignored.')
        return [s * j for s, j in zip(self.JOINT_SIGNS, joints[:6])]

    def _pose_2_edo(self, pose: robomath.Mat) -> List[float]:
        """Tool pose w.r.t. the reference frame -> flange pose w.r.t. the robot base, as Comau [x, y, z, a, e, r] (mm, ZYZ deg)."""
        pose_base = self._frame_pose * pose * robomath.invH(self._tool_pose)
        return robomath.Pose_2_Comau(pose_base)

    def _speed_2_ovr(self, speed: float, speed_max: float, units: str) -> int:
        """Speed -> pyedo override in %, limited to 1..100."""
        ovr = int(round(100.0 * speed / speed_max))
        ovr_ok = min(100, max(1, ovr))
        if ovr_ok != ovr:
            self.addlog('Speed %.1f %s is outside the e.DO range (max %.1f %s): override set to %d%%.' % (speed, units, speed_max, units, ovr_ok))
        return ovr_ok

    def _check_joint_limits(self, edo_joints: List[float]) -> None:
        """Warn when a target exceeds the real e.DO joint limits (stricter than the RoboDK model)."""
        for i, (j, (jmin, jmax)) in enumerate(zip(edo_joints, self.JOINT_LIMITS)):
            if not jmin <= j <= jmax:
                where = (' (target %s)' % self._target_name) if self._target_name else ''
                msg = 'J%d = %.1f deg is outside the real e.DO limits [%d, %d]%s' % (i + 1, j, jmin, jmax, where)
                self.addline('# WARNING: ' + msg)  # next to the move, visible to whoever reads/runs the script
                self.addlog('%s: %s.' % (self.PROG_NAME, msg))

    def _add_target_name(self) -> None:
        """Optionally add the RoboDK target name as a comment (ADD_TARGET_NAME)."""
        self._target_name = self._TargetName if type(self._TargetName) is str else None
        if self.ADD_TARGET_NAME and self._target_name:
            self.RunMessage('Target: ' + self._target_name, True)

    def _unsupported(self, instruction: str) -> None:
        """Keep a trace of an instruction pyedo cannot execute."""
        self.addline('# Not supported by pyedo: ' + instruction)
        self.addlog('%s: %s is not supported by pyedo (left as a comment).' % (self.PROG_NAME, instruction))

    def _log_once(self, key: str, msg: str) -> None:
        """Add a message to the log only the first time it happens."""
        if key not in self._logged:
            self._logged.add(key)
            self.addlog(msg)

    def _open_file(self, path: str, app: Union[bool, str, List[str]]) -> None:
        """Open the generated file with the editor given by RoboDK or the default application (cross-platform)."""
        import os
        import sys
        import subprocess
        if isinstance(app, str):
            subprocess.Popen([app, path])
        elif isinstance(app, list):
            subprocess.Popen(app + [path])
        elif sys.platform == 'darwin':
            subprocess.Popen(['open', path])
        elif os.name == 'nt':
            os.startfile(path)
        else:
            subprocess.Popen(['xdg-open', path])

    def _show_message(self, msg: str) -> None:
        """Show a message to the user; fall back to the console if no dialog can be opened."""
        print(msg)
        try:
            robodialogs.ShowMessage(msg)
        except Exception:
            pass

    def addline(self, newline: str) -> None:
        """Add a new program line with the current indentation."""
        self.PROG.append(self.TAB + newline)

    def addlog(self, newline: str) -> None:
        """Add a message to the log shown after the program is generated."""
        self.LOG = self.LOG + newline + '\n'


# -------------------------------------------------
# ------------ For testing purposes ---------------
def test_post() -> None:
    """Test the post processor with a program that uses every instruction.

    Poses are written in Comau format (x, y, z, a, e, r) and joints in the RoboDK convention.
    """
    p = robomath.Comau_2_Pose

    r = RobotPost(r"""Comau_eDO""", r"""Comau e.DO""", 6, axes_type=['R', 'R', 'R', 'R', 'R', 'R'], ip_com=r"""192.168.12.1""")

    r.ProgStart(r"""Prog1""")
    r.RunMessage(r"""Program generated by RoboDK v6.0.6 for Comau e.DO on 10/11/2026 20:00:00""", True)
    r.RunMessage(r"""Using nominal kinematics.""", True)
    r.setFrame(p([0, 0, 0, 0, 0, 0]), -1, r"""Comau e.DO Base""")
    r.setTool(p([0, 0, 0, 0, 0, 0]), -1, r"""Flange""")
    # Joint move to the pyedo example start pose (RoboDK convention: J3 = -45 -> e.DO J3 = +45)
    r.MoveJ(None, [0, 45, -45, 0, 90, 0], None)
    r.setSpeed(50.0)
    r.MoveL(p([400, 0, 250, 0, 180, 0]), [0, 31.0, -60.7, 0, 60.3, 0], [0, 0, 0])
    r.MoveL(p([400, -100, 180, 0, 180, 0]), [-14.0, 40.8, -50.3, 0, 81.1, -14.0], [0, 0, 0])
    r.setSpeedJoints(43.0)
    # Out of the real limits: J3 = -112.7 (RoboDK accepts it, the real e.DO does not)
    r.MoveJ(None, [0, -28.0, -112.7, 0, 50.3, 0], None)
    r.MoveC(p([400, 0, 180, 0, 180, 0]), [0, 35.0, -55.0, 0, 70.0, 0], p([400, 100, 180, 0, 180, 0]), [14.0, 40.8, -50.3, 0, 81.1, 14.0], [0, 0, 0], [0, 0, 0])
    r.MoveL(None, [0, 0, -90, 0, 45, 0], None)  # linear move to a joint target: not supported
    r.setSpeed(1000.0)  # above the assumed e.DO max: limited to 100%
    r.setAcceleration(3000.0)
    r.setZoneData(5.0)
    r.Pause(500)
    r.Pause(-1)
    r.setDO(1, 1)
    r.waitDI(2, 1, -1)
    r.RunMessage(r"""Pick done""")
    r.RunCode(r"""SubProg""", True)
    r.ProgFinish(r"""Prog1""")

    r.ProgStart(r"""SubProg""")
    r.ProgFinish(r"""SubProg""")  # empty subprogram -> 'pass'

    for prog in r.PROG_LIST:
        for line in prog:
            print(line)
    print('')
    print('--- LOG ---')
    print(r.LOG)


if __name__ == "__main__":
    """Procedure to call when the module is executed by itself: test_post()"""
    test_post()
