Skip to content

API Reference

mecode_viewer()

Parameters:

Name Type Description Default
file_name str

name of gcode file

required
rel_mode bool

True if relative coordinates, False if absolute coordinates

False
animate bool

True for 3D animation, False for static matplotlib figure

False
verbose bool

If True, will return print history as a list of dict's

False
raw_gcode List[str]

Can provide list of gcode str commands in lieu of file_name

None
origin Union[List[Union[int, float]], Tuple[Union[int, float]]]

Specify origin as initial starting point

(0, 0, 0)
extrude_cmd str or List[str] or Tuple[str]

Command string that is used to start extruding.E.g., Nordson pressure controller will typically use Call togglePress, whereas linear actuators use a command that contains FREERUN PDISP5 ...

None
extrude_cmd str or List[str] or Tuple[str]

Command string that is used to stop extruding.

None

Returns:

Type Description
Optional[List[Dict]]

Optional[List[Dict]]: If verbose is true, will return print history

Examples:

>>> mecode_viewer(file_name='gcode_file.pgm') # simplest case
>>> mecode_viewer(file_name='gcode_file.pgm', rel_mode=True) # specify relative coordinates are being used
>>> mecode_viewer(file_name='gcode_file.pgm', animate=True) # show vpython 3D animation
>>> mecode_viewer(file_name='gcode_file.pgm', extrude_cmd='FREERUN PDISP5') # using linear actuator command to specify extrusion

Note

If extrude_cmd is not provided, the default value will be to use the Nordson controller command (Call togglePress). If extrude_cmd is provided, mecode_viewer will search for extrude_cmd within gcode.

