Plotter

Plotter

new Plotter()

Source:
To Do:
  • Use OO to identify plotters with potential extended capabilities (such as 7440A)
  • Create a getter that returns the size of the plottable area.
  • Instructions queued with waitForResponse should timeout if the response does not come`
  • The queue() function should validate if the instruction(s) is actually valid.
  • Implement penThickness.
  • ?? The buffer must be flushed during connect because some devices (7440A) will keep commands in the buffer

The Plotter class provides methods to interact with an HPGL-compatible plotter such as those made by HP. Various other makers also use or support the HPGL protocol (Calcomp, for example).

Event Handling

This object extends Node's core EventEmitter object. This means you can use methods such as: on(), once(), removeListener(), etc.

Usage examples

Here is how you can use the Plotter object in a Node.js-compatible project:

const SerialPort = require("serialport");
let transport = new SerialPort("/dev/tty.usbserial", { autoOpen: false });

const Plotter = require("hpgl").Plotter;
let plotter = new Plotter();

plotter.connect(transport, {orientation: "portrait"}, function(error) {

  if (error) {
    console.log(error);
    return;
  }

  this
    .moveTo(2, 2)
    .drawText("Hello, World!")
    .moveTo(5, 5)
    .drawRectangle(4, 3)

});

If you are using NW.js, you need to change the first three lines of code to this:

var SerialPort = nw.require("browser-serialport").SerialPort;
var transport = new SerialPort("/dev/tty.usbserial", {}, false);

const Plotter = nw.require("hpgl").Plotter;
Fires:

Members

(readonly) characteristics :PlotterCharacteristics

Source:
Type:

(readonly) connected :Number

Source:

Indicates whether a successful serial connection has been established or not. This does not necessarily mean the device is ready to receive commands.

To know when the device is ready to receive commands, you can check out the ready property or listen to the ready event

Type:
  • Number

(readonly) flipX :Boolean

Source:
Default Value:
  • false

Whether the drawing should be flipped along the x-axis.

Type:
  • Boolean

(readonly) flipY :Boolean

Source:
Default Value:
  • false

Whether the drawing should be flipped along the y-axis.

Type:
  • Boolean

(readonly) orientation :String

Source:
Default Value:
  • "landscape"

The paper orientation currently selected (portrait or landscape). Paper orientation is assigned during the connection to the device (with the connect() function) or when saving to file (with the connect() function).

Type:
  • String

(readonly) paper :String

Source:
Default Value:
  • "A"

The format of paper currently selected (A4, letter, B, etc.). Paper format is assigned during the connection to the device (with the connect() function). Currently, it cannot be changed on the fly.

Type:
  • String

penThickness :Number

Source:

The thickness of the drawing pen's nib in millimiters. The value must be between 0.1 and 5. Specifying an invalid value will set the thickness to the default value of 0.3.

Specifying the pen's thickness is particularly important when trying to shade shapes.

Type:
  • Number

(readonly) ready :Boolean

Source:

Indicates whether the device is ready to receive commands or not. The device is ready only after having been successfully connected by using the Plotter.connect() function. Instructions should not be sent to the device prior to it being ready.

The Plotter object triggers the ready event when its ready.

Type:
  • Boolean

(readonly) transport :Object

Source:

The object that is used for serial communication. This object must adhere to the serialport module interface. Typically, it is one of: serialport, browser-serialport or virtual-serialport

Type:
  • Object

userData :Object

Source:

This is a an empty object inside which user's of this library are invited to add whatever property they might find useful.

Type:
  • Object

Methods

abort(callbackopt) → {Plotter}

Source:

Immediately abort any ongoing and upcoming plotting instructions. This empties the queue of any pending instructions.

Parameters:
Name Type Attributes Description
callback function <optional>

A function to execute once the abort command has been sent to the device.

Returns:
Type
Plotter

connect(transport, optionsopt, callbackopt) → {Plotter}

Source:

Opens a serial connection to the device using the specified serial transport layer. The following serial modules are supported: serialport and browser-serialport.

Important: calling connect() will terminate any ongoing file capture. If you want to both plot and save to file at the same time, call startCapturingToFile() only after the plotter is ready.

Parameters:
Name Type Attributes Default Description
transport Object

A transport object compatible with the serialport API interface. Typically, it is one of: serialport, browser-serialport or virtual-serialport.

options Object <optional>
{}

Options to use while setting up the device.

Properties
Name Type Attributes Default Description
paper string <optional>
"A"

The paper size to use. Choices are:

  • A: ANSI A (8.5"x11", a.k.a "letter")
  • B: ANSI B (11"x17", a.k.a "tabloid")
  • A4: ISO A4 (210mm × 297mm)
  • A3: ISO A3 (297mm × 420mm)
orientation string <optional>
"landscape"

The orientation of the paper: landscape or portrait.

penThickness number <optional>
0.3

The drawing pen's thickness in millimiters (between 0.1mm and 5mm).

callback function <optional>
null

A function to trigger when the connect operation has completed. This function will receive an error parameter if an error occured.

Fires:
Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

destroy(callback)

Source:

Disconnects from the hardware device. This will cancel ongoing and upcoming plotting instructions and close the serial connection. The device will be returned to its default state.

Parameters:
Name Type Description
callback function

A function to execute once the disconnection is complete. If an error occurs, this function will receive an error object as its parameter.

disconnect(callback)

Source:

Disconnects from the hardware device. This will cancel ongoing and upcoming plotting instructions and close the serial connection. The device will be returned to its default state.

Parameters:
Name Type Description
callback function

A function to execute once the disconnection is complete. If an error occurs, this function will receive an error object as its parameter.

drawCircle(radiusopt, angleopt, optionsopt, callbackopt) → {Plotter}

Source:

Draws a circle whose center is at the current location of the pen.

Parameters:
Name Type Attributes Default Description
radius number <optional>
1

The circle's radius (in centimeters).

angle number <optional>
5

An integer between -180° and 180° representing the chord angle. The most commonly used values are 0-180. In this case, the smaller the angle is, the smoother the circle will be. Negative values make the circle start at 180° instead of 0°.

options Object <optional>
{}

Additional options (none for now)

callback function <optional>

A function to execute when the instruction has been sent to the device.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

drawLine(x, y, optionsopt, callbackopt) → {Plotter}

Source:

Draws a line from the current pen position to the specified destination position (x, y).

Parameters:
Name Type Attributes Default Description
x number

The x coordinate of the point where the the line should end (in cm).

y number

The y coordinate of the point where the the line should end (in cm).

options Object <optional>
{}

Additional options

Properties
Name Type Attributes Default Description
linePattern number <optional>
7

Integer between 0 and 7. Value 0 prints dots at line extremities only. Values 1 to 6 prints various types of dotted lines. Value 7 (default) is a solid line.

penUp number <optional>
true

Whether the pen should be lifted off the paper at the end of the line.

penDown number <optional>
true

Whether the pen should be lowered on the paper before starting to draw a line;

callback function <optional>

A function to execute when the instruction has been sent to the device.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

drawLines(positionsopt, optionsopt, callbackopt) → {Plotter}

Source:
To Do:
  • add linePatternLength option

Draws a series of lines starting at the current pen position and going, in turn, to all x/y pairs specified in the array.

Parameters:
Name Type Attributes Default Description
positions Array.<number> <optional>
[]

An array of line-end positions in the form [x1, y1, x2, y2, ...].

options Object <optional>
{}

Additional options

Properties
Name Type Attributes Default Description
linePattern number <optional>
7

Integer between 0 and 7. Value 0 only prints dots at line extremities only. Values 1 to 6 prints various types of dotted lines. Value 7 (default) is a solid line.

penUp number <optional>
true

Whether the pen should be lifted off the paper after drawing all the lines.

penDown number <optional>
true

Whether the pen should be lowered on the paper before drawing all the lines.

callback function <optional>

A function to execute when all the instruction(s) have been sent to the device.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

drawRectangle(width, heightopt, optionsopt, callbackopt) → {Plotter}

Source:
To Do:
  • Add 'fill' option with RR and FT

Draws a rectangle with the specified width and height starting at the current pen position. When drawing is done, the pen is returned to the starting point.

If no height is specified, the height will be equal to the width, thus drawing a square.

Parameters:
Name Type Attributes Default Description
width number

The width of the rectangle (in cm).

height number <optional>

The height of the rectangle (in cm).

options Object <optional>
{}

Additional options (none for now)

callback function <optional>

A function to execute when the instruction has been sent to the device.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

drawText(text, optionsopt, callbackopt) → {Plotter}

Source:
To Do:
  • text direction (double check with orientation)
  • Add missing characters

Draws the specified text at the current pen position. The reference point is at the text's bottom left.

Currently, all of the ANSI/ASCII characters are supported as well as most of the characters in the Roman Extensions character set (Set 7) which covers most european languages. I'm still missing some characters because I'm not sure what they are...

Parameters:
Name Type Attributes Default Description
text string

A UTF-8 string to plot.

options Object <optional>
{}

Options to control how the text is drawn.

Properties
Name Type Attributes Default Description
characterWidth number <optional>
0.187

The width, in centimeters, of a single character of text. A negative value mirrors the text for that dimension.

characterHeight number <optional>
0.269

The height, in centimeters, of a single character of text. A negative value mirrors the text for that dimension.

rotation number <optional>
0

The counter-clockwise rotation to apply to the text (in degrees).

scale number <optional>
0

The scale factor used to size the characters. For example, a scale value of 2.0 doubles the character size while a scale of 0.5 makes it half as big. Scaling is applied after the characterWidth and characterHeight parameters are applied (if any). A negative value mirrors the character across both dimensions.

slant number <optional>
0

The slant (italic) with which characters are lettered (in degrees). A typical range of values is between -45° and +45°.

callback function <optional>

A function to execute when the instruction has been sent to the device.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

getMargins(metric) → {Object}

Source:

Returns an object with top, right, bottom and left properties each containing the size of the corresponding margin. The device model, the paper size and the paper orientation must have been defined before calling this function, otherwise the function will return undefined.

Parameters:
Name Type Description
metric Boolean

Whether the margin values should be returned in cm (default) or decimal inches.

Returns:

An object with top, right, bottom and left properties.

Type
Object

getModel(callback)

Source:

Retrieves the model from the device using RS-232-C or HP-GL (depending on the model).

Parameters:
Name Type Description
callback

A function to trigger once the model has been fetched. This function receives a string containing the model name.

getPaperSize(metric) → {Object}

Source:

Returns the dimensions of the currently selected paper size. The values returned (width and height) take into account the current paper orientation.

Parameters:
Name Type Description
metric Boolean

A boolean value indicating whether the dimensions should be output in cm (true) or inches (false).

Returns:

An object with width and height properties.

Type
Object

getPlottableArea(metricopt) → {Rectangle}

Source:

Returns the plottable area for the current paper and orientation.

Parameters:
Name Type Attributes Default Description
metric Boolean <optional>
true

Whether to use metric (cm, default) or imperial values (inches).

Returns:

A Rectangle object which contains information about the width, the height and the position (x, y) of the plottable area.

Type
Rectangle

getRs232Error(callback) → {Plotter}

Source:

Retrieves any RS-232-C errors that might have occured and passes it to the specified callback function.

Parameters:
Name Type Description
callback function

A function to call once the error has been obtained from the device. This function receives an object with various properties which are detailed below.

Properties
Name Type Description
code Boolean

The error code.

message Boolean

The error message.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

getStatus(callback) → {Plotter}

Source:

Fetches status information about the device. Once retrieved, the status information is packaged in an object that is passed to the specified callback.

The status request is not queued. It is being answered by the device in an immediate fashion. It still takes a little while but does not wait for previous drawing instructions to complete. It does not affect drawing in any way.

Parameters:
Name Type Description
callback function

A function to call once the status data has been obtained from the device. This function receives an object with various properties which are detailed below.

Properties
Name Type Description
rollPaper Boolean

Whether roll paper or sheet paper is being used.

cleanPaper Boolean

Whether the paper is "clean" (set after being sensed). The paper is considered to not be clean if:

  • No paper is loaded or advanced
  • The pen has touched the paper
  • No paper was sensed before or after paper advance (end of roll)
paperAdvance Boolean

Whether a paper advance instruction has been received since the last time the status was retrieved.

bufferEmpty Boolean

Whether the buffer is currently empty or not.

ready Boolean

Whether the device is ready to receive instructions or not.

viewEngaged Boolean

Whether "view" mode is currently engaged.

coverOpen Boolean

Whether the cover is currently open.

emulateMode Boolean

Whether the device is in emulate or normal mode.

expandMode Boolean

Whether expand mode is activated or not.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

initialize(optionsopt, callbackopt)

Source:

Reset the device to its 'power on' status using the IN instruction (same as DF plus: pen is raised, errors are cleared, rotation set to 0, scaling points reset). This function can also configure the plotting environments according to the options parameter. This operation is asynchronous.

Note: a call to this function is automatically performed when calling connect().

Parameters:
Name Type Attributes Default Description
options Object <optional>
{}

Options to use while setting up the device.

Properties
Name Type Attributes Default Description
paper string <optional>
"A"

The paper size to use. Choices are:

  • A: ANSI A (8.5"x11", a.k.a "letter")
  • B: ANSI B (11"x17", a.k.a "tabloid")
  • A4: ISO A4 (210mm × 297mm)
  • A3: ISO A3 (297mm × 420mm)
orientation string <optional>
"landscape"

The orientation of the paper: landscape or portrait.

penThickness number <optional>
0.3

The drawing pen's thickness in millimiters (between 0.1mm and 5mm).

callback function <optional>

A function to call once the device has been initialized. In case of error, the function will receive an Error object

moveTo(x, y, metric) → {Plotter}

Source:

Lifts the pen and moves it to the specified x and y coordinates.

Parameters:
Name Type Description
x number

Position along the x axis

y number

Position along the y axis

metric Boolean

Whether the coordinates are in centimeters (default) or decimal inches.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

plotFile(file, callbackopt)

Source:

Loads an HPGL file and sends all instructions found inside it to the plotter. The pen thickness, paper size and orientation defined in the file have precedence over the same properties defined during connection with the connect() function (if any).

The format for the instructions must be the HP-recommended syntax. That is:

  • Two-letter uppercase mnemonic
  • Optionnally followed by comma-separated parameters
  • Followed by a semicolon (or the CTX character, in the case of the LB instruction)

Newline (\n) characters may be used after the semicolons for readability. No other format is supported. Also note that all HPGL output instructions (those starting with "O") will be discarded. The file cannot include RS-232-C escape sequences.

Example

Note that the plotFile() function must be called after the device is ready:

plotter
  .on("ready", function() {
    this.plotFile("test.hpgl");
  })
  .on("fileplotted", function() {
    console.log("Done plotting!");
  })
  .connect(transport);
Parameters:
Name Type Attributes Description
file String

The path to the file that will be sent to the plotter.

callback Plotter~statusCallback <optional>

A function to execute when all the instructions have been sent to the plotter's buffer. Depending on the size of the file and of the device's buffer, this may take a while.

Fires:

queue(instruction, callbackopt, optionsopt) → {Plotter}

Source:

Queues a single HPGL instruction, a series of HPGL instructions concatenated in a string or a single RS-232-C device control command. The instructions will be sent as soon as the device's buffer can accept them.

Unless you are very familiar with HPGL or RS-232-C, you should not use this method directly. Instead, you can use friendlier methods such as: drawLines(), drawText(), drawCircle(), etc.

Parameters:
Name Type Attributes Default Description
instruction string

Any valid HPGL instruction(s) or RS-232-C command.

callback function <optional>
null

A function to call once the data has been sent to the device (default) or when an answer has been received from the device (when waitForResponse is true). Note that if waitForResponse is true, the callback function will receive a single parameter containing the data received from the device. Also note that if the instruction string contains multiple commands, the callback will be fired after each command.

options Object <optional>
Object

Additional options

Properties
Name Type Attributes Default Description
waitForResponse Boolean <optional>
false

Whether to execute the callback function after the data has been sent or only after an answer has been received from the device.

executeCallbackOnAbort Boolean <optional>
false

Whether the specified callback (if any) should be executed or simply ignored when Plotter.abort() is called.

ignoreOutputInstructions Boolean <optional>
false

Whether to ignore HPGL output instructions (instructions starting with "O"). This is useful when plotting a whole file.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

selectPen(penNumberopt, callbackopt) → {Plotter}

Source:

Selects the requested pen from the carousel or stall. If no pen is specified, selects the pen at position 1. If the pen designated for selection is not in its stall, the plotter will attempt to select a pen beginning in stall 1 and move up until a pen is found.

Specifying a pen number of 0, stores the current pen. This is the equivalent of calling storePen().

If the plotter does not have a carousel/stall or the specified pen number is out of range, this instruction is ignored.

Parameters:
Name Type Attributes Default Description
penNumber Number <optional>
1

The number of the pen to select.

callback function <optional>

A function to execute when the instruction has been sent to the device.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

send(instruction, callbackopt, waitForResponseopt) → {Plotter}

Source:

Immediately sends a single raw HPGL or RS-232-C instruction down the serial port. The validity of the instruction's syntax is not checked at all. If you need validation, use the queue() function.

Unless you are very familiar with HPGL, this method should not be used directly. Instead, you can use friendlier methods such as: drawLines(), drawText(), drawCircle(), etc.

Note: only instructions supported by the target device will be transmitted. Unsupported instructions will be silently ignored and the callback will not be executed.

Parameters:
Name Type Attributes Default Description
instruction string

The raw instruction to send (unterminated).

callback function <optional>
null

A function to call once the data has been sent to the device (default) or when an answer has been received from the device. If waitForResponse is true, the callback function will receive a single parameter containing the data received from the device.

waitForResponse boolean <optional>
false

Whether to execute the callback function immediately after the data has been sent or only after an answer has been received from the device.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

setVelocity(velocityopt) → {Plotter}

Source:

Sets the velocity of the plotting pen. When the velocity parameter is set to 1, the velocity will be at its maximum of 38.1cm/s (default). So, if you set the velocity parameter to 0.1, the actual velocity will be 3.81cm/s.

Any value equal or lower than 0 and any value above 1 will trigger the use of the default velocity.

Parameters:
Name Type Attributes Default Description
velocity number <optional>
1.0

A decimal number between 0 and 1.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

startCapturingToFile(pathopt, optionsopt) → {Plotter}

Source:

Starts appending all sent HPGL commands to the specified file. Unless a device has been previously connected, it is necessary to specify the device model, the paper size and the orientation in the options object.

If you want to both plot and save at the same time, you must wait for the device to be ready before calling the startCapturingToFile() function:

plotter
  .on("ready", function() {
    this.startCapturingToFile("test.hpgl");
  })

  .on("error", function (err) {
    console.log(err);
  })
  .connect(transport);
Parameters:
Name Type Attributes Default Description
path String <optional>
"job.hpgl"

The path of the file to append to.

options Object <optional>

Options affecting how the commands are captured to file.

Properties
Name Type Attributes Default Description
model String <optional>
"GENERIC"

The target device's model.

orientation String <optional>
"landscape"

The orientation of the paper: landscape or portrait.

paper String <optional>
"A"

The targeted paper size. Choices vary depending on the device. Typical choices are:

  • A: ANSI A (8.5"x11", a.k.a "letter")
  • B: ANSI B (11"x17", a.k.a "tabloid")
  • A4: ISO A4 (210mm × 297mm)
  • A3: ISO A3 (297mm × 420mm)
Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

stopCapturingToFile() → {Plotter}

Source:

Stops hpgl commands from being saved to file.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

storePen(callbackopt) → {Plotter}

Source:

Stores the pen back in the carousel or stall. The plotter will try to put the pen away in the appropriate stall. If the stall is occupied, the plotter will attempt to store the pen in pen stall 1, then 2, then 3, etc. If all the stalls are full, the pen holder will return to its previous location.

If the plotter does not support pen storage, this instruction is ignored.

Parameters:
Name Type Attributes Description
callback function <optional>

A function to execute when the instruction has been sent to the device.

Returns:

Returns the Plotter object to allow method chaining.

Type
Plotter

utf8toHpgl(text) → {string}

Source:

Converts all characters in the UTF-8 input string to equivalent HPGL instruction(s). The function will switch character set as needed in an attempt to reproduce as many characters as possible.

If a character is not found, it will be drawn as is using Set 0 (ANSI/ASCII).

Parameters:
Name Type Description
text string

A UTF-8 formatted string

Returns:

The resulting HPGL instruction(s)

Type
string

wait(callback)

Source:

Waits for the device to finish processing and/or drawing all previously queued instructions and then executes the specified callback function.

Parameters:
Name Type Description
callback Plotter~statusCallback

The function to execute.

Type Definitions

statusCallback(status)

Source:

Defines the expected signature of functions used in a statusCallback context. Such functions basically receive a status object detailing the current status of the hardware device.

Parameters:
Name Type Description
status Object

Hardware status information

Properties
Name Type Description
x Number

Position of the pen of the x axis (in plotter units)

y Number

Position of the pen of the y axis (in plotter units)

penDown Boolean

Whether the pen is down or not

Events

abort

Source:

Event emitted when the current job is aborted.

connected

Source:

Event emitted when the serial connection has been successfully closed.

data

Source:

Event emitted when data is received from the device.

Parameters:
Name Type Description
data string

The data received.

error

Source:

Event emitted when an error occurs. The specified function will receive an object with information about the error.

Parameters:
Name Type Description
error Object

object containing details about the error

fileaborted

Source:

Event emitted when the attempt to plot a file failed.

Parameters:
Name Type Description
err Error

The error that occured

fileplotted

Source:

Event emitted when a file has been completely drawn by the device.

Parameters:
Name Type Description
status Object

Additional information

Properties
Name Type Description
x Object

The ending x position of the pen (in cm).

y Object

The ending y position of the pen (in cm).

penDown Boolean

Whether the pen is down or not.

ready

Source:

Event emitted when the device is ready to receive plotting instructions.