Table of Contents

Class USB

Namespace
DuetControlServer.Link.Adapter
Assembly
DuetControlServer.dll

Class to handle the USB link to the firmware over ttyACM

[DiagnosticsPriority(-4)]
public class USB : IDiagnostics, ILinkAdapter
Inheritance
USB
Implements
Inherited Members

Constructors

Constructor of this class

public USB(EventLogger eventLogger, ObjectModel model, ILogger<USB> logger, IOptions<Settings> settings)

Parameters

eventLogger EventLogger

Event logger

model ObjectModel

Object model

logger ILogger<USB>

Logger instance

settings IOptions<Settings>

Settings

Exceptions

OperationCanceledException

Failed to connect to board

Properties

Returns the number of packets to read

public int PacketsToRead { get; }

Property Value

int

Currently-used protocol version

public int ProtocolVersion { get; }

Property Value

int

Methods

Attempt to connect to the firmware by sending M576.1 and parsing the init response

public void Connect(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

Optional cancellation token

Write the last packet + content for diagnostic purposes

public void DumpMalformedPacket()

Flash another segment of the firmware via the IAP binary. The IAP sends a 0x1A ready byte before each block.

public bool FlashFirmwareSegment(Stream stream)

Parameters

stream Stream

Stream of the firmware binary

Returns

bool

Whether another segment could be sent

Get the maximum time between two full transfers

public double GetMaxFullTransferDelay()

Returns

double

Time in ms

Check if the controller has been reset or disconnected. Unlike SPI (which uses sequence numbers), USB detects this via communication failure.

public bool HadReset()

Returns

bool

Whether the controller has been reset

Perform a full data transfer synchronously

public void PerformFullTransfer(bool connecting = false, CancellationToken cancellationToken = default)

Parameters

connecting bool

Whether this an initial connection is being established

cancellationToken CancellationToken

Cancellation token to cancel the transfer

Print diagnostics to the given string builder

public void PrintDiagnostics(StringBuilder builder)

Parameters

builder StringBuilder

Target to write to

Read the content of an AbortFileHeader packet

public void ReadAbortFile(out CodeChannel channel, out bool abortAll)

Parameters

channel CodeChannel

Code channel where all files are supposed to be aborted

abortAll bool

Whether all files are supposed to be aborted

Read a request to check if a file exists

public void ReadCheckFileExists(out string filename)

Parameters

filename string

Name of the file

Read a request to close a file

public void ReadCloseFile(out uint handle)

Parameters

handle uint

File handle

Read a code buffer update

public void ReadCodeBufferUpdate(out ushort bufferSpace)

Parameters

bufferSpace ushort

Buffer space

Read a code channel

public void ReadCodeChannel(out CodeChannel channel)

Parameters

channel CodeChannel

Code channel that has acquired the lock

Read a request to delete a file or directory

public void ReadDeleteFileOrDirectory(out string filename)

Parameters

filename string

Name of the file

Read a code request

public void ReadDoCode(out CodeChannel channel, out string code)

Parameters

channel CodeChannel

Channel to execute this code on

code string

Code to execute

Read the result of an expression evaluation request

public void ReadEvaluationResult(out CodeChannel? channel, out string expression, out object? result)

Parameters

channel CodeChannel?

Channel where the evaluation was performed

expression string

Evaluated expression

result object

Result

Read a chunk of a FileChunk packet

public void ReadFileChunkRequest(out string filename, out uint offset, out int maxLength)

Parameters

filename string

Filename

offset uint

File offset

maxLength int

Maximum chunk size

Read a request to read data from a file

public void ReadFileRequest(out uint handle, out int maxLength)

Parameters

handle uint

File handle

maxLength int

Maximum data length

Read the content of a ExecuteMacroHeader packet

public void ReadMacroRequest(out CodeChannel channel, out bool isSystemMacro, out string filename)

Parameters

channel CodeChannel

Channel requesting a macro file

isSystemMacro bool

Indicates if this code is not bound to a code being executed (e.g. when a trigger macro is requested)

filename string

Filename of the requested macro

Read an incoming message

public void ReadMessage(out MessageTypeFlags messageType, out string reply)

Parameters

messageType MessageTypeFlags

Message type flags of the reply

reply string

Code reply

Read the next packet

public PacketHeader? ReadNextPacket()

Returns

PacketHeader?

The next packet or null if none is available

Read the result of a GetObjectModel request

public void ReadObjectModel(out ReadOnlySpan<byte> json)

Parameters

json ReadOnlySpan<byte>

JSON data

Read an open file request

public void ReadOpenFile(out string filename, out bool forWriting, out bool append, out long preAllocSize)

Parameters

filename string

Filename to open

forWriting bool

Whether the file is supposed to be written to

append bool

Whether data is supposed to be appended in write mode

preAllocSize long

How many bytes to allocate if the file is created or overwritten

Read the content of a PrintPausedHeader packet

public void ReadPrintPaused(out uint filePosition, out uint filePosition2, out PrintPausedReason reason)

Parameters

filePosition uint

Position where the print has been paused

filePosition2 uint

Position where the second open file has been paused (if applicable)

reason PrintPausedReason

Reason why the print has been paused

Read a request to seek in a file

public void ReadSeekFile(out uint handle, out long offset)

Parameters

handle uint

File handle

offset long

New file position

Read a request to truncate a file

public void ReadTruncateFile(out uint handle)

Parameters

handle uint

File handle

Read a request to write data to a file

public void ReadWriteRequest(out uint handle, out ReadOnlySpan<byte> data)

Parameters

handle uint

File handle

data ReadOnlySpan<byte>

Data to write

Resend a packet back to the firmware

public void ResendPacket(PacketHeader packet, out Request sbcRequest)

Parameters

packet PacketHeader

Packet holding the resend request

sbcRequest Request

Content of the packet to resend

Instruct the firmware to start the IAP binary

public void StartIap(uint firmwareLength, CancellationToken cancellationToken = default)

Parameters

firmwareLength uint

Length of the firmware binary in bytes; sent to IAP as part of the USB handshake

cancellationToken CancellationToken

Optional cancellation token

Send the CRC16 checksum of the firmware binary to the IAP program and verify the written data. Uses timing-based end-of-transfer detection (matching SPI IAP protocol).

public bool VerifyFirmwareChecksum(long firmwareLength, ushort crc16)

Parameters

firmwareLength long

Length of the written firmware in bytes

crc16 ushort

CRC16 checksum of the firmware

Returns

bool

Whether the firmware has been written successfully

Wait for the IAP program to reset the controller. Close the IAP serial port and flag for reconnection to the main firmware.

public void WaitForIapReset()

Send back whether a file exists or not

public bool WriteCheckFileExistsResult(bool exists)

Parameters

exists bool

Whether the file exists

Returns

bool

If the packet could be written

Request a code to be executed

public bool WriteCode(Code code)

Parameters

code Code

Code to send

Returns

bool

True if the packet could be written

Delete a local variable at the end of the current code block

public bool WriteDeleteLocalVariable(CodeChannel channel, string varName)

Parameters

channel CodeChannel

G-code channel

varName string

Name of the variable excluding var prefix

Returns

bool

True if the packet could be written

Request an emergency stop

public bool WriteEmergencyStop()

Returns

bool

True if the packet could be written

Write a request for an expression evaluation

public bool WriteEvaluateExpression(CodeChannel channel, string expression)

Parameters

channel CodeChannel

Where to evaluate the expression

expression string

Expression to evaluate

Returns

bool

Whether the evaluation request has been written successfully

Write another chunk of the file being requested

public bool WriteFileChunk(Span<byte> data, long fileLength)

Parameters

data Span<byte>

File chunk data

fileLength long

Total length of the file in bytes

Returns

bool

Whether the firmware has been written successfully

Send back whether a file or directory could be deleted

public bool WriteFileDeleteResult(bool success)

Parameters

success bool

Whether the file operation was successful

Returns

bool

If the packet could be written

Write requested read data from a file

public bool WriteFileReadResult(Span<byte> data, int bytesRead)

Parameters

data Span<byte>

File data

bytesRead int

Number of bytes read or negative on error

Returns

bool

If the packet could be written

Tell RRF if the seek operation was successful

public bool WriteFileSeekResult(bool success)

Parameters

success bool

If the seek operation succeeded

Returns

bool

If the packet could be written

Tell RRF if the seek operation was successful

public bool WriteFileTruncateResult(bool success)

Parameters

success bool

If the seek operation succeeded

Returns

bool

If the packet could be written

Tell RRF if the last file block could be written

public bool WriteFileWriteResult(bool success)

Parameters

success bool

If the file data could be written

Returns

bool

If the packet could be written

Request the key of a object module of a specific module

public bool WriteGetObjectModel(string key, string flags)

Parameters

key string

Object model key to query

flags string

Object model flags to query

Returns

bool

True if the packet could be written

Write another segment of the IAP binary

public bool WriteIapSegment(Stream stream, CancellationToken cancellationToken = default)

Parameters

stream Stream

IAP binary

cancellationToken CancellationToken

Optional cancellation token

Returns

bool

Whether another segment could be written

Called when a code channel is supposed to be invalidated (e.g. via abort keyword)

public bool WriteInvalidateChannel(CodeChannel channel)

Parameters

channel CodeChannel

Code channel that requires the lock

Returns

bool

True if the packet could be written

Request the movement systems to be locked and wait for standstill

public bool WriteLockAllMovementSystemsAndWaitForStandstill(CodeChannel channel)

Parameters

channel CodeChannel

Code channel that requires the lock

Returns

bool

True if the packet could be written

Notify the firmware about a completed macro file. This function is only used for macro files that the firmware requested

public bool WriteMacroCompleted(CodeChannel channel, bool error)

Parameters

channel CodeChannel

Code channel of the finished macro

error bool

Whether an error occurred

Returns

bool

True if the packet could be written

Notify RepRapFirmware that a macro file could be started

public bool WriteMacroStarted(CodeChannel channel)

Parameters

channel CodeChannel

Code channel that requires the lock

Returns

bool

True if the packet could be written

Write a message

public bool WriteMessage(MessageTypeFlags flags, string message)

Parameters

flags MessageTypeFlags

Message flags

message string

Message content

Returns

bool

Whether the firmware has been written successfully

Notify RRF that an object model key has changed

public bool WriteObjectModelKeyChanged(string key)

Parameters

key string

Key that has changed

Returns

bool

If the packet could be written

Write the new file handle and file length of the file that has just been opened

public bool WriteOpenFileResult(uint fileHandle, long length)

Parameters

fileHandle uint

New file handle or noFileHandle if the file could not be opened

length long

Length of the file

Returns

bool

If the packet could be written

Notify the firmware that a file print has started

public bool WritePrintFileInfo(GCodeFileInfo info)

Parameters

info GCodeFileInfo

Information about the file being printed

Returns

bool

True if the packet could be written

Notify that a file print has been stopped

public bool WritePrintStopped(PrintStoppedReason reason)

Parameters

reason PrintStoppedReason

Reason why the print has been stopped

Returns

bool

True if the packet could be written

Request a firmware reset

public bool WriteReset()

Returns

bool

True if the packet could be written

Write the last code result for a specific code channel

public bool WriteSetLastCodeResult(CodeChannel channel, CodeResult result)

Parameters

channel CodeChannel

Code channel

result CodeResult

Last code result

Returns

bool

If the packet could be written

Set a global or local variable

public bool WriteSetVariable(CodeChannel channel, bool createVariable, string varName, string expression)

Parameters

channel CodeChannel

G-code channel

createVariable bool

Whether the variable should be created or updated

varName string

Name of the variable including global or var prefix

expression string

New value of the variable

Returns

bool

True if the packet could be written

Release all acquired locks again

public bool WriteUnlock(CodeChannel channel)

Parameters

channel CodeChannel

Code channel that releases the locks

Returns

bool

True if the packet could be written