Source code in mecode_viewer/mecode_viewer.py
def mecode_viewer(file_name: str,
                  rel_mode: bool=False,
                  animate: bool=False,
                  verbose: bool=False,
                  raw_gcode: List[str]=None,
                  hide_plots: bool=False,
                  origin: Union[List[Union[int, float]], Tuple[Union[int, float]]]=(0,0,0),
                  extrude_cmd:  Union[str, List[str], Tuple[str]]=None,
                  extrude_stop_cmd: Union[str, List[str], Tuple[str]]=None,
                  **kwargs
                  ) -> Optional[List[Dict]]:
    '''mecode_viewer()

        Args:
            file_name (str): name of gcode file
            rel_mode (bool): True if relative coordinates, False if absolute coordinates
            animate (bool): True for 3D animation, False for static matplotlib figure
            verbose (bool): If True, will return print history as a list of dict's
            raw_gcode (List[str]): Can provide list of gcode str commands in lieu of file_name
            origin (Union[List[Union[int, float]], Tuple[Union[int, float]]]): Specify origin as initial starting point
            extrude_cmd (str or List[str] or Tuple[str]): Command string that is used to start extruding.E.g., Nordson pressure controller will typically use `Call togglePress`, whereas linear actuators use a command that contains `FREERUN PDISP5 ...`
            extrude_cmd (str or List[str] or Tuple[str]): Command string that is used to stop extruding.

        Returns:
            Optional[List[Dict]]: If `verbose` is true, will return print history

        Examples:
            >>> mecode_viewer(file_name='gcode_file.pgm') # simplest case

            >>> mecode_viewer(file_name='gcode_file.pgm', rel_mode=True) # specify relative coordinates are being used

            >>> mecode_viewer(file_name='gcode_file.pgm', animate=True) # show vpython 3D animation

            >>> mecode_viewer(file_name='gcode_file.pgm', extrude_cmd='FREERUN PDISP5') # using linear actuator command to specify extrusion

            !!! note

                If `extrude_cmd` is not provided, the default value will be to use the Nordson controller command (`Call togglePress`). If `extrude_cmd` is provided, `mecode_viewer` will search for `extrude_cmd` within gcode.  


    '''
    # variables
    REL_MODE = rel_mode #True if mode == 'rel' else False

    ACCEL_RATE = 2000
    DECEL_RATE = 2000

    P_COM_PORT = 5
    PRESSURE = 0
    PRINT_SPEED = 0
    PRINTING = False
    if extrude_cmd is None:
        PRINTING = False
    elif isinstance(extrude_cmd, str):
        PRINTING = {extrude_cmd.strip(): {'printing': False, 'value': 0}}
    elif any([isinstance(extrude_cmd, list), isinstance(extrude_cmd, tuple)]):
        PRINTING = {k.strip() : {'printing': False, 'value': 0} for k in extrude_cmd}
    else:
        raise ValueError('Unsupported `extrude_cmd` provided. ', extrude_cmd)

    ORIGIN = origin
    VARIABLES = {}

    history = [{
            'REL_MODE': REL_MODE,
            'ACCEL' : ACCEL_RATE,
            'DECEL' : DECEL_RATE,
            'P' : PRESSURE,
            'P_COM_PORT': P_COM_PORT,
            'PRINTING': PRINTING,
            'PRINT_SPEED': 0,
            'COORDS': origin,
            'ORIGIN': origin,
            'CURRENT_POSITION': {'X': origin[0], 'Y': origin[1], 'Z': origin[2]},
            'VARIABLES': VARIABLES,
            'COLOR': kwargs['color'] if 'color' in kwargs else None
        }]


    move_counter = 1

    if raw_gcode is not None:
        print('raw gcode')
        file_contents = raw_gcode
    # elif isfile(file_name):
    elif len(file_name) > 0:
        print('openning file: ', file_name)
        with open(file_name, 'r') as f:
            file_contents = f.readlines()
    else:
        print('file_name is neither a file nor a string...')

    for j, line in enumerate(file_contents):
        if line.strip().startswith(';') != ';': 
            # check if need to re-define origin
            ORIGIN = _check_origin_change(line, ORIGIN, history[move_counter-1]['COORDS'])

            # keep track of any aerotech variables created with `#define`
            if '#define' in line:
                define_pattern = re.compile(r'#define\s+(\w+)\s+([\d.]+)')
                match = re.match(define_pattern, line)
                if match:
                    variable_name, variable_value = match.groups()
                    VARIABLES[variable_name] = float(variable_value)

            # identify if gcode is in relative mode
            REL_MODE = get_print_mode(line, REL_MODE)

            # set accel and decel rates
            ACCEL_RATE, DECEL_RATE = get_accel_decel(line, ACCEL_RATE, DECEL_RATE)

            # get pressure config
            PRESSURE, P_COM_PORT = get_pressure_config(line, PRESSURE, P_COM_PORT)

            # are we printing?
            PRINTING = are_we_printing(line, PRINTING, extrude_cmd, extrude_stop_cmd, VARIABLES)

            if ('G1' in line or 'G01' in line or 'G00' in line):
                COORDS, PRINT_SPEED = get_print_move(line, history[move_counter-1], REL_MODE, VARIABLES)
                if COORDS is not None:
                    history.append({
                        'REL_MODE': REL_MODE,
                        'ACCEL' : ACCEL_RATE,
                        'DECEL' : DECEL_RATE,
                        'P' : PRESSURE,
                        'P_COM_PORT': P_COM_PORT,
                        'PRINTING': PRINTING,
                        'PRINT_SPEED' : PRINT_SPEED,
                        'COORDS': COORDS,
                        'ORIGIN': ORIGIN,
                        'CURRENT_POSITION': _update_current_position(COORDS, history[move_counter-1]['CURRENT_POSITION'], REL_MODE,),
                        'VARIABLES': VARIABLES
                    })
                    move_counter += 1

    if hide_plots is False:
        if not animate:
            plot3d(history, **kwargs)
        elif animate:
            animation(history, **kwargs)
        else:
            raise ValueError("Invalid plotting backend! Choose one of mayavi or matplotlib or matplotlib2d or vpython.")

    if verbose:
        return history