# Copyright 2015-2020 - RoboDK Inc. - 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 
# for an ABB robot with RoboDK (compatible with S4 to IRC5)
#
# 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
# ----------------------------------------------------


# Define a custom header (variable declaration)
CUSTOM_HEADER = '''    ! -------------------------------
    ! Define customized variables here
    ! ...'''

# ----------------------------------------------------
# In general, one tab equals 4 spaces or a tab
ONETAB = '\t' 

# Add specific pre header module for ABB robots (required for S4C)
MODULE_PREHEAD = ['%%%','  VERSION:1','  LANGUAGE:ENGLISH','%%%']

# List known reserved names and known variables
RESERVED_NAMES = ['tool0','work0','work1','clock1','reg1','reg2','reg3','reg4','reg5','alias','and','backward','case','connect','const','default','div','do','else','elseif','endfor','endfunc','endif','endmodule','endproc','endrecord','endtest','endtrap','endwhile','error','exit','false','for','from','func','goto','if','inout','local','mod','module','nostepin','not','noview','or','pers','proc','raise','readonly','record','retry','return','step','sysmodule','test','then','to','trap','true','trynext','undo','var','viewonly','while','with','xor']
KNOWN_ZONEDATA = [0,1,5,10,15,20,30,40,50,60,80,100,150,200]
KNOWN_SPEEDS = [5,10,20,30,40,50,60,80,100,150,200,300,400,500,600,800,1000,1500,2000,2500,3000,4000,5000,6000,7000]
for zd in KNOWN_ZONEDATA:
    RESERVED_NAMES.append('z%i'%zd)
for sp in KNOWN_SPEEDS:
    RESERVED_NAMES.append('v%i'%sp)
#-----------------------------------------------------

# ----------------------------------------------------
# Import RoboDK tools
from robodk import *


def FilterName(namefilter, safechar='P', reserved_names=None):
    """Get a safe program or variable name that can be used for robot programming"""
    # remove non accepted characters
    for c in r' .-[]/\;,><&*:%=+@!#^|?^':
        namefilter = namefilter.replace(c,'')
    
    # remove non english characters
    char_list = (c for c in namefilter if 0 < ord(c) < 127)
    namefilter = ''.join(char_list)
        
    # Make sure we have a non empty string
    if len(namefilter) <= 0:
        namefilter = safechar
        
    # Make sure we don't start with a number
    if namefilter[0].isdigit():
        namefilter = safechar + namefilter
        
    # Make sure we are not using a reserved name
    if reserved_names is not None:
        cnt = 1
        namefilter_root = namefilter
        while namefilter.lower() in reserved_names:
            cnt = cnt + 1
            namefilter = namefilter_root + "%i" % cnt
            
        # Add the name to reserved names
        reserved_names.append(namefilter)
        
    return namefilter    
    
def getSaveFolder(path_programs='/',popup_msg='Select a directory to save your program'):
    """Ask the user to select a folder to save a program or other file"""
    import sys
    if sys.version_info[0] < 3:
        # Python 2
        import Tkinter as tkinter
        import tkFileDialog as filedialog
    else:
        # Python 3
        import tkinter
        from tkinter import filedialog
    
    tkinter.Tk().withdraw()
    dirname = filedialog.askdirectory(initialdir=path_programs, title=popup_msg)
    if len(dirname) < 1:
        dirname = None
        
    return dirname
    
def pose_2_str(pose):
    """Prints a pose target"""
    [x,y,z,q1,q2,q3,q4] = Pose_2_ABB(pose)
    return ('[%.3f,%.3f,%.3f],[%.8f,%.8f,%.8f,%.8f]' % (x,y,z,q1,q2,q3,q4))
    
def angles_2_str(angles):
    """Prints a joint target"""
    njoints = len(angles)
    # extend the joint target if the robot has less than 6 degrees of freedom
    if njoints < 6:
        angles.extend([0]*(6-njoints))
    # Generate a string like:
    # [10,20,30,40,50,60]
    # with up to 6 decimals
    return '[%s]' % (','.join(format(ji, ".6f") for ji in angles[0:6]))

def extaxes_2_str(angles, ratio=None):
    """Prints the external axes, if any"""
    # extend the joint target if the robot has less than 6 degrees of freedom
    njoints = len(angles)
    if njoints <= 6:
        # should print 9E9 for unset external axes
        # [9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]
        return '[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]'
        
    if ratio is not None:
        for i in range(6,len(angles)):
            angles[i] = ratio[i]*angles[i]
            
    extaxes_str = (','.join(format(ji, ".6f") for ji in angles[6:njoints]))
    if njoints < 12:
        extaxes_str = extaxes_str + ',' + ','.join(['9E9']*(12-njoints))
    # If angles is [j1,j2,j3,j4,j5,j6,10,20], it will generate a string like:
    # [10,20,9E9,9E9,9E9,9E9]
    # with up to 6 decimals
    return '[%s]' % extaxes_str

