Skip to main content
AdvancedRaw protocol access

When Camera has no method for what you need (a vendor command, a property Darkgrade Slate doesn't name, a look at what the camera really sends), talk PTP to it directly. protocolSession(camera) gives you the session the Camera already holds.

import { Camera } from '@darkgrade/slate'
import {
    genericOperationRegistry as operations,
    protocolSession,
} from '@darkgrade/slate/protocol'

const camera = new Camera()
await camera.connect()

const session = protocolSession(camera)
const reply = await session.send(operations.GetDeviceInfo, {})
console.log(reply.code.toString(16), reply.data.model)
// '2001' 'ILCE-6700'

@darkgrade/slate/protocol is unsupported. Its names follow each vendor's own protocol and can change between releases. Nothing here is confirmed the way Camera operations are: a write that returns did not necessarily take effect. Build applications on Camera, and keep this entry for diagnostics and experiments.

The session

protocolSession(camera) returns the same object on every call for a given Camera, and throws a TypeError for anything else. It opens nothing: it uses the camera's connection and driver, so camera.connect() comes first and camera.disconnect() ends both.

MemberWhat it is
vendorIdThe connected camera's USB vendor id, or null. Compare with VendorIDs.
sessionIdThe open PTP session's id, or null when closed.
registryThe connected camera's own operations, properties, events and responses: the standard definitions plus its vendor's.
driverThe vendor driver serving the camera now. Internal: its methods are not documented and change freely.

A raw command shares the cable with Camera's own commands but not its queue. Don't send one while a Camera operation is in flight on the same camera.

Send an operation

session.send(operation, params, data?, maxDataLength?)
    : Promise<{ code, parameters?, data? }>

operation is a definition from a registry, and params is typed from it. data is the bytes to send when the camera receives a data phase, and maxDataLength caps what it may send back: 256 KiB unless you raise it, as a file download must. The response has the PTP response code (0x2001 is OK; the rest are in response codes) and data, decoded when the operation defines a dataset and raw bytes otherwise.

const storage = await session.send(operations.GetStorageIDs, {})
if (storage.code !== 0x2001) {
    throw new Error(`Camera answered 0x${storage.code.toString(16)}`)
}
console.log(storage.data)

A response code other than OK is returned, not thrown: check code. Transport failures throw the protocol errors.

To use the connected camera's vendor operations without importing a vendor table, read them from session.registry.operations.

Read and write properties

import {
    genericPropertyRegistry as properties,
    protocolSession,
} from '@darkgrade/slate/protocol'

const session = protocolSession(camera)

const whiteBalance = await session.get(properties.WhiteBalance)
await session.set(properties.WhiteBalance, whiteBalance)
MethodDoes
get(property)Reads the property and decodes it with the definition's codec.
readValue(property)Reads with GetDevicePropValue only. It does not look up the camera's descriptor, so it misreads a body that uses a different data type for the property.
set(property, value)Writes the property. The compiler refuses a read-only definition. The write is not read back.
getStandardPropertyStates()Every standard property the camera advertises, with code, name, value, rawValue, writable, form ('none', 'range' or 'enum') and its allowed values or range.
setStandardProperty(nameOrCode, value)Writes a standard property by its name or numeric code. Refuses a property the camera doesn't advertise, a read-only one, and a value missing from its list of allowed values.

The property tables are in the PTP reference: standard, Canon, Sony and Nikon.

To change a setting, prefer setControl or a typed setter. They check the value against what the camera offers and read it back; session.set does neither.

Listen to raw events

import {
    genericEventRegistry as events,
    protocolSession,
} from '@darkgrade/slate/protocol'

const session = protocolSession(camera)
const added = (params: unknown) => console.log('ObjectAdded', params)

session.on(events.ObjectAdded, added)
session.off(events.ObjectAdded, added)
session.off(events.ObjectAdded) // every handler of the event

Handlers receive the event's decoded parameters. A handler added before connect() is kept when the camera connects; disconnect() drops it. For the two events that mean the same on every brand, use camera.on.

Vendor diagnostics

These read a vendor's own state. Each throws CameraUnsupportedError on another vendor's camera.

VendorMethods
SonygetSonyPropertyStates(), sonyPressButton(button, options?), connectSonyMenuSession(device?)
CanongetCanonPropertyStates(), getCanonUnknownPropertyStates(), getCanonExtendedDeviceInfo(), getCanonNetworkState(), setCanonNetworkCommunicationMode(value, allowUnadvertised?), setCanonLiveViewZoom(magnification), getCanonLiveViewPosition(), setCanonLiveViewPosition(x, y), panCanonLiveView(direction, step?), captureCanonViewfinderFrame(), keepDeviceOn()
NikongetNikonVendorPropertyCodes()

sonyPressButton takes a key of SONY_CAMERA_BUTTONS ('up', 'down', 'left', 'right', 'enter', 'menu' and more) and { action: 'click' | 'press' | 'release', holdMilliseconds }. Canon live-view magnification is 1, 5, 6, 10 or 15.

What else the entry exports

GroupWhat's in it
RegistriesThe tables behind the PTP reference: genericOperationRegistry, genericPropertyRegistry, genericEventRegistry, responseRegistry, formatRegistry, the Sony registries (sonyOperationRegistry, sonyPropertyRegistry, sonyEventRegistry, sonyResponseRegistry, sonyFormatRegistry), nikonOperationRegistry, VendorIDs and getDatatypeByCode. Canon's tables are not exported: read them from session.registry.
TransportsIPTransport, USBTransport, TransportFactory and TransportType. IPTransport is how you connect over Wi-Fi with PTP/IP.
TypesThe operation, property, event, response, codec, datatype and parameter types, and the DeviceInfo, ObjectInfo and StorageInfo datasets, for typing what send and get return. See Types.
DriversGenericCamera, CanonCamera, NikonCamera, SonyCamera and VendorExtensionCamera: the internal classes behind Camera. Use Camera.
Vendor helpersSony and Nikon recording, card, menu and accessory helpers that Camera's own operations are absorbing. Expect them to go.
Wireless pairingSony Wi-Fi and its SDK bridge, Nikon Wi-Fi pairing and discovery, and the Sony and Nikon Bluetooth remotes, kept here until they become Camera.connect options. Expect them to move.

The Entry points reference lists every export of this entry.

Record a connection

recordFullTransport wraps a transport before you construct the Camera and hands every send, receive and event to a write callback, for debugging a camera you can't reproduce a problem on.

import { Camera } from '@darkgrade/slate'
import {
    IPTransport,
    recordFullTransport,
    VendorIDs,
    type TransportRecordingEntry,
} from '@darkgrade/slate/protocol'

const entries: TransportRecordingEntry[] = []
const network = new IPTransport({ address: '192.168.1.1' })
const recording = recordFullTransport(network, {
    write: async entry => {
        entries.push(entry) // persist it before resolving
    },
})

const camera = new Camera({
    transport: recording.transport,
    vendorId: VendorIDs.CANON,
})
try {
    await camera.connect()
    await camera.getInfo()
} finally {
    await camera.disconnect()
}
// Only after disconnect() has settled.
const status = await recording.finish()
console.log(status.complete, status.entries, status.droppedEntries)

Each entry has a sequence, a kind ('connect', 'disconnect', 'reset', 'send', 'receive' or 'event'), start and finish times in milliseconds since the recording began, and for sends and receives the full bytes at the transport boundary. The recording stops accepting entries at 100,000 entries or 512 MiB unless you set maximumEntries and maximumTotalBytes. A failed write or a full recording makes status.complete false and sets status.error; it never fails the camera operation. finish() throws if a camera operation is still running.

A recording holds every byte that crossed the connection, including image data. Treat the file accordingly.

⌘I