# ----------------------------------------------------    
# Object class that handles the robot instructions/syntax
class RobotPost(object):
    """Robot post object"""
    #------------------------ Customize your post using the following variables ----------------------
    # Set the program file extension:  
    PROG_EXT = 'mod'  # IRC5 (newer controllers)
    #PROG_EXT = 'prg' # S4 (older controllers)
    
    # Set if we want to generate the main/first program as a Main() program. The name of the main/first program will be replaced by Main()
    # Example: PROC Main() instead of PROG Prog1()
    #FIRST_PROG_AS_MAIN = False # It will generate PROG Prog1() (or the name set in the RoboDK program)
    FIRST_PROG_AS_MAIN = True # It will generate PROG Main()    
    
    # Default maximum number of lines per program. If a program exceeds this value it will then generate multiple "pages" (files)
    # This value can also be set in Tools-Options-Program-Maximum number of lines per program.
    MAX_LINES_X_PROG = 20000  # recommended for IRC5: 20000
    #MAX_LINES_X_PROG = 5000  # recommended for S4:  5000    
    
    # Include subprograms in the main module:
    # Set to True to include sub programs in the same module
    INCLUDE_SUB_PROGRAMS = True
    # You can also specify the maximum lines of code allowed to include a subprogram in the main/first program
    # If a subprogram exceeds this number of lines of code it will be generated as a separate module
    MAX_SUBPROG_LINES = 500    
            
    # External dripfeed: set to True if you use an external tool to load the programs (such as RAPBOX):
    EXTERNAL_DRIPFEEDER = False # It will generate a main program to load subprograms.
    #EXTERNAL_DRIPFEEDER = True # It will not generate a main program to load subprograms. Each subprogram will be called Main(). This is suitable for RAPBOX.
    
    # Remote path to place programs in the robot controller
    # When program splitting takes place we need this path to load programs on the fly
    RAPID_REMOTE_PATH = "/hd0a/Enter-Serial-Number/HOME/RoboDK"
    
    # Set if you want to ignore the setup of the turntable (or external axis) on the controller 
    # If you set it to True it means the controller will not be aware of the axis
    # (you can't move using a synchronized movement and the turntable will not hold the wobjdata)
    TURNTABLE_IGNORE = False # default: False
    
    # Specify the mechanical unit name for linear track and/or turntable, if required.
    # This name will be added to the wobjdata variable
    MECHANICAL_UNIT_NAME = 'Turntable_Mechanical_Unit_Name'    
    #MECHANICAL_UNIT_NAME = 'T6003'  
    #MECHANICAL_UNIT_NAME = 'STN1'
    
    # Set to False to use MoveJ for joint movements instead of MoveAbsJ
    MOVEJ_AS_MOVEABSJ = False
    
    # Enter the axes ratio for external axes, if required
    AXES_RATIO = None
    #AXES_RATIO = [1,1,1,1,1,1,  -1,1,1]
    #------------------------------------------------------------------------------
    #if EXTERNAL_DRIPFEEDER:
    #    FIRST_PROG_AS_MAIN = False
    
    # other variables
    ROBOT_POST = 'ABB S4 to IRC5 including arc welding and 3D printing options'
    ROBOT_NAME = 'unknown'
    
    PROG = []
    PROG_LIST = []
    PROG_NAMES = []
    PROG_FILES = []
    nProgs = 0
    
    TAB = ''
    LOG = ''
    SPEED_MMS = 500
    SPEEDDATA = 'v500' #[500,500,5000,1000]'
    ZONEDATA = 'z1'
    TOOLDATA = 'tool0'
    WOBJDATA = 'wobj0'
    
    TOOL_DEF = [ONETAB + '! Tool variables: ']
    FRAME_DEF = [ONETAB + '! Reference variables:']
    
    
    # Define the names that you do not want to redefine in the header (add list): 
    FRAME_LIST = []
    TOOL_LIST = []
    
    LAST_TARGET = None
    
    # Default header:
    HEADER = []
    
    nAxes = 6
    
    CLAD_ON = False
    CLAD_DATA = 'clad1'
    
    ARC_ON = False
    ARC_WELDDATA = 'weld1'
    ARC_WEAVEDATA = 'weave1'
    ARC_SEAMDATA = 'seam1'
    
    # Important: This is usually provided by RoboDK automatically. Otherwise, override the __init__ procedure. 
    nAxes = 6 
    # Important: This is usually set up by RoboDK automatically. Otherwise, override the __init__ procedure.
    AXES_TYPE = ['R','R','R','R','R','R']  
    # 'R' for rotative axis, 'L' for linear axis, 'T' for external linear axis (linear track), 'J' for external rotative axis (turntable)
    #AXES_TYPE = ['R','R','R','R','R','R','T','J','J'] #example of a robot with one external linear track axis and a turntable with 2 rotary axes
    AXES_TRACK = []
    AXES_TURNTABLE = []
    HAS_TRACK = False
    HAS_TURNTABLE = False
    FR_EXTERNAL_POSE = None
    
    # 3D Printing Extruder Setup Parameters:
    PRINT_E_AO = 5              # Analog Output ID to command the extruder flow
    PRINT_SPEED_2_SIGNAL = 0.10 # Ratio to convert the speed/flow to an analog output signal
    PRINT_FLOW_MAX_SIGNAL = 24  # Maximum signal to provide to the Extruder
    PRINT_ACCEL_MMSS = -1      # Acceleration, -1 assumes constant speed if we use rounding/blending
   
    # Internal 3D Printing Parameters
    PRINT_POSE_LAST = None # Last pose printed
    PRINT_E_LAST = 0 # Last Extruder length
    PRINT_E_NEW = None # New Extruder Length
    PRINT_LAST_SIGNAL = None # Last extruder signal
    
    def __init__(self, robotpost=None, robotname=None, robot_axes = 6, **kwargs):
        self.ROBOT_POST = robotpost
        self.ROBOT_NAME = robotname
        self.PROG = []
        self.LOG = ''
        self.nAxes = robot_axes
        for k,v in kwargs.items():
            if k == 'lines_x_prog':
                self.MAX_LINES_X_PROG = v  
            elif k == 'axes_type':
                self.AXES_TYPE = v  
            elif k == 'pose_turntable':
                pose_turntable = v
                self.FR_EXTERNAL_POSE = pose_turntable
            elif k == 'pose_rail':
                pose_rail = v
                #self.FR_RAIL_POSE = pose_rail   

        for i in range(len(self.AXES_TYPE)):
            if self.AXES_TYPE[i] == 'T':
                self.AXES_TRACK.append(i)
                self.HAS_TRACK = True
            elif self.AXES_TYPE[i] == 'J':
                self.AXES_TURNTABLE.append(i)
                self.HAS_TURNTABLE = True                   
        
    def ProgStart(self, progname): #, new_page = False):
        progname = FilterName(progname,'P',RESERVED_NAMES)
        
        self.nProgs = self.nProgs + 1            
        if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS:
            return

        self.PROG_NAME = progname
        self.PROG_NAMES.append(progname)
        
        #self.TAB = ONETAB
        #self.addline('')
        #self.addline('PROC %s()' % progname)
        self.TAB = ONETAB + ONETAB # instructions need two tabs
        if self.HAS_TRACK or self.HAS_TURNTABLE:
            self.addline('! ActUnit %s;' % self.MECHANICAL_UNIT_NAME)
        
        self.addline('ConfJ \On;')
        self.addline('ConfL \Off;')
        
    def ProgFinish(self, progname): #, new_page = False):
        if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS:
            return
            
        progname = self.PROG_NAME # take already filtered name
        
        #self.TAB = ONETAB
        #self.addline('ENDPROC')
        self.PROG_LIST.append(self.PROG)
        self.PROG = []        
    
    def save_module(self, filesave, prog, module_name):
        with open(filesave, "w", errors="replace") as fid:
            for line in MODULE_PREHEAD:
                fid.write(line)
                fid.write('\n')
                
            fid.write('MODULE ' + module_name + '\n\n')
            for line in prog:
                fid.write(line)
                fid.write('\n')
            fid.write('\nENDMODULE\n')
        
        # Remember all files saved for FTP transfer
        self.PROG_FILES.append(filesave)
    
    def ProgSave(self, folder, progname, ask_user = False, show_result = False):        
        # If required, ask the user to save the folder (ask_user = True if we selected "Save program as..."
        if ask_user or not DirExists(folder):
            folder = getSaveFolder(folder,'Select a directory to save your program')
            if folder is None:
                # The user selected the Cancel button
                return                
        # Complete path to save the main program
        #filesave = folder + '/' + progname + '.mod'
                    
        #------------------------------------------------------          
        # Save each program module
        # Store the files we want to display on the text editor
        files_display = []
                
        # First: retrieve all small program calls and add them as subprograms
        module_list_prog = []
        module_list_names = []        
        module_addtop = []
        max_subprog_lines = min(self.MAX_LINES_X_PROG, self.MAX_SUBPROG_LINES)
        for i in range(len(self.PROG_LIST)):
            prgi = self.PROG_LIST[i]
            namei = self.PROG_NAMES[i]
            if i > 0 and len(prgi) < max_subprog_lines:
                # Add subprograms for the first module
                subprog_header = [ONETAB + 'PROC %s()' % namei]
                subprog_footer = [ONETAB + 'ENDPROC\n']            
                subprog_complete = subprog_header + prgi + subprog_footer
                module_addtop += subprog_complete
            else:
                module_list_prog.append(prgi)
                module_list_names.append(namei)
                
        # Save all module files   
        for i in range(len(module_list_prog)):
            prgi_lines = module_list_prog[i]
            prgi_name = module_list_names[i]
            module_name = "MOD_" + prgi_name
            filesave = folder + '/' + prgi_name  # extension is required
            if i == 0 and self.FIRST_PROG_AS_MAIN:
                prgi_name = 'Main'            
            
            nLines = len(prgi_lines)        
            nSubModules = math.ceil(nLines/self.MAX_LINES_X_PROG)
            
            # Header to add to the program
            prgi_header = []
            
            # Check if we need to apply module splitting (temporary modules will be loaded on the fly)
            if nSubModules > 1:            
                line_start = 0
                lines_written = 0
                file_names = []
                prog_count = 0
                
                prgi_header_tmp = []
                if self.EXTERNAL_DRIPFEEDER:
                    # Add custom header, tools and reference frames for the main program
                    prgi_header_tmp.append(CUSTOM_HEADER)
                    prgi_header_tmp.append('')
                    prgi_header_tmp += self.TOOL_DEF
                    prgi_header_tmp.append('')
                    prgi_header_tmp += self.FRAME_DEF
                    prgi_header_tmp.append('')
                
                while line_start < nLines:
                    prog_count = prog_count + 1
                    line_end = line_start + self.MAX_LINES_X_PROG
                    line_end = min(line_end, nLines)
                    # Alternate program names so that 3 consecutive programs can live at the same time
                    file_name_i = "%s_%i.%s" % (filesave, prog_count-1, self.PROG_EXT)
                    file_names.append(file_name_i)
                    temp_prgi = prgi_lines[line_start:line_end]
                    tempmodule_name = ""
                    tempmodule_header = []
                    
                    # If we use an external dripfeeder all programs should be named Main()
                    if self.EXTERNAL_DRIPFEEDER:
                        tempmodule_name = "%s_%i" % (prgi_name, prog_count-1) # "MOD_Tmp"
                        tempmodule_header = list(prgi_header_tmp) # make sure we create a copy
                        tempmodule_header += [ONETAB + 'PROC Main()\n']                        
                    else:
                        id_temp = (prog_count-1) % 3 + 1
                        tempmodule_name = "MOD_Tmp%i" % id_temp
                        tempmodule_header = [ONETAB + 'PROC Prg_Tmp%i()\n' % id_temp]
                        
                    tempmodule_footer = ['',ONETAB+'ENDPROC']
                    temp_prgi = tempmodule_header + temp_prgi + tempmodule_footer

                    # Save the module                    
                    self.save_module(file_name_i, temp_prgi, tempmodule_name)
                    line_start = line_end
                
                if not self.EXTERNAL_DRIPFEEDER:
                    # Create the parent program that will call all the modules:
                    add_variables = ['']
                    prgi_parent = []
                    
                    add_variables.append(ONETAB + 'LOCAL PERS string modulepath1 := "";')
                    add_variables.append(ONETAB + 'LOCAL PERS string modulepath2 := "";')
                    add_variables.append(ONETAB + 'LOCAL VAR loadsession load1;')
                    add_variables.append(ONETAB + 'LOCAL VAR loadsession load2;')
                    add_variables.append(ONETAB + 'LOCAL VAR string module_unload := "";')
                    add_variables.append(ONETAB)              
                    
                    #prgi_parent.append(ONETAB + ONETAB + 'PROC %s()' % prgi_name) #will be added later
                    prgi_parent.append(ONETAB + ONETAB + '! This program has automatically been split into smaller subprograms')
                    prgi_parent.append(ONETAB + ONETAB + 'TPErase;\n')
                    
                    # Unloading files does not always work
                    #prgi_parent.append(ONETAB + ONETAB + '! Unload previous modules if necessary')
                    #prgi_parent.append(ONETAB + ONETAB + 'IF StrLen(modulepath1) > 0 THEN')
                    #prgi_parent.append(ONETAB + ONETAB + ONETAB + 'module_unload := modulepath1;')
                    #prgi_parent.append(ONETAB + ONETAB + ONETAB + 'modulepath1 := "";')
                    #prgi_parent.append(ONETAB + ONETAB + ONETAB + 'UnLoad module_unload;')
                    #prgi_parent.append(ONETAB + ONETAB + 'ENDIF')
                    #prgi_parent.append(ONETAB + ONETAB + 'IF StrLen(modulepath2) > 0 THEN')
                    #prgi_parent.append(ONETAB + ONETAB + ONETAB + 'module_unload := modulepath2;')
                    #prgi_parent.append(ONETAB + ONETAB + ONETAB + 'modulepath2 := "";')
                    #prgi_parent.append(ONETAB + ONETAB + ONETAB + 'UnLoad module_unload;')
                    #prgi_parent.append(ONETAB + ONETAB + 'ENDIF')
                    #prgi_parent.append(ONETAB + ONETAB + '')

                
                    for j in range(prog_count):
                        file = getBaseName(file_names[j])
                        j_next = j+1
                        id_load = 1 + (j % 2)                          
                        temp_module_name = 'modulepath%i' % id_load
                        temp_load_name = 'load%i' % id_load
                        
                        prgi_parent.append(ONETAB + ONETAB + 'TPWrite "Starting Subprogram %i/%i";' % (j_next, prog_count))
                        if j == 0:
                            prgi_parent.append(ONETAB + ONETAB + "! Load the first program (may take some time)")
                            prgi_parent.append(ONETAB + ONETAB + '%s := "%s";' % (temp_module_name, (self.RAPID_REMOTE_PATH + '/' + file)))
                            prgi_parent.append(ONETAB + ONETAB + "Load \Dynamic, %s;" % temp_module_name)
                        else:
                            prgi_parent.append(ONETAB + ONETAB + "! Wait for the program to be ready (fast)")
                            prgi_parent.append(ONETAB + ONETAB + "WaitLoad %s;" % temp_load_name)
                        
                        if j < prog_count-1:
                            file_next = getBaseName(file_names[j+1])
                            id_load_next = 1 + (j_next % 2)
                            load_name_next = 'load%i' % id_load_next
                            module_name_next = 'modulepath%i' % id_load_next                    
                            prgi_parent.append(ONETAB + ONETAB + '%s := "%s";' % (module_name_next, (self.RAPID_REMOTE_PATH + '/' + file_next)))
                            prgi_parent.append(ONETAB + ONETAB + "StartLoad %s, %s;" % (module_name_next, load_name_next))
                        
                        id_mod = j % 3 + 1
                        prgi_parent.append(ONETAB + ONETAB + "%%\"MOD_Tmp%i:Prg_Tmp%i\"%%;" % (id_mod, id_mod))
                        prgi_parent.append(ONETAB + ONETAB + 'Unload %s;' % temp_module_name)
                        prgi_parent.append(ONETAB + ONETAB + '%s := "";\n\n' % temp_module_name)
                        
                    prgi_parent.append(ONETAB + ONETAB + 'TPWrite "Program completed";\n')
    
                    prgi_lines = prgi_parent
                    module_addtop = add_variables + module_addtop

            prgi_header = []
            if i == 0:
                # Add custom header, tools and reference frames for the main program
                prgi_header.append(CUSTOM_HEADER)
                prgi_header.append('')
                prgi_header += self.TOOL_DEF
                prgi_header.append('')
                prgi_header += self.FRAME_DEF
                prgi_header.append('')
                
            # Add program calls
            prgi_header += module_addtop
            module_addtop = []
                        
            prgi_header.append(ONETAB + 'PROC %s()' % prgi_name)
            prgi_footer = [ONETAB + 'ENDPROC']            
            prgi_complete = prgi_header + prgi_lines + prgi_footer
            filesave_complete = filesave + '.' + self.PROG_EXT
            self.save_module(filesave_complete, prgi_complete, module_name)
                
            # Remember saved files that are not temporary modules
            files_display.append(filesave_complete)
            print('SAVED: %s\n' % filesave_complete) # tell RoboDK the path of the saved file
            sys.stdout.flush()            
        
        #-------------------------------------------------------        
        # open file with default application
        if show_result:
            if type(show_result) is str:
                # Open file with provided application
                import subprocess
                p = subprocess.Popen([show_result] + files_display)
            elif type(show_result) is list:
                import subprocess
                p = subprocess.Popen(show_result + files_display)   
            else:
                # open file with default application
                import os
                os.startfile(filesave)
            if len(self.LOG) > 0:
                mbox('Program generation LOG:\n\n' + self.LOG)                
                 
    def ProgSendRobot(self, robot_ip, remote_path, ftp_user, ftp_pass):
        """Send a program to the robot using the provided parameters. This method is executed right after ProgSave if we selected the option "Send Program to Robot".
        The connection parameters must be provided in the robot connection menu of RoboDK"""
        UploadFTP(self.PROG_FILES, robot_ip, remote_path, ftp_user, ftp_pass)
        
    def MoveJ(self, pose, joints, conf_RLF=None):
        """Add a joint movement"""
        if self.MOVEJ_AS_MOVEABSJ or pose is None:
            self.addline('MoveAbsJ [%s,%s],%s,%s,%s \WObj:=%s;' % (angles_2_str(joints), extaxes_2_str(joints, self.AXES_RATIO), self.SPEEDDATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
        else:
            if conf_RLF is None:
                conf_RLF = [0,0,0]
            cf1 = 0
            cf4 = 0
            cf6 = 0            
            if joints is not None and len(joints) >= 6:
                cf1 = math.floor(joints[0]/90.0)
                cf4 = math.floor(joints[3]/90.0)
                cf6 = math.floor(joints[5]/90.0)
            [REAR, LOWERARM, FLIP] = conf_RLF
            cfx = 4*REAR + 2*LOWERARM + FLIP
            target = '[%s,[%i,%i,%i,%i],%s]' % (pose_2_str(pose), cf1, cf4, cf6, cfx, extaxes_2_str(joints, self.AXES_RATIO))
            
            self.addline('MoveJ %s,%s,%s,%s \WObj:=%s;' % (target, self.SPEEDDATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
            
        self.LAST_TARGET = None
        
    def calculate_time(self, distance, Vmax, Amax=-1):
        """Calculate the time to move a distance with Amax acceleration and Vmax speed"""
        if Amax < 0:
            # Assume constant speed (appropriate smoothing/rounding parameter must be set)
            Ttot = distance/Vmax
        else:
            # Assume we accelerate and decelerate
            tacc = Vmax/Amax;
            Xacc = 0.5*Amax*tacc*tacc;
            if distance <= 2*Xacc:
                # Vmax is not reached
                tacc = sqrt(distance/Amax)
                Ttot = tacc*2
            else:
                # Vmax is reached
                Xvmax = distance - 2*Xacc
                Tvmax = Xvmax/Vmax
                Ttot = 2*tacc + Tvmax
        return Ttot
            
    def new_move(self, new_pose):                        
        """Implement the action on the extruder for 3D printing, if applicable"""
        if self.PRINT_E_NEW is None or new_pose is None:
            return
            
        # Skip the first move and remember the pose
        if self.PRINT_POSE_LAST is None:
            self.PRINT_POSE_LAST = new_pose
            return          

        # Calculate the increase of material for the next movement
        add_material = self.PRINT_E_NEW - self.PRINT_E_LAST
        self.PRINT_E_LAST = self.PRINT_E_NEW
        
        # Calculate the robot speed and Extruder signal
        extruder_signal = 0
        if add_material > 0:
            distance_mm = norm(subs3(self.PRINT_POSE_LAST.Pos(), new_pose.Pos()))
            # Calculate movement time in seconds
            time_s = self.calculate_time(distance_mm, self.SPEED_MMS, self.PRINT_ACCEL_MMSS)
            
            # Avoid division by 0
            if time_s > 0:
                # This may look redundant but it allows you to account for accelerations and we can apply small speed adjustments
                speed_mms = distance_mm / time_s
                
                # Calculate the extruder speed in RPM*Ratio (PRINT_SPEED_2_SIGNAL)
                extruder_signal = speed_mms * self.PRINT_SPEED_2_SIGNAL
        
        # Make sure the signal is within the accepted values
        extruder_signal = max(0,min(self.PRINT_FLOW_MAX_SIGNAL, extruder_signal))
        
        # Update the extruder speed when required
        if self.PRINT_LAST_SIGNAL is None or abs(extruder_signal - self.PRINT_LAST_SIGNAL) > 1e-6:
            self.PRINT_LAST_SIGNAL = extruder_signal
            #self.setDO(self.PRINT_E_AO, "%.3f" % extruder_signal)
            self.addline('ExtruderSpeed %.3f;' % extruder_signal)
        
        # Remember the last pose
        self.PRINT_POSE_LAST = new_pose
      
    def MoveL(self, pose, joints, conf_RLF=None):
        """Add a linear movement"""        
        target = ''
        if pose is None:
            target = 'CalcRobT([%s,%s],%s \WObj:=%s)' % (angles_2_str(joints), extaxes_2_str(joints, self.AXES_RATIO), self.TOOLDATA, self.WOBJDATA)
        else:
            # Filter small movements
            #if self.LAST_POSE is not None and pose is not None:
            #    # Skip adding a new movement if the new position is the same as the last one
            #    if distance(pose.Pos(), self.LAST_POSE.Pos()) < 0.001 and pose_angle_between(pose, self.LAST_POSE) < 0.01:
            #        return                    
            
            # Handle 3D printing Extruder integration
            self.new_move(pose)      
        
            if conf_RLF is None:
                conf_RLF = [0,0,0]
            cf1 = 0
            cf4 = 0
            cf6 = 0            
            if joints is not None and len(joints) >= 6:
                cf1 = math.floor(joints[0]/90.0)
                cf4 = math.floor(joints[3]/90.0)
                cf6 = math.floor(joints[5]/90.0)
            [REAR, LOWERARM, FLIP] = conf_RLF
            cfx = 4*REAR + 2*LOWERARM + FLIP
            target = '[%s,[%i,%i,%i,%i],%s]' % (pose_2_str(pose), cf1, cf4, cf6,cfx, extaxes_2_str(joints, self.AXES_RATIO))
            
        if self.ARC_ON:
            # ArcL p100, v100, seam1, weld5 \Weave:=weave1, z10, gun1;
            if self.ARC_ON == 2:
                self.addline('ArcLStart %s,%s,%s,%s,\Weave:=%s,%s,%s \WObj:=%s;' % (target, self.SPEEDDATA, self.ARC_SEAMDATA, self.ARC_WELDDATA, self.ARC_WEAVEDATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
            else:                
                self.addline('ArcL %s,%s,%s,%s,\Weave:=%s,%s,%s \WObj:=%s;' % (target, self.SPEEDDATA, self.ARC_SEAMDATA, self.ARC_WELDDATA, self.ARC_WEAVEDATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
            
            self.ARC_ON = True
                
        elif self.CLAD_ON:
            self.addline('CladL %s,%s,%s,%s,%s \WObj:=%s;' % (target, self.SPEEDDATA, self.CLAD_DATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
        else:
            self.addline('MoveL %s,%s,%s,%s \WObj:=%s;' % (target, self.SPEEDDATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
            
        self.LAST_TARGET = target
            
    def MoveC(self, pose1, joints1, pose2, joints2, conf_RLF_1=None, conf_RLF_2=None):
        """Add a circular movement"""
        target1 = ''
        target2 = ''
        if pose1 is None:
            target1 = 'CalcRobT([%s,%s], %s \WObj:=%s)' % (angles_2_str(joints1), extaxes_2_str(joints1, self.AXES_RATIO), self.TOOLDATA, self.WOBJDATA)
        else:
            if conf_RLF_1 is None:
                conf_RLF_1 = [0,0,0]                
            cf1_1 = 0
            cf4_1 = 0
            cf6_1 = 0   
            if joints1 is not None and len(joints1) >= 6:
                cf1_1 = math.floor(joints1[0]/90.0)
                cf4_1 = math.floor(joints1[3]/90.0)
                cf6_1 = math.floor(joints1[5]/90.0)
            [REAR, LOWERARM, FLIP] = conf_RLF_1
            cfx_1 = 4*REAR + 2*LOWERARM + FLIP
            target1 = '[%s,[%i,%i,%i,%i],%s]' % (pose_2_str(pose1), cf1_1, cf4_1, cf6_1,cfx_1, extaxes_2_str(joints1, self.AXES_RATIO))
            
        if pose2 is None:
            target2 = 'CalcRobT([%s,%s],%s \WObj:=%s)' % (angles_2_str(joints2), extaxes_2_str(joints2, self.AXES_RATIO), self.TOOLDATA, self.WOBJDATA)
        else:
            if conf_RLF_2 is None:
                conf_RLF_2 = [0,0,0]
            cf1_2 = 0
            cf4_2 = 0
            cf6_2 = 0  
            if joints2 is not None and len(joints2) >= 6:
                cf1_2 = math.floor(joints2[0]/90.0)
                cf4_2 = math.floor(joints2[3]/90.0)
                cf6_2 = math.floor(joints2[5]/90.0)
            [REAR, LOWERARM, FLIP] = conf_RLF_2
            cfx_2 = 4*REAR + 2*LOWERARM + FLIP
            target2 = '[%s,[%i,%i,%i,%i],%s]' % (pose_2_str(pose2), cf1_2, cf4_2, cf6_2,cfx_2, extaxes_2_str(joints2, self.AXES_RATIO))
           
        if self.ARC_ON:
            # ArcL p100, v100, seam1, weld5 \Weave:=weave1, z10, gun1;
            self.addline('ArcC %s,%s,%s,%s,%s \Weave:=%s,%s,%s \WObj:=%s;' % (target1, target2, self.SPEEDDATA, self.ARC_SEAMDATA, self.ARC_WELDDATA, self.ARC_WEAVEDATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
        elif self.CLAD_ON:
            self.addline('CladC %s,%s,%s,%s,%s,%s \WObj:=%s;' % (target1, target2, self.SPEEDDATA, self.CLAD_DATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
        else:
            self.addline('MoveC %s,%s,%s,%s,%s \WObj:=%s;' % (target1, target2, self.SPEEDDATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
            
        self.LAST_TARGET = target2
    
    def setFrame(self, pose, frame_id=None, frame_name=None):
        """Change the robot reference frame"""
        #self.addline('rdkWObj := [FALSE, TRUE, "", [%s],[[0,0,0],[1,0,0,0]]];' % pose_2_str(pose))
        if frame_name is not None:
            self.WOBJDATA = FilterName(frame_name,'w',RESERVED_NAMES)
     
        #self.addline('%s.uframe := [%s];' % (self.WOBJDATA, pose_2_str(pose)))
        set_data = ''
        if self.HAS_TURNTABLE:
            if self.TURNTABLE_IGNORE and self.FR_EXTERNAL_POSE is not None:
                pose = self.FR_EXTERNAL_POSE*pose
                set_data = '%s := [FALSE, TRUE, "", [%s],[[0,0,0],[1,0,0,0]]];' % (self.WOBJDATA, pose_2_str(pose))
            else:
                set_data = '%s := [FALSE, FALSE, "%s", [%s],[[0,0,0],[1,0,0,0]]];' % (self.WOBJDATA, self.MECHANICAL_UNIT_NAME, pose_2_str(pose))
            
        else:
            set_data = '%s := [FALSE, TRUE, "", [%s],[[0,0,0],[1,0,0,0]]];' % (self.WOBJDATA, pose_2_str(pose))
            
        #print(self.WOBJDATA)
        #print(str(self.FRAME_LIST))
        if self.WOBJDATA in self.FRAME_LIST:
            self.addline(set_data)
        else:
            self.FRAME_LIST.append(self.WOBJDATA)
            self.FRAME_DEF.append(ONETAB + 'PERS wobjdata %s' % set_data)
        
    def setTool(self, pose, tool_id=None, tool_name=None):
        """Change the robot TCP"""
        if tool_name is not None:
            self.TOOLDATA = FilterName(tool_name,'t',RESERVED_NAMES)
        
        #self.addline('%s.tframe := [%s];' % (self.TOOLDATA, pose_2_str(pose)))
        set_data = '%s := [TRUE,[%s],[1,[0,0,20],[1,0,0,0],0,0,0.005]];' % (self.TOOLDATA, pose_2_str(pose))
        if self.TOOLDATA in self.TOOL_LIST:
            self.addline(set_data)
        else:
            self.TOOL_LIST.append(self.TOOLDATA)
            self.TOOL_DEF.append(ONETAB + 'PERS tooldata %s' % set_data)
        
    def Pause(self, time_ms):
        """Pause the robot program"""
        if time_ms <= 0:
            self.addline('STOP;')
        else:
            self.addline('WaitTime %.3f;' % (time_ms*0.001))
        
    def setSpeed(self, speed_mms):
        """Changes the robot speed (in mm/s)"""
        # force a specific speed limitation
        max_speed_mms = 7000
        min_speed_mms = 0.01
        speed_mms = max(min(speed_mms, max_speed_mms), min_speed_mms)
        self.SPEED_MMS = speed_mms        
        if speed_mms in KNOWN_SPEEDS:
            self.SPEEDDATA = 'v%i' % int(speed_mms)
        else:
            self.SPEEDDATA = '[%.2f,500,5000,1000]' % speed_mms
        
    def setAcceleration(self, accel_mmss):
        """Changes the robot acceleration (in mm/s2)"""
        self.addlog('setAcceleration is not defined')
        
    def setSpeedJoints(self, speed_degs):
        """Changes the robot joint speed (in deg/s)"""
        self.addlog('setSpeedJoints not defined')
    
    def setAccelerationJoints(self, accel_degss):
        """Changes the robot joint acceleration (in deg/s2)"""
        self.addlog('setAccelerationJoints not defined')
        
    def setZoneData(self, zone_mm):
        """Changes the zone data approach (makes the movement more smooth)"""
        if zone_mm < 0:
            self.ZONEDATA = 'fine'
        else:
            if zone_mm in KNOWN_ZONEDATA:
                self.ZONEDATA = 'z%i' % int(zone_mm)
            else:
                zone_mm_O = zone_mm * 1.5
                zone_mm_O2 = 0.1*zone_mm_O
                self.ZONEDATA = '[FALSE,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f]' % (zone_mm,zone_mm_O,zone_mm_O,zone_mm_O2,zone_mm_O,zone_mm_O2)
        
    def setDO(self, io_var, io_value):
        """Set a Digital Output"""
        if type(io_var) != str:  # set default variable name if io_var is a number
            io_var = 'D_OUT_%s' % str(io_var)        
        if type(io_value) != str: # set default variable value if io_value is a number            
            if io_value > 0:
                io_value = '1'
            else:
                io_value = '0'
        
        # at this point, io_var and io_value must be string values
        self.addline('SetDO %s, %s;' % (io_var, io_value))
        
    def setAO(self, io_var, io_value):
        """Set an Analog Output"""
        self.setDO(io_var, io_value)
        
    def waitDI(self, io_var, io_value, timeout_ms=-1):
        """Waits for an input io_var to attain a given value io_value. Optionally, a timeout can be provided."""
        if type(io_var) != str:  # set default variable name if io_var is a number
            io_var = 'D_IN_%s' % str(io_var)        
        if type(io_value) != str: # set default variable value if io_value is a number            
            if io_value > 0:
                io_value = '1'
            else:
                io_value = '0'
        
        # at this point, io_var and io_value must be string values
        if timeout_ms < 0:
            self.addline('WaitDI %s, %s;' % (io_var, io_value))
        else:
            self.addline('WaitDI %s, %s, \MaxTime:=%.1f;' % (io_var, io_value, timeout_ms*0.001))   
        
    def RunCode(self, code, is_function_call = False):
        """Adds code or a function call"""
        if is_function_call:
            code = code.replace(' ','_')
            code_lower = code.lower()
            if code_lower.startswith('arclstart') or code_lower.startswith('arcstart'):
                if not self.ARC_ON:
                    self.ARC_ON = 2 # provke first move with ArcLStart
                return
            elif code_lower.startswith('arclend') or code_lower.startswith('arcend'):
                self.ARC_ON = False
                # add a new redundant move
                self.addline('ArcLEnd %s,%s,%s,%s,\Weave:=%s,%s,%s \WObj:=%s;' % (self.LAST_TARGET, self.SPEEDDATA, self.ARC_SEAMDATA, self.ARC_WELDDATA, self.ARC_WEAVEDATA, self.ZONEDATA, self.TOOLDATA, self.WOBJDATA))
                return
            elif code_lower.startswith('cladlstart'):
                self.CLAD_ON = True
                return
            elif code_lower.startswith('cladlend'):
                self.CLAD_ON = False
            elif code_lower.startswith("extruder("):            
                # If the program call is Extruder(123.56), we extract the number as a string and convert it to a number
                self.PRINT_E_NEW = float(code[9:-1]) # it needs to retrieve the extruder length from the program call
                # Do not generate the program call
                return
            
            code_safe = FilterName(code)
            self.addline(code_safe + ';')
            
        else:
            if code.startswith('END') or code.startswith('ELSEIF'):
                # remove tab after ENDWHILE or ENDIF
                self.TAB = self.TAB[:-len(ONETAB)]
                
            self.addline(code.replace('\t','  '))# replace each tab by 2 spaces

            if code.startswith('IF ') or code.startswith('ELSEIF ') or code.startswith('WHILE '):
                # add tab (one tab = two spaces)
                self.TAB = self.TAB + ONETAB
            
        
    def RunMessage(self, message, iscomment = False):
        """Add a joint movement"""
        if iscomment:
            self.addline('! ' + message)
        else:
            self.addline('TPWrite "%s";' % message)
        
# ------------------ private ----------------------                
    def addline(self, newline):
        """Add a program line"""
        if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS:
            return
            
        self.PROG += [self.TAB + newline]
        
    def addlog(self, newline):
        """Add a log message"""
        if self.nProgs > 1 and not self.INCLUDE_SUB_PROGRAMS:
            return
            
        self.LOG = self.LOG + newline + '\n'
        

# -------------------------------------------------
# ------------ For testing purposes ---------------   
def Pose(xyzrpw):
    [x,y,z,r,p,w] = xyzrpw
    a = r*math.pi/180
    b = p*math.pi/180
    c = w*math.pi/180
    ca = math.cos(a)
    sa = math.sin(a)
    cb = math.cos(b)
    sb = math.sin(b)
    cc = math.cos(c)
    sc = math.sin(c)
    return Mat([[cb*ca, ca*sc*sb - cc*sa, sc*sa + cc*ca*sb, x],[cb*sa, cc*ca + sc*sb*sa, cc*sb*sa - ca*sc, y],[-sb, cb*sc, cc*cb, z],[0,0,0,1]])

def test_post():
    """Test the post with a basic program"""

    robot = RobotPost(r'ABB_RAPID_IRC5', r'ABB IRB 6700-155/2.85', 6, axes_type=['R','R','R','R','R','R'])

    robot.ProgStart(r'Prog1')
    robot.RunMessage(r'Program generated by RoboDK 3.1.5 for ABB IRB 6700-155/2.85 on 18/05/2017 11:02:41', True)
    robot.RunMessage(r'Using nominal kinematics.', True)
    robot.setFrame(Pose([0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000]),-1,r'ABB IRB 6700-155/2.85 Base')
    robot.setTool(Pose([380.000000, 0.000000, 200.000000, 0.000000, 90.000000, 0.000000]),1,r'Tool 1')
    robot.setSpeed(2000.000)
    robot.MoveJ(Pose([2103.102861, 0.000000, 1955.294643, -180.000000, -3.591795, -180.000000]), [0.00000, 3.93969, -14.73451, 0.00000, 14.38662, -0.00000], [0.0, 0.0, 0.0])
    robot.MoveJ(Pose([2065.661612, 700.455189, 1358.819971, 180.000000, -3.591795, -180.000000]), [22.50953, 5.58534, 8.15717, 67.51143, -24.42689, -64.06258], [0.0, 0.0, 1.0])
    robot.Pause(500.0)
    robot.setSpeed(100.000)
    #robot.RunCode(r'ArcLStart', True)
    robot.MoveL(Pose([2065.661612, 1074.197508, 1358.819971, 149.453057, -3.094347, -178.175378]), [36.19352, 22.86988, -12.37860, 88.83085, -66.57439, -81.72795], [0.0, 0.0, 1.0])
    robot.MoveC(Pose([2468.239418, 1130.614560, 1333.549802, -180.000000, -3.591795, -180.000000]), [28.37934, 35.45210, -28.96667, 85.54799, -28.41204, -83.00289], Pose([2457.128674, 797.241647, 1156.545094, 180.000000, -37.427062, -180.000000]), [18.58928, 43.77805, -40.05410, 155.58093, -37.76022, -148.70252], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0])
    robot.MoveL(Pose([2457.128674, 797.241647, 1156.545094, 180.000000, -37.427062, -180.000000]), [18.58928, 43.77805, -40.05410, 155.58093, -37.76022, -148.70252], [0.0, 0.0, 1.0])
    robot.MoveL(Pose([2469.684137, 397.051453, 1356.565545, -180.000000, -3.591795, -180.000000]), [10.73523, 21.17902, -10.22963, 56.13802, -12.93695, -54.77268], [0.0, 0.0, 1.0])
    robot.MoveL(Pose([2494.452316, 404.343933, 1751.146172, -180.000000, -3.591795, -180.000000]), [10.80299, 25.05092, -31.54821, 132.79244, -14.76878, -133.06820], [0.0, 0.0, 1.0])
    robot.MoveL(Pose([2494.452316, 834.649436, 1751.146172, -180.000000, -3.591795, -180.000000]), [21.49850, 33.45974, -43.37980, 121.21995, -25.32130, -122.42907], [0.0, 0.0, 1.0])
    robot.setZoneData(5.000)
    robot.MoveL(Pose([2147.781731, 834.649436, 1772.906995, -180.000000, -3.591795, -180.000000]), [25.21677, 13.65153, -17.95808, 107.03387, -26.40518, -107.19412], [0.0, 0.0, 1.0])
    robot.MoveL(Pose([2147.781731, 375.769504, 1772.906995, -180.000000, -3.591795, -180.000000]), [11.97030, 5.74930, -8.96838, 119.55454, -13.76610, -119.51539], [0.0, 0.0, 1.0])
    robot.MoveL(Pose([2147.781731, 61.363728, 1772.906995, -180.000000, -3.591795, -180.000000]), [1.98292, 3.75693, -6.84136, -16.54793, 6.96416, 16.55673], [0.0, 0.0, 0.0])
    #robot.RunCode(r'ArcLEnd', True)
    robot.MoveL(Pose([2147.781731, 275.581430, 1772.906995, -180.000000, -3.591795, -180.000000]), [8.83799, 4.80606, -7.95436, 127.27676, -11.11070, -127.24243], [0.0, 0.0, 1.0])
    robot.ProgFinish(r'Prog1')
    
    for prgi in robot.PROG_LIST:
        for line in prgi:
            print(line)
        print('')
        print('')
        
    
    if len(robot.LOG) > 0:
        mbox('Program generation LOG:\n\n' + robot.LOG)
    input("Press Enter to close...")

if __name__ == "__main__":
    """Function to call when the module is executed by itself: test"""
    test_post()
