diff --git a/README.md b/README.md index 76273b0bf..6ee2466a1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,19 @@ -# JACDAC +# JACDAC Services for MakeCode + +This project contains [JACDAC](https://aka.ms/jacdac) host and client services for MakeCode editors. + +**This project is still under construction.** + +## Using this extensions + +* Open your MakeCode editor (see supported editors) +* Go to the extension dialog and search for https://github.com/microsoft/pxt-jacdac-services +* Import the extension. + +### Supported editors + +* Maker, https://maker.makecode.com +* Arcade BETA, https://arcade.makecoe.com/beta ## Contributing diff --git a/accelerometerclient.ts b/accelerometerclient.ts index dbcd2a711..f129db2d6 100644 --- a/accelerometerclient.ts +++ b/accelerometerclient.ts @@ -73,13 +73,9 @@ namespace jacdac { */ //% blockId=jacadacacconevent block="jacdac %accelerometer on %gesture" //% group="Accelerometer" - onEvent(gesture: JDGesture, handler: () => void) { + onEvent(gesture: AccelEvent, handler: () => void) { this.registerEvent(gesture, handler); } - - onCustomGesture(id: number, handler: () => void) { - this.registerEvent(JDGesture.Shake + id, handler); - } } //% fixedInstance whenUsed block="accelerometer client" diff --git a/actuator.ts b/actuator.ts index f2875bd39..37dc262fb 100644 --- a/actuator.ts +++ b/actuator.ts @@ -12,8 +12,8 @@ namespace jacdac { public handlePacket(packet: JDPacket) { this.stateUpdated = false - this.intensity = this.handleRegInt(packet, REG_INTENSITY, this.intensity) - this.state = this.handleRegBuffer(packet, REG_VALUE, this.state) + this.intensity = this.handleRegInt(packet, SystemReg.Intensity, this.intensity) + this.state = this.handleRegBuffer(packet, SystemReg.Value, this.state) if (this.stateUpdated) this.handleStateChanged(); @@ -45,7 +45,7 @@ namespace jacdac { } protected notifyChange() { - this.sendCommand(JDPacket.from(CMD_SET_REG | REG_VALUE, this.state)) + this.sendCommand(JDPacket.from(CMD_SET_REG | SystemReg.Value, this.state)) } } } \ No newline at end of file diff --git a/aggregator.ts b/aggregator.ts index 9c232bbb0..ac6cb0898 100644 --- a/aggregator.ts +++ b/aggregator.ts @@ -21,7 +21,7 @@ namespace jacdac { private sampleMult: number handlePacket(packet: JDPacket) { - if (packet.service_command == (CMD_GET_REG | REG_READING)) { + if (packet.service_command == (CMD_GET_REG | SystemReg.Reading)) { this.parent._newData(packet.timestamp, false) const arr = packet.data.toArray(numberFmt(this.sampleType)) for (let i = 0; i < arr.length; ++i) @@ -37,7 +37,7 @@ namespace jacdac { } announceCallback() { - this.setRegInt(REG_STREAMING_SAMPLES, 255) + this.setRegInt(SensorReg.StreamingSamples, 255) } constructor(parent: SensorAggregatorHost, config: Buffer) { @@ -169,8 +169,8 @@ namespace jacdac { let frameSz = 0 while (off < config.length) { const coll = new Collector(this, config.slice(off, entrySize)) - coll.setRegInt(REG_STREAMING_INTERVAL, this.samplingInterval) - coll.setRegInt(REG_STREAMING_SAMPLES, 255) + coll.setRegInt(SensorReg.StreamingInterval, this.samplingInterval) + coll.setRegInt(SensorReg.StreamingSamples, 255) this.collectors.push(coll) frameSz += coll.lastSample.length off += entrySize @@ -189,7 +189,6 @@ namespace jacdac { this.handleRegInt(packet, SensorAggregatorReg.NumSamples, this.numSamples) this.handleRegInt(packet, SensorAggregatorReg.SampleSize, this.sampleSize) this.streamSamples = this.handleRegInt(packet, SensorAggregatorReg.StreamSamples, this.streamSamples) - this.streamSamples = this.handleRegInt(packet, REG_STREAMING_SAMPLES, this.streamSamples) switch (packet.service_command) { case SensorAggregatorReg.Inputs | CMD_GET_REG: diff --git a/arcadecontrolsclient.ts b/arcadecontrolsclient.ts index 4968ec4c0..ef9b00a97 100644 --- a/arcadecontrolsclient.ts +++ b/arcadecontrolsclient.ts @@ -9,7 +9,7 @@ namespace jacdac { } handlePacket(pkt: JDPacket) { - if (pkt.service_command == CMD_EVENT) { + if (pkt.service_command == jacdac.SystemCmd.Event) { const [evid, key] = pkt.data.unpack("II") let evsrc = 0 if (evid == 1) diff --git a/buttonclient.ts b/buttonclient.ts index 4ce5118aa..4cea29abb 100644 --- a/buttonclient.ts +++ b/buttonclient.ts @@ -10,9 +10,9 @@ namespace jacdac { connectControllerButton(controllerButton: number) { this.start() - control.internalOnEvent(this.eventId, JDButtonEvent.Down, + control.internalOnEvent(this.eventId, ButtonEvent.Down, () => control.raiseEvent(INTERNAL_KEY_DOWN, controllerButton)) - control.internalOnEvent(this.eventId, JDButtonEvent.Up, + control.internalOnEvent(this.eventId, ButtonEvent.Up, () => control.raiseEvent(INTERNAL_KEY_UP, controllerButton)) } @@ -34,7 +34,7 @@ namespace jacdac { */ //% blockId=jacadacbtnonevent block="jacdac %button on %event" //% group="Buttons" - onEvent(event: JDButtonEvent, handler: () => void) { + onEvent(event: ButtonEvent, handler: () => void) { this.registerEvent(event, handler); } } diff --git a/musicclient.ts b/buzzerclient.ts similarity index 85% rename from musicclient.ts rename to buzzerclient.ts index ddf4060c4..628d2a90b 100644 --- a/musicclient.ts +++ b/buzzerclient.ts @@ -12,7 +12,7 @@ namespace jacdac { class JDMelodyPlayer extends music.MelodyPlayer { private queue: ToneToPlay[] - constructor(m: music.Melody, private musicClient: MusicClient) { + constructor(m: music.Melody, private musicClient: BuzzerClient) { super(m) } @@ -34,7 +34,7 @@ namespace jacdac { const delta = e.timestamp - now if (delta > 0) pause(delta) - this.musicClient.sendCommand(JDPacket.from(JDMusicCommand.PlayTone, e.payload)) + this.musicClient.sendCommand(JDPacket.from(BuzzerCmd.PlayTone, e.payload)) } } @@ -59,9 +59,9 @@ namespace jacdac { } //% fixedInstances - export class MusicClient extends Client { + export class BuzzerClient extends Client { constructor(requiredDevice: string = null) { - super("mus", SRV_MUSIC, requiredDevice); + super("mus", SRV_BUZZER, requiredDevice); } private player: JDMelodyPlayer @@ -83,10 +83,10 @@ namespace jacdac { //% weight=76 blockGap=8 //% group="Music" playTone(frequency: number, ms: number, volume = 255): void { - this.sendCommand(JDPacket.from(JDMusicCommand.PlayTone, tonePayload(frequency, ms, volume << 2))) + this.sendCommand(JDPacket.from(BuzzerCmd.PlayTone, tonePayload(frequency, ms, volume << 2))) } } - //% fixedInstance whenUsed block="music client" - export const musicClient = new MusicClient(); + //% fixedInstance whenUsed + export const buzzerClient = new BuzzerClient(); } \ No newline at end of file diff --git a/commands.ts b/commands.ts index b0595cbd6..3a0c05b83 100644 --- a/commands.ts +++ b/commands.ts @@ -7,56 +7,8 @@ namespace jacdac { // Registers 0x200-0xeff - custom, defined per-service // Registers 0xf00-0xfff - reserved for implementation, should not be on the wire - // this is either binary (0 or non-zero), or can be gradual (eg. brightness of neopixel) - export const REG_INTENSITY = 0x01 - // the primary value of actuator (eg. servo angle) - export const REG_VALUE = 0x02 - // enable/disable streaming - export const REG_STREAMING_SAMPLES = 0x03 - // streaming interval in miliseconds - export const REG_STREAMING_INTERVAL = 0x04 - // for analog sensors - export const REG_LOW_THRESHOLD = 0x05 - export const REG_HIGH_THRESHOLD = 0x06 - // limit power drawn; in mA - export const REG_MAX_POWER = 0x07 - - // eg. one number for light sensor, all 3 coordinates for accelerometer - export const REG_READING = 0x101 - export const CMD_GET_REG = 0x1000 export const CMD_SET_REG = 0x2000 export const CMD_TYPE_MASK = 0xf000 export const CMD_REG_MASK = 0x0fff - - // Commands 0x000-0x07f - common to all services - // Commands 0x080-0xeff - defined per-service - // Commands 0xf00-0xfff - reserved for implementation - // enumeration data for CTRL, ad-data for other services - export const CMD_ADVERTISEMENT_DATA = 0x00 - // event from sensor or on broadcast service - export const CMD_EVENT = 0x01 - // request to calibrate sensor - export const CMD_CALIBRATE = 0x02 - // request human-readable description of service - export const CMD_GET_DESCRIPTION = 0x03 - - // Commands specific to control service - // do nothing - export const CMD_CTRL_NOOP = 0x80 - // blink led or otherwise draw user's attention - export const CMD_CTRL_IDENTIFY = 0x81 - // reset device - export const CMD_CTRL_RESET = 0x82 - - // identifies the type of hardware (eg., ACME Corp. Servo X-42 Rev C) - export const REG_CTRL_DEVICE_DESCRIPTION = 0x180 - // a numeric code for the string above; used to mark firmware images - export const REG_CTRL_DEVICE_CLASS = 0x181 - // MCU temperature in Celsius - export const REG_CTRL_TEMPERATURE = 0x182 - // semver string - export const REG_CTRL_FIRMWARE_VERSION = 0x185 - // number of microseconds since boot, 64 bit - export const REG_CTRL_MICROS_SINCE_BOOT = 0x186 } diff --git a/config.ts b/config.ts index 8106d4daa..e00a139ef 100644 --- a/config.ts +++ b/config.ts @@ -1,7 +1,6 @@ namespace jd_class { // needs spec export const CONTROLLER = 0x188ae4b8; - export const RGB_LED = 0x17aeb0fc } namespace jacdac { @@ -35,140 +34,12 @@ namespace jacdac { ]; } -const enum JDRGBLEDCommand { - SetColor = 0x80 -} - -const enum JDLightReg { - LightType = 0x80, - NumPixels = 0x81, - Duration = 0x82, - Color = 0x83, -} - -const enum JDLightCommand { - StartAnimation = 0x80, // deprecated - Run = 0x81, -} - -enum JDLightAnimation { - //% block="rainbow" - Rainbow = 2, - //% block="running lights" - RunningLights = 3, - //% block="color wipe" - ColorWipe = 4, - //% block="comet" - Comet = 5, - //% block="theater chase" - TheaterChase = 6, - //% block="sparkle" - Sparkle = 7 -} - -const enum JDKeyboardCommand { - Type = 0x80, - Key = 0x81, - MediaKey = 0x82, - FunctionKey = 0x83, -} - -const enum JDMouseCommand { - Button = 0x80, - Move = 0x81, - TurnWheel = 0x82, -} - const enum JDGamepadCommand { Button = 0x80, Move = 0x81, Throttle = 0x82, } -const enum JDMusicCommand { - PlayTone = 0x80, -} - -const enum JDConsoleReg { - MinPriority = 0x80 -} - -const enum JDConsoleCommand { - MessageDbg = 0x80, - SetMinPriority = 0x2000 | JDConsoleReg.MinPriority, -} - -const enum JDConsolePriority { - Debug = 0, - Log = 1, - Warning = 2, - Error = 3, - Silent = 4 -} - -const enum JDGesture { - /** - * Raised when shaken - */ - //% block=shake - Shake = DAL.ACCELEROMETER_EVT_SHAKE, - /** - * Raised when the device tilts up - */ - //% block="tilt up" - TiltUp = DAL.ACCELEROMETER_EVT_TILT_UP, - /** - * Raised when the device tilts down - */ - //% block="tilt down" - TiltDown = DAL.ACCELEROMETER_EVT_TILT_DOWN, - /** - * Raised when the screen is pointing left - */ - //% block="tilt left" - TiltLeft = DAL.ACCELEROMETER_EVT_TILT_LEFT, - /** - * Raised when the screen is pointing right - */ - //% block="tilt right" - TiltRight = DAL.ACCELEROMETER_EVT_TILT_RIGHT, - /** - * Raised when the screen faces up - */ - //% block="face up" - FaceUp = DAL.ACCELEROMETER_EVT_FACE_UP, - /** - * Raised when the screen is pointing up and the board is horizontal - */ - //% block="face down" - FaceDown = DAL.ACCELEROMETER_EVT_FACE_DOWN, - /** - * Raised when the board is falling! - */ - //% block="free fall" - FreeFall = DAL.ACCELEROMETER_EVT_FREEFALL, - /** - * Raised when a 3G shock is detected - */ - //% block="3g" - ThreeG = DAL.ACCELEROMETER_EVT_3G, - /** - * Raised when a 6G shock is detected - */ - //% block="6g" - SixG = DAL.ACCELEROMETER_EVT_6G, - /** - * Raised when a 8G shock is detected - */ - //% block="8g" - EightG = DAL.ACCELEROMETER_EVT_8G, - /** - * Raised when a 2g move (or step) is detected - */ - //% block="2g (step)" - TwoG = DAL.ACCELEROMETER_EVT_2G, -} - const enum JDDimension { //% block=x X = 0, @@ -180,24 +51,6 @@ const enum JDDimension { Strength = 3 } -const enum JDButtonEvent { - //% block="click" - Click = DAL.DEVICE_BUTTON_EVT_CLICK, - //% block="long click" - LongClick = DAL.DEVICE_BUTTON_EVT_LONG_CLICK, - //% block="up" - Up = DAL.DEVICE_BUTTON_EVT_UP, - //% block="down" - Down = DAL.DEVICE_BUTTON_EVT_DOWN -} - -const enum JDSwitchDirection { - //% block="left" - Left = DAL.DEVICE_BUTTON_EVT_UP, - //% block="right" - Right = DAL.DEVICE_BUTTON_EVT_DOWN, -} - const enum JDControllerCommand { ClientButtons = 1, ControlServer = 2, @@ -213,41 +66,3 @@ const enum JDControllerButton { Down = 4, Menu = 7 } - -const enum JDLCDFlags { - None, - Display = 1 << 0, - Blink = 1 << 1, - Cursor = 1 << 2 -} - -const enum JDLightSpectrumRange { - Full = 10, - Infrared = 20, - Visible = 40 -} - -const enum JDLightCondition { - //% block="dark" - Dark = DAL.SENSOR_THRESHOLD_LOW, - //% block="bright" - Bright = DAL.SENSOR_THRESHOLD_HIGH -} - -const enum JDLightSpectrumEvent { - FullBright = JDLightSpectrumRange.Full | DAL.LEVEL_THRESHOLD_HIGH, - FullDark = JDLightSpectrumRange.Full | DAL.LEVEL_THRESHOLD_LOW, - InfraredBright = JDLightSpectrumRange.Infrared | DAL.LEVEL_THRESHOLD_HIGH, - InfraredDark = JDLightSpectrumRange.Infrared | DAL.LEVEL_THRESHOLD_LOW, - VisibleBright = JDLightSpectrumRange.Visible | DAL.LEVEL_THRESHOLD_HIGH, - VisibleDark = JDLightSpectrumRange.Visible | DAL.LEVEL_THRESHOLD_LOW -} - -const enum JDPromixityEvent { - Close = DAL.LEVEL_THRESHOLD_LOW, - Far = DAL.LEVEL_THRESHOLD_HIGH -} - -const enum JDRotaryEncoderEvent { - Changed = 0x2233 /* ROT_EV_CHANGED */ -} diff --git a/consoleclient.ts b/consoleclient.ts index a80ca2c8d..3333e8b2f 100644 --- a/consoleclient.ts +++ b/consoleclient.ts @@ -1,6 +1,7 @@ namespace jacdac { + export class ConsoleClient extends Client { - minPriority = JDConsolePriority.Silent; // drop all packets by default + minPriority = LoggerPriority.Error + 1; // drop all packets by default onMessageReceived: (priority: number, dev: Device, message: string) => void; @@ -10,15 +11,17 @@ namespace jacdac { onAnnounce(() => { // on every announce, if we're listening to anything, tell // everyone to log - if (this.minPriority < JDConsolePriority.Silent) - JDPacket.packed(JDConsoleCommand.SetMinPriority, "i", [this.minPriority]) + if (this.minPriority <= LoggerPriority.Error) { + const SetMinPriority = 0x2000 | LoggerReg.MinPriority + JDPacket.packed(SetMinPriority, "i", [this.minPriority]) .sendAsMultiCommand(this.serviceClass) + } }) } handlePacket(packet: JDPacket) { - let pri = packet.service_command - JDConsoleCommand.MessageDbg - if (0 <= pri && pri <= JDConsolePriority.Silent) { + let pri = packet.service_command - LoggerCmd.Debug + if (0 <= pri && pri <= LoggerPriority.Error) { if (pri < this.minPriority) return; @@ -28,10 +31,10 @@ namespace jacdac { // the initial ':' is used as marker to avoid infinite console repeat const msg = `:${deviceName}> ${innerMsg}`; switch (pri) { - case JDConsolePriority.Debug: console.debug(msg); break; - case JDConsolePriority.Log: console.log(msg); break; - case JDConsolePriority.Warning: console.warn(msg); break; - case JDConsolePriority.Error: console.error(msg); break; + case LoggerPriority.Debug: console.debug(msg); break; + case LoggerPriority.Log: console.log(msg); break; + case LoggerPriority.Warning: console.warn(msg); break; + case LoggerPriority.Error: console.error(msg); break; } if (this.onMessageReceived) this.onMessageReceived(pri, this.currentDevice, innerMsg); diff --git a/consolehost.ts b/consolehost.ts index e1f071666..356611cee 100644 --- a/consolehost.ts +++ b/consolehost.ts @@ -1,7 +1,7 @@ namespace jacdac { export class ConsoleHost extends Host { private _lastListenerTime: number = 0; - minPriority = JDConsolePriority.Silent; + minPriority = LoggerPriority.Error + 1; constructor() { super("conh", SRV_LOGGER); @@ -9,8 +9,10 @@ namespace jacdac { } handlePacket(packet: JDPacket) { + // TODO: is this a command? + const SetMinPriority = 0x2000 | LoggerReg.MinPriority switch (packet.service_command) { - case JDConsoleCommand.SetMinPriority: + case SetMinPriority: const now = control.millis() // lower the priority immediately, but tighten it only when no one // was asking for lower one for some time @@ -27,19 +29,19 @@ namespace jacdac { } debug(message: string): void { - this.add(JDConsolePriority.Debug, message); + this.add(LoggerPriority.Debug, message); } log(message: string): void { - this.add(JDConsolePriority.Log, message); + this.add(LoggerPriority.Log, message); } warn(message: string): void { - this.add(JDConsolePriority.Warning, message); + this.add(LoggerPriority.Warning, message); } error(message: string): void { - this.add(JDConsolePriority.Error, message); + this.add(LoggerPriority.Error, message); } - add(priority: JDConsolePriority, message: string): void { + add(priority: LoggerPriority, message: string): void { if (!message || !message.length || priority < this.minPriority || !this._lastListenerTime) return; @@ -50,7 +52,7 @@ namespace jacdac { } for (let buf of Buffer.chunkedFromUTF8(message, JD_SERIAL_MAX_PAYLOAD_SIZE)) { - this.sendReport(JDPacket.from(JDConsoleCommand.MessageDbg + priority, buf)) + this.sendReport(JDPacket.from(LoggerPriority.Debug + priority, buf)) } } } diff --git a/controllerclient.ts b/controllerclient.ts index 34ce47486..ee0540c82 100644 --- a/controllerclient.ts +++ b/controllerclient.ts @@ -197,7 +197,7 @@ namespace jacdac { this.stateUpdateHandler(); // send state this.sendReport( - JDPacket.from(CMD_GET_REG | REG_READING, this.state)) + JDPacket.from(CMD_GET_REG | SystemReg.Reading, this.state)) // waiting for a bit pause(this.streamingInterval); // check if server still alive diff --git a/lcdclient.ts b/lcdclient.ts index 0a83ed649..79536f121 100644 --- a/lcdclient.ts +++ b/lcdclient.ts @@ -1,4 +1,11 @@ namespace jacdac { + const enum JDLCDFlags { + None, + Display = 1 << 0, + Blink = 1 << 1, + Cursor = 1 << 2 + } + //% fixedInstances export class LCDClient extends ActuatorClient { constructor(requiredDevice: string = null) { diff --git a/lightclient.ts b/lightclient.ts index 559c0e6d0..c51ff4dba 100644 --- a/lightclient.ts +++ b/lightclient.ts @@ -148,9 +148,9 @@ namespace jacdac { setStrip(numpixels: number, type = LightType.WS2812B_GRB, maxpower = 500): void { this._length = numpixels - this.setRegInt(JDLightReg.NumPixels, numpixels) - this.setRegInt(JDLightReg.LightType, type) - this.setRegInt(REG_MAX_POWER, maxpower) + this.setRegInt(LightReg.NumPixels, numpixels) + this.setRegInt(LightReg.LightType, type) + this.setRegInt(SystemReg.MaxPower, maxpower) } /** @@ -162,18 +162,18 @@ namespace jacdac { //% weight=2 blockGap=8 //% group="Light" setBrightness(brightness: number): void { - this.setRegInt(REG_INTENSITY, brightness) + this.setRegInt(SystemReg.Intensity, brightness) } runProgram(prog: Buffer) { this.currAnimation++ - this.sendCommandWithAck(JDPacket.from(JDLightCommand.Run, prog)) + this.sendCommandWithAck(JDPacket.from(LightCmd.Run, prog)) } runEncoded(prog: string, args?: number[]) { if (!args) args = [] this.currAnimation++ - this.sendCommand(JDPacket.from(JDLightCommand.Run, lightEncode(prog, args))) + this.sendCommand(JDPacket.from(LightCmd.Run, lightEncode(prog, args))) } set(idx: number, rgb: number) { diff --git a/lightsensorclient.ts b/lightsensorclient.ts index 2ee6c8490..6a0f00130 100644 --- a/lightsensorclient.ts +++ b/lightsensorclient.ts @@ -1,4 +1,11 @@ namespace jacdac { + const enum JDLightCondition { + //% block="dark" + Dark = DAL.SENSOR_THRESHOLD_LOW, + //% block="bright" + Bright = DAL.SENSOR_THRESHOLD_HIGH + } + //% fixedInstances export class LightSensorClient extends SensorClient { constructor(requiredDevice: string = null) { diff --git a/lightspectrumsensorclient.ts b/lightspectrumsensorclient.ts index 52b5d1812..4add54b89 100644 --- a/lightspectrumsensorclient.ts +++ b/lightspectrumsensorclient.ts @@ -1,4 +1,18 @@ namespace jacdac { + const enum JDLightSpectrumRange { + Full = 10, + Infrared = 20, + Visible = 40 + } + + const enum JDLightSpectrumEvent { + FullBright = JDLightSpectrumRange.Full | DAL.LEVEL_THRESHOLD_HIGH, + FullDark = JDLightSpectrumRange.Full | DAL.LEVEL_THRESHOLD_LOW, + InfraredBright = JDLightSpectrumRange.Infrared | DAL.LEVEL_THRESHOLD_HIGH, + InfraredDark = JDLightSpectrumRange.Infrared | DAL.LEVEL_THRESHOLD_LOW, + VisibleBright = JDLightSpectrumRange.Visible | DAL.LEVEL_THRESHOLD_HIGH, + VisibleDark = JDLightSpectrumRange.Visible | DAL.LEVEL_THRESHOLD_LOW + } //% fixedInstances export class LightSpectrumSensorClient extends SensorClient { constructor(requiredDevice: string = null) { diff --git a/motorclient.ts b/motorclient.ts index 44f5d7f06..5b8eed105 100644 --- a/motorclient.ts +++ b/motorclient.ts @@ -22,10 +22,10 @@ namespace jacdac { run(speed: number): void { speed = Math.clamp(-100, 100, speed) if (speed == 0) - this.setRegInt(REG_INTENSITY, 0) + this.setRegInt(SystemReg.Intensity, 0) else { - this.setRegInt(REG_VALUE, Math.clamp(-0x7fff, 0x7fff, (speed * 327.67) | 0)) - this.setRegInt(REG_INTENSITY, 1) + this.setRegInt(SystemReg.Value, Math.clamp(-0x7fff, 0x7fff, (speed * 327.67) | 0)) + this.setRegInt(SystemReg.Intensity, 1) } } } diff --git a/mouseclient.ts b/mouseclient.ts index ed5e92b4b..45bd29c03 100644 --- a/mouseclient.ts +++ b/mouseclient.ts @@ -19,8 +19,8 @@ namespace jacdac { */ //% blockId=jdmouseSetButton block="%mouse button %index|%down=toggleDownUp" //% group="Mouse" - setButton(button: JDMouseButton, down: boolean): void { - this.sendPackedCommand(JDMouseCommand.Button, "BB", [button, down ? 1 : 0]) + setButton(button: MouseButton, down: boolean): void { + this.sendPackedCommand(MouseCmd.SetButton, "BB", [button, down ? 1 : 0]) } /** @@ -32,7 +32,7 @@ namespace jacdac { //% y.min=-128 y.max=127 //% group="Mouse" move(x: number, y: number): void { - this.sendPackedCommand(JDMouseCommand.Move, "bb", [x, y]) + this.sendPackedCommand(MouseCmd.Move, "bb", [x, y]) } /** @@ -43,7 +43,7 @@ namespace jacdac { //% w.min=-128 w.max=127 //% group="Mouse" turnWheel(w: number): void { - this.sendPackedCommand(JDMouseCommand.TurnWheel, "b", [w]) + this.sendPackedCommand(MouseCmd.Wheel, "b", [w]) } } diff --git a/proximityclient.ts b/proximityclient.ts index cd1a407ac..4d689347d 100644 --- a/proximityclient.ts +++ b/proximityclient.ts @@ -1,4 +1,9 @@ namespace jacdac { + const enum JDPromixityEvent { + Close = DAL.LEVEL_THRESHOLD_LOW, + Far = DAL.LEVEL_THRESHOLD_HIGH + } + //% fixedInstances export class ProximityClient extends SensorClient { constructor(requiredDevice: string = null) { diff --git a/pwmlightclient.ts b/pwmlightclient.ts index 4be78eeaa..c941acfba 100644 --- a/pwmlightclient.ts +++ b/pwmlightclient.ts @@ -35,7 +35,7 @@ namespace jacdac { } setBrightness(brightness: number): void { - this.setRegInt(REG_INTENSITY, brightness << 8) + this.setRegInt(SystemReg.Intensity, brightness << 8) } showAnimation(animation: MonoLightAnimation, speed = 100) { diff --git a/pxt.json b/pxt.json index b4d5bc771..6585c69df 100644 --- a/pxt.json +++ b/pxt.json @@ -32,24 +32,21 @@ "actuator.ts", "controllerclient.ts", "ns.ts", - "nameservice.ts", + "rolemanager.ts", "aggregator.ts", "sensorclient.ts", "consoleclient.ts", "buttonclient.ts", "accelerometerclient.ts", "lightclient.ts", - "keyboardclient.ts", - "mouseclient.ts", "servoclient.ts", "motorclient.ts", "rotaryencoderclient.ts", "arcadecontrolsclient.ts", - "musicclient.ts", + "buzzerclient.ts", "wificlient.ts", "pwmlightclient.ts", "multitouchclient.ts", - "rgbledclient.ts", "modelrunnerclient.ts", "sliderclient.ts", "specconstants.ts", @@ -63,7 +60,7 @@ "nucleo-f411re": "*" }, "fileDependencies": { - "musicclient.ts": "mixer", + "buzzerclient.ts": "mixer", "wificlient.ts": "net", "mbcompat.ts": "target:microbit" }, diff --git a/nameservice.ts b/rolemanager.ts similarity index 100% rename from nameservice.ts rename to rolemanager.ts diff --git a/rotaryencoderclient.ts b/rotaryencoderclient.ts index 08142afbe..9c8ecff5a 100644 --- a/rotaryencoderclient.ts +++ b/rotaryencoderclient.ts @@ -48,7 +48,7 @@ namespace jacdac { */ //% blockId=jacadacrotaryencoderonevent block="jacdac %client on %event" //% group="Light sensor" - onEvent(event: JDRotaryEncoderEvent, handler: () => void) { + onEvent(event: RoleManagerEvent, handler: () => void) { this.registerEvent(event, handler); } } diff --git a/routing.ts b/routing.ts index 440294ba1..9301296d1 100644 --- a/routing.ts +++ b/routing.ts @@ -51,9 +51,9 @@ namespace jacdac { if (this.handleStatusCode(pkt)) return; - if (pkt.service_command == CMD_ADVERTISEMENT_DATA) { + if (pkt.service_command == SystemCmd.Announce) { this.sendReport( - JDPacket.from(CMD_ADVERTISEMENT_DATA, this.advertisementData())) + JDPacket.from(SystemCmd.Announce, this.advertisementData())) } else { this.stateUpdated = false this.handlePacket(pkt) @@ -76,7 +76,7 @@ namespace jacdac { } protected sendChangeEvent(): void { - this.sendReport(JDPacket.packed(CMD_EVENT, "I", [SystemEvent.Change])) + this.sendReport(JDPacket.packed(SystemCmd.Event, "I", [SystemEvent.Change])) } private handleStatusCode(pkt: JDPacket): boolean { @@ -269,14 +269,14 @@ namespace jacdac { } requestAdvertisementData() { - this.sendCommand(JDPacket.onlyHeader(CMD_ADVERTISEMENT_DATA)) + this.sendCommand(JDPacket.onlyHeader(SystemCmd.Announce)) } handlePacketOuter(pkt: JDPacket) { - if (pkt.service_command == CMD_ADVERTISEMENT_DATA) + if (pkt.service_command == SystemCmd.Announce) this.advertisementData = pkt.data - if (pkt.service_command == CMD_EVENT) + if (pkt.service_command == SystemCmd.Event) this.raiseEvent(pkt.intData, pkt.data.length >= 8 ? pkt.getNumber(NumberFormat.Int32LE, 4) : undefined) this.handlePacket(pkt) @@ -473,24 +473,24 @@ namespace jacdac { return q.value } - get classDescription() { - const v = this.query(REG_CTRL_DEVICE_DESCRIPTION, null) - if (v) return v.toString() - else { - const num = this.query(REG_CTRL_DEVICE_CLASS, null) - if (num) - return "0x" + num.toHex() - else - return "" - } - } - - get temperature() { - return this.queryInt(REG_CTRL_TEMPERATURE) + get mcuTemperature() { + return this.queryInt(CtrlReg.McuTemperature) } get firmwareVersion() { - const b = this.query(REG_CTRL_FIRMWARE_VERSION, null) + const b = this.query(CtrlReg.FirmwareVersion, null) + if (b) return b.toString() + else return "" + } + + get firmwareUrl() { + const b = this.query(CtrlReg.FirmwareUrl, null) + if (b) return b.toString() + else return "" + } + + get deviceUrl() { + const b = this.query(CtrlReg.DeviceUrl, null) if (b) return b.toString() else return "" } @@ -549,16 +549,16 @@ namespace jacdac { } handlePacketOuter(pkt: JDPacket) { switch (pkt.service_command) { - case CMD_ADVERTISEMENT_DATA: + case SystemCmd.Announce: queueAnnounce() break - case CMD_CTRL_IDENTIFY: + case CtrlCmd.Identify: control.runInParallel(onIdentifyRequest) break - case CMD_CTRL_RESET: + case CtrlCmd.Reset: control.reset() break - case CMD_GET_REG | REG_CTRL_DEVICE_DESCRIPTION: + case CMD_GET_REG | CtrlReg.DeviceDescription: this.sendReport(JDPacket.from(pkt.service_command, Buffer.fromUTF8("PXT: " + control.programName()))) break } @@ -595,7 +595,7 @@ namespace jacdac { const ids = hostServices.map(h => h.running ? h.serviceClass : -1) if (restartCounter < 0xf) restartCounter++ ids[0] = restartCounter | 0x100 - JDPacket.packed(CMD_ADVERTISEMENT_DATA, fmt, ids) + JDPacket.packed(SystemCmd.Announce, fmt, ids) ._sendReport(selfDevice()) announceCallbacks.forEach(f => f()) for (const cl of _allClients) @@ -710,7 +710,7 @@ namespace jacdac { let dev = devices_.find(d => d.deviceId == devId) if (pkt.service_number == JD_SERVICE_NUMBER_CTRL) { - if (pkt.service_command == CMD_ADVERTISEMENT_DATA) { + if (pkt.service_command == SystemCmd.Announce) { if (dev && (dev.services[0] & 0xf) > (pkt.data[0] & 0xf)) { // if the reset counter went down, it means the device resetted; treat it as new device devices_.removeElement(dev) diff --git a/sensorclient.ts b/sensorclient.ts index 508a7a71a..099d36b4e 100644 --- a/sensorclient.ts +++ b/sensorclient.ts @@ -21,7 +21,7 @@ namespace jacdac { announceCallback() { if (this.isStreaming) - this.setRegInt(REG_STREAMING_SAMPLES, this.isStreaming ? 255 : 0) + this.setRegInt(SystemReg.StreamingSamples, this.isStreaming ? 255 : 0) } /** @@ -34,16 +34,16 @@ namespace jacdac { public setStreaming(on: boolean, interval?: number) { this.start(); this.isStreaming = on - this.setRegInt(REG_STREAMING_SAMPLES, this.isStreaming ? 255 : 0) + this.setRegInt(SystemReg.StreamingSamples, this.isStreaming ? 255 : 0) if (interval != undefined) - this.setRegInt(REG_STREAMING_INTERVAL, interval) + this.setRegInt(SystemReg.StreamingInterval, interval) } /** * Requests the sensor to calibrate */ public calibrate() { - this.sendCommand(JDPacket.onlyHeader(CMD_CALIBRATE)) + this.sendCommand(JDPacket.onlyHeader(SystemCmd.Calibrate)) } public onStateChanged(handler: () => void) { @@ -54,7 +54,7 @@ namespace jacdac { handlePacket(packet: JDPacket) { // this.log(`vpkt ${packet.service_command}`) switch (packet.service_command) { - case CMD_GET_REG | REG_READING: { + case CMD_GET_REG | SystemReg.Reading: { const state = packet.data const changed = !state.equals(this._lastState); this.handleVirtualState(state); @@ -77,7 +77,7 @@ namespace jacdac { } protected setThreshold(low: boolean, value: number) { - this.setRegInt(low ? REG_LOW_THRESHOLD : REG_HIGH_THRESHOLD, value) + this.setRegInt(low ? SystemReg.LowThreshold : SystemReg.HighThreshold, value) } } @@ -109,7 +109,7 @@ namespace jacdac { } handlePacket(packet: JDPacket) { - if (this._samples && packet.service_command == (CMD_GET_REG | REG_READING)) { + if (this._samples && packet.service_command == (CMD_GET_REG | SystemReg.Reading)) { const v = this.parseSample(packet) if (v != null) { let num = 1 diff --git a/sensordriver.ts b/sensordriver.ts index 07484b293..cd80dae97 100644 --- a/sensordriver.ts +++ b/sensordriver.ts @@ -4,28 +4,27 @@ namespace jacdac { */ export class SensorHost extends Host { public streamingInterval: number; // millis - public isStreaming: boolean; + public streamingSamples: number; protected lowThreshold: number protected highThreshold: number constructor(name: string, deviceClass: number) { super(name, deviceClass); this.streamingInterval = 100; - this.isStreaming = false; + this.streamingSamples = 0; } public handlePacket(packet: JDPacket) { this.log(`hpkt ${packet.service_command}`); this.stateUpdated = false - this.lowThreshold = this.handleRegInt(packet, REG_LOW_THRESHOLD, this.lowThreshold) - this.highThreshold = this.handleRegInt(packet, REG_HIGH_THRESHOLD, this.highThreshold) - this.streamingInterval = this.handleRegInt(packet, REG_STREAMING_INTERVAL, this.streamingInterval) - // TODO this should be integer counter - const newStr = this.handleRegBool(packet, REG_STREAMING_SAMPLES, this.isStreaming) - this.setStreaming(newStr) + this.lowThreshold = this.handleRegInt(packet, SystemReg.LowThreshold, this.lowThreshold) + this.highThreshold = this.handleRegInt(packet, SystemReg.HighThreshold, this.highThreshold) + this.streamingInterval = this.handleRegInt(packet, SystemReg.StreamingInterval, this.streamingInterval) + const samples = this.handleRegInt(packet, SystemReg.StreamingSamples, this.streamingSamples) + this.setStreaming(samples) switch (packet.service_command) { - case CMD_CALIBRATE: + case SystemCmd.Calibrate: this.handleCalibrateCommand(packet); break default: @@ -48,47 +47,53 @@ namespace jacdac { } protected raiseHostEvent(value: number) { - this.sendReport(JDPacket.packed(CMD_EVENT, "I", [value])) + this.sendReport(JDPacket.packed(SystemCmd.Event, "I", [value])) } - public setStreaming(on: boolean) { - if (on) this.startStreaming(); + public setStreaming(samples: number) { + if (samples) this.startStreaming(samples); else this.stopStreaming(); } - private startStreaming() { - if (this.isStreaming) + private startStreaming(samples: number) { + if (this.streamingSamples) { + // already running + this.streamingSamples = samples; return; + } this.log(`start`); - this.isStreaming = true; + this.streamingSamples = samples; control.runInParallel(() => { - while (this.isStreaming) { + while (this.streamingSamples !== undefined && this.streamingSamples > 0) { // run callback const state = this.serializeState(); if (!!state) { // did the state change? if (this.isConnected()) { // send state and record time - this.sendReport(JDPacket.from(CMD_GET_REG | REG_READING, state)) + this.sendReport(JDPacket.from(CMD_GET_REG | SystemReg.Reading, state)) } } - // check streaming interval value - if (this.streamingInterval < 0) + // check streaming interval value or cancelled + if (this.streamingInterval < 0 || this.streamingSamples === undefined) break; // waiting for a bit pause(this.streamingInterval); + // decrement counter + if (this.streamingSamples !== undefined) + this.streamingSamples--; } - this.isStreaming = false + this.streamingSamples = 0; this.log(`stopped`); }) } private stopStreaming() { - if (this.isStreaming) { + if (this.streamingSamples > 0) { this.log(`stopping`) - this.isStreaming = null - pauseUntil(() => this.isStreaming === false); + this.streamingSamples = undefined + pauseUntil(() => this.streamingSamples === 0); } } } diff --git a/servoclient.ts b/servoclient.ts index 564ebdf18..0fde1e544 100644 --- a/servoclient.ts +++ b/servoclient.ts @@ -14,10 +14,10 @@ namespace jacdac { if (n === this.pulse) return if (n == null) { - this.setRegInt(REG_INTENSITY, 0) + this.setRegInt(SystemReg.Intensity, 0) } else { - this.setRegInt(REG_VALUE, n | 0) - this.setRegInt(REG_INTENSITY, 1) + this.setRegInt(SystemReg.Value, n | 0) + this.setRegInt(SystemReg.Intensity, 1) } this.pulse = n } diff --git a/specconstants.ts b/specconstants.ts index 4c8a30403..3fa140672 100644 --- a/specconstants.ts +++ b/specconstants.ts @@ -19,27 +19,35 @@ namespace jacdac { */ SetRegister = 0x2000, - // const [eventId, eventArgument] = buf.unpack("LL") - /** Event from sensor or a broadcast service. */ + /** + * Event from sensor or a broadcast service. + * + * ``` + * const [eventId, eventArgument] = buf.unpack("LL") + * ``` + */ Event = 0x1, - /** No args. Request to calibrate a sensor. The report indicates the calibration is done. */ + /** + * No args. Request to calibrate a sensor. The report indicates the calibration is done. + */ Calibrate = 0x2, } - export const enum SystemEvent { - /** Emit notifying that the internal state of the service changed. */ - Change = 0x1, - } - export const enum SystemReg { - /** Read-write uint32_t. This is either binary on/off (0 or non-zero), or can be gradual (eg. brightness of an RGB LED strip). */ + /** + * Read-write uint32_t. This is either binary on/off (0 or non-zero), or can be gradual (eg. brightness of an RGB LED strip). + */ Intensity = 0x1, - /** Read-write int32_t. The primary value of actuator (eg. servo pulse length, or motor duty cycle). */ + /** + * Read-write int32_t. The primary value of actuator (eg. servo pulse length, or motor duty cycle). + */ Value = 0x2, - /** Read-write mA uint16_t. Limit the power drawn by the service, in mA. */ + /** + * Read-write mA uint16_t. Limit the power drawn by the service, in mA. + */ MaxPower = 0x7, /** @@ -48,41 +56,64 @@ namespace jacdac { */ StreamingSamples = 0x3, - /** Read-write ms uint32_t. Period between packets of data when streaming in milliseconds. */ + /** + * Read-write ms uint32_t. Period between packets of data when streaming in milliseconds. + */ StreamingInterval = 0x4, - /** Read-only int32_t. Read-only value of the sensor, also reported in streaming. */ + /** + * Read-only int32_t. Read-only value of the sensor, also reported in streaming. + */ Reading = 0x101, - /** Read-write int32_t. Thresholds for event generation for event generation for analog sensors. */ + /** + * Read-write int32_t. Thresholds for event generation for event generation for analog sensors. + */ LowThreshold = 0x5, - /** Read-write int32_t. Thresholds for event generation for event generation for analog sensors. */ + /** + * Read-write int32_t. Thresholds for event generation for event generation for analog sensors. + */ HighThreshold = 0x6, - // const [code, vendorCode] = buf.unpack("HH") /** * Reports the current state or error status of the device. ``code`` is a standardized value from * the JACDAC error codes. ``vendor_code`` is any vendor specific error code describing the device * state. This report is typically not queried, when a device has an error, it will typically * add this report in frame along with the anounce packet. + * + * ``` + * const [code, vendorCode] = buf.unpack("HH") + * ``` */ StatusCode = 0x7, - /** Constant ms uint32_t. Preferred default streaming interval for sensor in milliseconds. */ + /** + * Constant ms uint32_t. Preferred default streaming interval for sensor in milliseconds. + */ StreamingPreferredInterval = 0x102, } + export const enum SystemEvent { + /** + * Emit notifying that the internal state of the service changed. + */ + Change = 0x1, + } + } namespace jacdac { // Service: Base service export const enum BaseReg { - // const [code, vendorCode] = buf.unpack("HH") /** * Reports the current state or error status of the device. ``code`` is a standardized value from * the JACDAC error codes. ``vendor_code`` is any vendor specific error code describing the device * state. This report is typically not queried, when a device has an error, it will typically * add this report in frame along with the anounce packet. + * + * ``` + * const [code, vendorCode] = buf.unpack("HH") + * ``` */ StatusCode = 0x7, } @@ -97,10 +128,14 @@ namespace jacdac { */ StreamingSamples = 0x3, - /** Read-write ms uint32_t. Period between packets of data when streaming in milliseconds. */ + /** + * Read-write ms uint32_t. Period between packets of data when streaming in milliseconds. + */ StreamingInterval = 0x4, - /** Constant ms uint32_t. Preferred default streaming interval for sensor in milliseconds. */ + /** + * Constant ms uint32_t. Preferred default streaming interval for sensor in milliseconds. + */ StreamingPreferredInterval = 0x102, } @@ -109,46 +144,75 @@ namespace jacdac { // Service: Accelerometer export const SRV_ACCELEROMETER = 0x1f140409 export const enum AccelReg { - // const [x, y, z] = buf.unpack("hhh") - /** Indicates the current forces acting on accelerometer. */ + /** + * Indicates the current forces acting on accelerometer. + * + * ``` + * const [x, y, z] = buf.unpack("hhh") + * ``` + */ Forces = 0x101, } export const enum AccelEvent { - /** Emitted when accelerometer is tilted in the given direction. */ + /** + * Emitted when accelerometer is tilted in the given direction. + */ TiltUp = 0x1, - /** Emitted when accelerometer is tilted in the given direction. */ + /** + * Emitted when accelerometer is tilted in the given direction. + */ TiltDown = 0x2, - /** Emitted when accelerometer is tilted in the given direction. */ + /** + * Emitted when accelerometer is tilted in the given direction. + */ TiltLeft = 0x3, - /** Emitted when accelerometer is tilted in the given direction. */ + /** + * Emitted when accelerometer is tilted in the given direction. + */ TiltRight = 0x4, - /** Emitted when accelerometer is laying flat in the given direction. */ + /** + * Emitted when accelerometer is laying flat in the given direction. + */ FaceUp = 0x5, - /** Emitted when accelerometer is laying flat in the given direction. */ + /** + * Emitted when accelerometer is laying flat in the given direction. + */ FaceDown = 0x6, - /** Emitted when total force acting on accelerometer is much less than 1g. */ + /** + * Emitted when total force acting on accelerometer is much less than 1g. + */ Freefall = 0x7, - /** Emitted when forces change violently a few times. */ + /** + * Emitted when forces change violently a few times. + */ Shake = 0xb, - /** Emitted when force in any direction exceeds given threshold. */ + /** + * Emitted when force in any direction exceeds given threshold. + */ Force_2g = 0xc, - /** Emitted when force in any direction exceeds given threshold. */ + /** + * Emitted when force in any direction exceeds given threshold. + */ Force_3g = 0x8, - /** Emitted when force in any direction exceeds given threshold. */ + /** + * Emitted when force in any direction exceeds given threshold. + */ Force_6g = 0x9, - /** Emitted when force in any direction exceeds given threshold. */ + /** + * Emitted when force in any direction exceeds given threshold. + */ Force_8g = 0xa, } @@ -167,24 +231,35 @@ namespace jacdac { } export const enum SensorAggregatorReg { - // const [samplingInterval, samplesInWindow, reserved, serviceClass, serviceNum, sampleSize, sampleType, sampleShift] = buf.unpack("HHL8xLBBBb") - // const deviceId = buf.slice(8, 8) /** * Set automatic input collection. * These settings are stored in flash. + * + * ``` + * const [samplingInterval, samplesInWindow, reserved, serviceClass, serviceNum, sampleSize, sampleType, sampleShift] = buf.unpack("HHL8xLBBBb") + * const deviceId = buf.slice(8, 8) + * ``` */ Inputs = 0x80, - /** Read-only uint32_t. Number of input samples collected so far. */ + /** + * Read-only uint32_t. Number of input samples collected so far. + */ NumSamples = 0x180, - /** Read-only B uint8_t. Size of a single sample. */ + /** + * Read-only B uint8_t. Size of a single sample. + */ SampleSize = 0x181, - /** Read-write uint32_t. When set to `N`, will stream `N` samples as `current_sample` reading. */ + /** + * Read-write uint32_t. When set to `N`, will stream `N` samples as `current_sample` reading. + */ StreamSamples = 0x81, - /** Read-only bytes. Last collected sample. */ + /** + * Read-only bytes. Last collected sample. + */ CurrentSample = 0x101, } @@ -207,23 +282,38 @@ namespace jacdac { * that "fits" this device. */ Info = 0x0, - // report Info - // const [serviceClass, pageSize, flashableSize, firmwareIdentifier] = buf.unpack("LLLL") - /** Argument: session_id uint32_t. The flashing host should generate a random id, and use this command to set it. */ + /** + * report Info + * ``` + * const [serviceClass, pageSize, flashableSize, firmwareIdentifier] = buf.unpack("LLLL") + * ``` + */ + + /** + * Argument: session_id uint32_t. The flashing host should generate a random id, and use this command to set it. + */ SetSession = 0x81, - // const [pageAddress, pageOffset, chunkNo, chunkMax, sessionId, reserved0, reserved1, reserved2, reserved3] = buf.unpack("LHBBLLLLL") - // const pageData = buf.slice(28) /** * Use to send flashing data. A physical page is split into `chunk_max + 1` chunks, where `chunk_no = 0 ... chunk_max`. * Each chunk is stored at `page_address + page_offset`. `page_address` has to be equal in all chunks, * and is included in response. * Only the last chunk causes writing to flash and elicits response. + * + * ``` + * const [pageAddress, pageOffset, chunkNo, chunkMax, sessionId, reserved0, reserved1, reserved2, reserved3] = buf.unpack("LHBBLLLLL") + * const pageData = buf.slice(28) + * ``` */ PageData = 0x80, - // report PageData - // const [sessionId, pageError, pageAddress] = buf.unpack("LLL") + + /** + * report PageData + * ``` + * const [sessionId, pageError, pageAddress] = buf.unpack("LLL") + * ``` + */ } } @@ -231,31 +321,71 @@ namespace jacdac { // Service: Button export const SRV_BUTTON = 0x1473a263 export const enum ButtonReg { - /** Read-only bool (uint8_t). Indicates whether the button is currently active (pressed). */ + /** + * Read-only bool (uint8_t). Indicates whether the button is currently active (pressed). + */ Pressed = 0x101, } export const enum ButtonEvent { - /** Emitted when button goes from inactive (`pressed == 0`) to active. */ + /** + * Emitted when button goes from inactive (`pressed == 0`) to active. + */ Down = 0x1, - /** Emitted when button goes from active (`pressed == 1`) to inactive. */ + /** + * Emitted when button goes from active (`pressed == 1`) to inactive. + */ Up = 0x2, - /** Emitted together with `up` when the press time was not longer than 500ms. */ + /** + * Emitted together with `up` when the press time was not longer than 500ms. + */ Click = 0x3, - /** Emitted together with `up` when the press time was more than 500ms. */ + /** + * Emitted together with `up` when the press time was more than 500ms. + */ LongClick = 0x4, } +} +namespace jacdac { + // Service: Buzzer + export const SRV_BUZZER = 0x1b57b1d7 + export const enum BuzzerReg { + /** + * Read-write ratio uint8_t. The volume (duty cycle) of the buzzer. + */ + Volume = 0x1, + } + + export const enum BuzzerCmd { + /** + * Play a PWM tone with given period and duty for given duration. + * The duty is scaled down with `volume` register. + * To play tone at frequency `F` Hz and volume `V` (in `0..1`) you will want + * to send `P = 1000000 / F` and `D = P * V / 2`. + * + * ``` + * const [period, duty, duration] = buf.unpack("HHH") + * ``` + */ + PlayTone = 0x80, + } + } namespace jacdac { // Service: CODAL Message Bus export const SRV_CODAL_MESSAGE_BUS = 0x16ad7cd5 export const enum CODALMessageBusCmd { - // const [id, event] = buf.unpack("HH") - /** Sends a new event on the message bus. */ + /** + * Sends a new event on the message bus. + * + * ``` + * const [id, event] = buf.unpack("HH") + * ``` + */ Send = 0x80, } @@ -278,42 +408,69 @@ namespace jacdac { * The command form can be used to induce report, which is otherwise broadcast every 500ms. */ Services = 0x0, - // report Services - // const [restartCounter, flags, reserved, serviceClass] = buf.unpack("BBHL") - /** No args. Do nothing. Always ignored. Can be used to test ACKs. */ + /** + * report Services + * ``` + * const [restartCounter, flags, reserved, serviceClass] = buf.unpack("BBHL") + * ``` + */ + + /** + * No args. Do nothing. Always ignored. Can be used to test ACKs. + */ Noop = 0x80, - /** No args. Blink an LED or otherwise draw user's attention. */ + /** + * No args. Blink an LED or otherwise draw user's attention. + */ Identify = 0x81, - /** No args. Reset device. ACK may or may not be sent. */ + /** + * No args. Reset device. ACK may or may not be sent. + */ Reset = 0x82, } export const enum CtrlReg { - /** Constant string (bytes). Identifies the type of hardware (eg., ACME Corp. Servo X-42 Rev C) */ + /** + * Constant string (bytes). Identifies the type of hardware (eg., ACME Corp. Servo X-42 Rev C) + */ DeviceDescription = 0x180, - /** Constant uint32_t. A numeric code for the string above; used to identify firmware images and devices. */ + /** + * Constant uint32_t. A numeric code for the string above; used to identify firmware images and devices. + */ FirmwareIdentifier = 0x181, - /** Constant uint32_t. Typically the same as `firmware_identifier` unless device was flashed by hand; the bootloader will respond to that code. */ + /** + * Constant uint32_t. Typically the same as `firmware_identifier` unless device was flashed by hand; the bootloader will respond to that code. + */ BootloaderFirmwareIdentifier = 0x184, - /** Constant string (bytes). A string describing firmware version; typically semver. */ + /** + * Constant string (bytes). A string describing firmware version; typically semver. + */ FirmwareVersion = 0x185, - /** Read-only °C int16_t. MCU temperature in degrees Celsius (approximate). */ + /** + * Read-only °C int16_t. MCU temperature in degrees Celsius (approximate). + */ McuTemperature = 0x182, - /** Read-only μs uint64_t. Number of microseconds since boot. */ + /** + * Read-only μs uint64_t. Number of microseconds since boot. + */ Uptime = 0x186, - /** Constant string (bytes). Request the information web site for this device */ + /** + * Constant string (bytes). Request the information web site for this device + */ DeviceUrl = 0x187, - /** Constant string (bytes). URL with machine-readable metadata information about updating device firmware */ + /** + * Constant string (bytes). URL with machine-readable metadata information about updating device firmware + */ FirmwareUrl = 0x188, } @@ -328,7 +485,9 @@ namespace jacdac { */ Position = 0x101, - /** Constant # uint16_t. This specifies by how much `position` changes when the crank does 360 degree turn. Typically 12 or 24. */ + /** + * Constant # uint16_t. This specifies by how much `position` changes when the crank does 360 degree turn. Typically 12 or 24. + */ ClicksPerTurn = 0x180, } @@ -351,28 +510,48 @@ namespace jacdac { } export const enum GamepadCmd { - /** No args. Indicates number of players supported and which buttons are present on the controller. */ + /** + * No args. Indicates number of players supported and which buttons are present on the controller. + */ Announce = 0x0, - // report Announce - // const [flags, numPlayers, buttonPresent] = buf.unpack("BBH") + + /** + * report Announce + * ``` + * const [flags, numPlayers, buttonPresent] = buf.unpack("BBH") + * ``` + */ } export const enum GamepadReg { - // const [button, playerIndex, pressure] = buf.unpack("HBB") /** * Indicates which buttons are currently active (pressed). * `pressure` should be `0xff` for digital buttons, and proportional for analog ones. + * + * ``` + * const [button, playerIndex, pressure] = buf.unpack("HBB") + * ``` */ Buttons = 0x101, } export const enum GamepadEvent { - // const [button, playerIndex] = buf.unpack("HH") - /** Emitted when button goes from inactive to active. */ + /** + * Emitted when button goes from inactive to active. + * + * ``` + * const [button, playerIndex] = buf.unpack("HH") + * ``` + */ Down = 0x1, - // const [button, playerIndex] = buf.unpack("HH") - /** Emitted when button goes from active to inactive. */ + /** + * Emitted when button goes from active to inactive. + * + * ``` + * const [button, playerIndex] = buf.unpack("HH") + * ``` + */ Up = 0x2, } @@ -381,7 +560,9 @@ namespace jacdac { // Service: Humidity export const SRV_HUMIDITY = 0x16c810b8 export const enum HumidityReg { - /** Read-only %RH u22.10 (uint32_t). The relative humidity in percentage of full water saturation. */ + /** + * Read-only %RH u22.10 (uint32_t). The relative humidity in percentage of full water saturation. + */ Humidity = 0x101, } @@ -402,61 +583,100 @@ namespace jacdac { */ Disconnect = 0x81, - // const msg = string0(buf, 0, 0) - // const propertyName = string0(buf, 0, 1) - // const propertyValue = string0(buf, 0, 2) - /** Sends a short message in string format (it's typically JSON-encoded). Multiple properties can be attached. */ + /** + * Sends a short message in string format (it's typically JSON-encoded). Multiple properties can be attached. + * + * ``` + * const msg = string0(buf, 0, 0) + * const propertyName = string0(buf, 0, 1) + * const propertyValue = string0(buf, 0, 2) + * ``` + */ SendStringMsg = 0x82, - /** No args. Sends an arbitrary, possibly binary, message. The size is only limited by RAM on the module. */ + /** + * No args. Sends an arbitrary, possibly binary, message. The size is only limited by RAM on the module. + */ SendMsgExt = 0x83, - /** Argument: devicebound pipe (bytes). Subscribes for cloud to device messages, which will be sent over the specified pipe. */ + /** + * Argument: devicebound pipe (bytes). Subscribes for cloud to device messages, which will be sent over the specified pipe. + */ Subscribe = 0x84, - /** Argument: twin_result pipe (bytes). Ask for current device digital twin. */ + /** + * Argument: twin_result pipe (bytes). Ask for current device digital twin. + */ GetTwin = 0x85, - /** Argument: twin_updates pipe (bytes). Subscribe to updates to our twin. */ + /** + * Argument: twin_updates pipe (bytes). Subscribe to updates to our twin. + */ SubscribeTwin = 0x87, - /** No args. Start twin update. */ + /** + * No args. Start twin update. + */ PatchTwin = 0x86, - /** Argument: method_call pipe (bytes). Subscribe to direct method calls. */ + /** + * Argument: method_call pipe (bytes). Subscribe to direct method calls. + */ SubscribeMethod = 0x88, - // const [status] = buf.unpack("L") - // const requestId = string0(buf, 4, 0) - /** Respond to a direct method call (`request_id` comes from `subscribe_method` pipe). */ + /** + * Respond to a direct method call (`request_id` comes from `subscribe_method` pipe). + * + * ``` + * const [status] = buf.unpack("L") + * const requestId = string0(buf, 4, 0) + * ``` + */ RespondToMethod = 0x89, } export const enum IotHubPipeCmd { - // const propertyName = string0(buf, 0, 0) - // const propertyValue = string0(buf, 0, 1) - /** Set properties on the message. Can be repeated multiple times. */ + /** + * Set properties on the message. Can be repeated multiple times. + * + * ``` + * const propertyName = string0(buf, 0, 0) + * const propertyValue = string0(buf, 0, 1) + * ``` + */ Properties = 0x1, - // const propertyName = string0(buf, 0, 0) - // const propertyValue = string0(buf, 0, 1) /** * If there are any properties, this meta-report is send one or more times. * All properties of a given message are always sent before the body. + * + * ``` + * const propertyName = string0(buf, 0, 0) + * const propertyValue = string0(buf, 0, 1) + * ``` */ DeviceboundProperties = 0x1, - /** Argument: status_code uint32_t. This emitted if status is not 200. */ + /** + * Argument: status_code uint32_t. This emitted if status is not 200. + */ TwinError = 0x1, - // const methodName = string0(buf, 0, 0) - // const requestId = string0(buf, 0, 1) - /** This is sent after the last part of the `method_call_body`. */ + /** + * This is sent after the last part of the `method_call_body`. + * + * ``` + * const methodName = string0(buf, 0, 0) + * const requestId = string0(buf, 0, 1) + * ``` + */ MethodCall = 0x1, } export const enum IotHubReg { - /** Read-only string (bytes). Returns `"ok"` when connected, and an error description otherwise. */ + /** + * Read-only string (bytes). Returns `"ok"` when connected, and an error description otherwise. + */ ConnectionStatus = 0x180, /** @@ -468,27 +688,38 @@ namespace jacdac { */ ConnectionString = 0x80, - /** Read-only string (bytes). Something like `my-iot-hub.azure-devices.net`; empty string when `connection_string` is not set. */ + /** + * Read-only string (bytes). Something like `my-iot-hub.azure-devices.net`; empty string when `connection_string` is not set. + */ HubName = 0x181, - /** Read-only string (bytes). Something like `my-dev-007`; empty string when `connection_string` is not set. */ + /** + * Read-only string (bytes). Something like `my-dev-007`; empty string when `connection_string` is not set. + */ DeviceId = 0x182, } export const enum IotHubEvent { - /** Emitted upon successful connection. */ + /** + * Emitted upon successful connection. + */ Connected = 0x1, - /** Argument: reason string (bytes). Emitted when connection was lost. */ + /** + * Argument: reason string (bytes). Emitted when connection was lost. + */ ConnectionError = 0x2, - // const msg = string0(buf, 0, 0) - // const propertyName = string0(buf, 0, 1) - // const propertyValue = string0(buf, 0, 2) /** * This event is emitted upon reception of a cloud to device message, that is a string * (doesn't contain NUL bytes) and fits in a single event packet. * For reliable reception, use the `subscribe` command above. + * + * ``` + * const msg = string0(buf, 0, 0) + * const propertyName = string0(buf, 0, 1) + * const propertyValue = string0(buf, 0, 2) + * ``` */ DeviceboundStr = 0x3, } @@ -517,11 +748,18 @@ namespace jacdac { } export const enum KeyboardCmd { - // const [selector, modifiers, action] = buf.unpack("HBB") - /** Presses a key or a sequence of keys down. */ + /** + * Presses a key or a sequence of keys down. + * + * ``` + * const [selector, modifiers, action] = buf.unpack("HBB") + * ``` + */ Key = 0x80, - /** No args. Clears all pressed keys. */ + /** + * No args. Clears all pressed keys. + */ Clear = 0x81, } @@ -536,21 +774,31 @@ namespace jacdac { */ Leds = 0x80, - /** Read-write bool (uint8_t). Disables or enables the whole screen. */ + /** + * Read-write bool (uint8_t). Disables or enables the whole screen. + */ Enabled = 0x81, - /** Read-write uint8_t. Sets the general brightness of the LEDs. */ + /** + * Read-write uint8_t. Sets the general brightness of the LEDs. + */ Brightness = 0x82, - /** Constant # uint16_t. Number of rows on the screen */ + /** + * Constant # uint16_t. Number of rows on the screen + */ Rows = 0x83, - /** Constant # uint16_t. Number of columns on the screen */ + /** + * Constant # uint16_t. Number of columns on the screen + */ Columns = 0x84, } export const enum LEDMatrixControllerCmd { - /** No args. Shorthand command to clear all the LEDs on the screen. */ + /** + * No args. Shorthand command to clear all the LEDs on the screen. + */ Clear = 0x80, } @@ -606,12 +854,16 @@ namespace jacdac { */ NumPixels = 0x81, - /** Read-write mA uint16_t. Limit the power drawn by the light-strip (and controller). */ + /** + * Read-write mA uint16_t. Limit the power drawn by the light-strip (and controller). + */ MaxPower = 0x7, } export const enum LightCmd { - /** Argument: program bytes. Run the given light "program". See service description for details. */ + /** + * Argument: program bytes. Run the given light "program". See service description for details. + */ Run = 0x81, } @@ -639,16 +891,24 @@ namespace jacdac { } export const enum LoggerCmd { - /** Argument: message string (bytes). Report a message. */ + /** + * Argument: message string (bytes). Report a message. + */ Debug = 0x80, - /** Argument: message string (bytes). Report a message. */ + /** + * Argument: message string (bytes). Report a message. + */ Log = 0x81, - /** Argument: message string (bytes). Report a message. */ + /** + * Argument: message string (bytes). Report a message. + */ Warn = 0x82, - /** Argument: message string (bytes). Report a message. */ + /** + * Argument: message string (bytes). Report a message. + */ Error = 0x83, } @@ -657,13 +917,16 @@ namespace jacdac { // Service: Microphone export const SRV_MICROPHONE = 0x113dac86 export const enum MicrophoneCmd { - // const [numSamples] = buf.unpack("12xL") - // const samples = buf.slice(0, 12) /** * The samples will be streamed back over the `samples` pipe. * If `num_samples` is `0`, streaming will only stop when the pipe is closed. * Otherwise the specified number of samples is streamed. * Samples are sent as `i16`. + * + * ``` + * const [numSamples] = buf.unpack("12xL") + * const samples = buf.slice(0, 12) + * ``` */ Sample = 0x81, } @@ -712,25 +975,39 @@ namespace jacdac { */ AutoInvokeEvery = 0x80, - /** Read-only output f32 (uint32_t). Results of last model invocation as `float32` array. */ + /** + * Read-only output f32 (uint32_t). Results of last model invocation as `float32` array. + */ Outputs = 0x101, - /** Read-only dimension uint16_t. The shape of the input tensor. */ + /** + * Read-only dimension uint16_t. The shape of the input tensor. + */ InputShape = 0x180, - /** Read-only dimension uint16_t. The shape of the output tensor. */ + /** + * Read-only dimension uint16_t. The shape of the output tensor. + */ OutputShape = 0x181, - /** Read-only μs uint32_t. The time consumed in last model execution. */ + /** + * Read-only μs uint32_t. The time consumed in last model execution. + */ LastRunTime = 0x182, - /** Read-only B uint32_t. Number of RAM bytes allocated for model execution. */ + /** + * Read-only B uint32_t. Number of RAM bytes allocated for model execution. + */ AllocatedArenaSize = 0x183, - /** Read-only B uint32_t. The size of the model in bytes. */ + /** + * Read-only B uint32_t. The size of the model in bytes. + */ ModelSize = 0x184, - /** Read-only string (bytes). Textual description of last error when running or loading model (if any). */ + /** + * Read-only string (bytes). Textual description of last error when running or loading model (if any). + */ LastError = 0x185, /** @@ -741,7 +1018,9 @@ namespace jacdac { */ Format = 0x186, - /** Constant uint32_t. A version number for the format. */ + /** + * Constant uint32_t. A version number for the format. + */ FormatVersion = 0x187, /** @@ -762,7 +1041,9 @@ namespace jacdac { */ Duty = 0x2, - /** Read-write bool (uint8_t). Turn the power to the motor on/off. */ + /** + * Read-write bool (uint8_t). Turn the power to the motor on/off. + */ Enabled = 0x1, } @@ -786,25 +1067,34 @@ namespace jacdac { } export const enum MouseCmd { - // const [buttons, event] = buf.unpack("HB") /** * Sets the up/down state of one or more buttons. * A ``Click`` is the same as ``Down`` followed by ``Up`` after 100ms. * A ``DoubleClick`` is two clicks with ``150ms`` gap between them (that is, ``100ms`` first click, ``150ms`` gap, ``100ms`` second click). + * + * ``` + * const [buttons, event] = buf.unpack("HB") + * ``` */ SetButton = 0x80, - // const [dx, dy, time] = buf.unpack("hhH") /** * Moves the mouse by the distance specified. * If the time is positive, it specifies how long to make the move. + * + * ``` + * const [dx, dy, time] = buf.unpack("hhH") + * ``` */ Move = 0x81, - // const [dy, time] = buf.unpack("hH") /** * Turns the wheel up or down. Positive if scrolling up. * If the time is positive, it specifies how long to make the move. + * + * ``` + * const [dy, time] = buf.unpack("hH") + * ``` */ Wheel = 0x82, } @@ -823,43 +1113,35 @@ namespace jacdac { } export const enum MultitouchEvent { - /** Argument: channel uint32_t. Emitted when an input is touched. */ + /** + * Argument: channel uint32_t. Emitted when an input is touched. + */ Touch = 0x1, - /** Argument: channel uint32_t. Emitted when an input is no longer touched. */ + /** + * Argument: channel uint32_t. Emitted when an input is no longer touched. + */ Release = 0x2, - /** Argument: channel uint32_t. Emitted when an input is briefly touched. TODO Not implemented. */ + /** + * Argument: channel uint32_t. Emitted when an input is briefly touched. TODO Not implemented. + */ Tap = 0x3, - /** Argument: channel uint32_t. Emitted when an input is touched for longer than 500ms. TODO Not implemented. */ + /** + * Argument: channel uint32_t. Emitted when an input is touched for longer than 500ms. TODO Not implemented. + */ LongPress = 0x4, - /** Emitted when input channels are successively touched in order of increasing channel numbers. */ + /** + * Emitted when input channels are successively touched in order of increasing channel numbers. + */ SwipePos = 0x10, - /** Emitted when input channels are successively touched in order of decreasing channel numbers. */ - SwipeNeg = 0x11, - } - -} -namespace jacdac { - // Service: Music - export const SRV_MUSIC = 0x1b57b1d7 - export const enum MusicReg { - /** Read-write ratio uint8_t. The volume (duty cycle) of the buzzer. */ - Volume = 0x1, - } - - export const enum MusicCmd { - // const [period, duty, duration] = buf.unpack("HHH") /** - * Play a PWM tone with given period and duty for given duration. - * The duty is scaled down with `volume` register. - * To play tone at frequency `F` Hz and volume `V` (in `0..1`) you will want - * to send `P = 1000000 / F` and `D = P * V / 2`. + * Emitted when input channels are successively touched in order of decreasing channel numbers. */ - PlayTone = 0x80, + SwipeNeg = 0x11, } } @@ -867,7 +1149,9 @@ namespace jacdac { // Service: Power export const SRV_POWER = 0x1fa4c95a export const enum PowerReg { - /** Read-write bool (uint8_t). Turn the power to the bus on/off. */ + /** + * Read-write bool (uint8_t). Turn the power to the bus on/off. + */ Enabled = 0x1, /** @@ -876,16 +1160,24 @@ namespace jacdac { */ MaxPower = 0x7, - /** Read-only bool (uint8_t). Indicates whether the power has been shut down due to overdraw. */ + /** + * Read-only bool (uint8_t). Indicates whether the power has been shut down due to overdraw. + */ Overload = 0x181, - /** Read-only mA uint16_t. Present current draw from the bus. */ + /** + * Read-only mA uint16_t. Present current draw from the bus. + */ CurrentDraw = 0x101, - /** Read-only mV uint16_t. Voltage on input. */ + /** + * Read-only mV uint16_t. Voltage on input. + */ BatteryVoltage = 0x180, - /** Read-only ratio uint16_t. Fraction of charge in the battery. */ + /** + * Read-only ratio uint16_t. Fraction of charge in the battery. + */ BatteryCharge = 0x182, /** @@ -920,16 +1212,23 @@ namespace jacdac { */ Brightness = 0x1, - /** Read-write mA uint16_t. Limit the power drawn by the light-strip (and controller). */ + /** + * Read-write mA uint16_t. Limit the power drawn by the light-strip (and controller). + */ MaxPower = 0x7, - /** Constant uint8_t. Maximum number of steps allowed in animation definition. This determines the size of the `steps` register. */ + /** + * Constant uint8_t. Maximum number of steps allowed in animation definition. This determines the size of the `steps` register. + */ MaxSteps = 0x180, - // const [startIntensity, duration] = buf.unpack("HH") /** * The steps of current animation. Setting this also sets `current_iteration` to `0`. * Step with `duration == 0` is treated as an end marker. + * + * ``` + * const [startIntensity, duration] = buf.unpack("HH") + * ``` */ Steps = 0x82, @@ -939,7 +1238,9 @@ namespace jacdac { */ CurrentIteration = 0x80, - /** Read-write uint16_t. The animation will be repeated `max_iterations + 1` times. */ + /** + * Read-write uint16_t. The animation will be repeated `max_iterations + 1` times. + */ MaxIterations = 0x81, } @@ -947,51 +1248,92 @@ namespace jacdac { namespace jacdac { // Service: Role Manager export const SRV_ROLE_MANAGER = 0x119c3ad1 - export const enum RoleManagerCmd { - /** Argument: device_id uint64_t. Get the role corresponding to given device identifer. Returns empty string if unset. */ - GetRole = 0x80, - // report GetRole - // const deviceId = buf.slice(0, 8) - // const role = buf.slice(8).toString() - - // const deviceId = buf.slice(0, 8) - // const role = buf.slice(8).toString() - /** Set role. Can set to empty to remove role binding. */ - SetRole = 0x81, - - /** No args. Remove all role bindings. */ - ClearAllRoles = 0x84, - - /** Argument: stored_roles pipe (bytes). Return all roles stored internally. */ - ListStoredRoles = 0x82, - - /** Argument: required_roles pipe (bytes). List all roles required by the current program. `device_id` is `0` if role is unbound. */ - ListRequiredRoles = 0x83, - } - export const enum RoleManagerReg { - /** Read-only bool (uint8_t). Indicates if all required roles have been allocated to devices. */ + /** + * Read-only bool (uint8_t). Indicates if all required roles have been allocated to devices. + */ AllRolesAllocated = 0x181, } - // pipe_report StoredRoles - // const deviceId = buf.slice(0, 8) - // const role = buf.slice(8).toString() - // pipe_report RequiredRoles - // const [serviceClass] = buf.unpack("8xL") - // const deviceId = buf.slice(0, 8) - // const roles = buf.slice(12).toString() + export const enum RoleManagerCmd { + /** + * Argument: device_id uint64_t. Get the role corresponding to given device identifer. Returns empty string if unset. + */ + GetRole = 0x80, + /** + * report GetRole + * ``` + * const deviceId = buf.slice(0, 8) + * const role = buf.slice(8).toString() + * ``` + */ + + /** + * Set role. Can set to empty to remove role binding. + * + * ``` + * const deviceId = buf.slice(0, 8) + * const role = buf.slice(8).toString() + * ``` + */ + SetRole = 0x81, + + /** + * No args. Remove all role bindings. + */ + ClearAllRoles = 0x84, + + /** + * Argument: stored_roles pipe (bytes). Return all roles stored internally. + */ + ListStoredRoles = 0x82, + + /** + * Argument: required_roles pipe (bytes). List all roles required by the current program. `device_id` is `0` if role is unbound. + */ + ListRequiredRoles = 0x83, + } + + + /** + * pipe_report StoredRoles + * ``` + * const deviceId = buf.slice(0, 8) + * const role = buf.slice(8).toString() + * ``` + */ + + /** + * pipe_report RequiredRoles + * ``` + * const [serviceClass] = buf.unpack("8xL") + * const deviceId = buf.slice(0, 8) + * const roles = buf.slice(12).toString() + * ``` + */ + + + export const enum RoleManagerEvent { + /** + * Emit notifying that the internal state of the service changed. + */ + Change = 0x1, + } } namespace jacdac { // Service: Servo export const SRV_SERVO = 0x12fc9103 export const enum ServoReg { - /** Read-write μs uint32_t. Specifies length of the pulse in microseconds. The period is always 20ms. */ + /** + * Read-write μs uint32_t. Specifies length of the pulse in microseconds. The period is always 20ms. + */ Pulse = 0x2, - /** Read-write bool (uint8_t). Turn the power to the servo on/off. */ + /** + * Read-write bool (uint8_t). Turn the power to the servo on/off. + */ Enabled = 0x1, } @@ -1000,30 +1342,53 @@ namespace jacdac { // Service: Settings Storage export const SRV_SETTINGS_STORAGE = 0x1107dc4a export const enum SettingsCmd { - /** Argument: key string (bytes). Get the value of given setting. If no such entry exists, the value returned is empty. */ + /** + * Argument: key string (bytes). Get the value of given setting. If no such entry exists, the value returned is empty. + */ Get = 0x80, - // report Get - // const key = string0(buf, 0, 0) - // const value = buf.slice(0) - // const key = string0(buf, 0, 0) - // const value = buf.slice(0) - /** Set the value of a given setting. */ + /** + * report Get + * ``` + * const key = string0(buf, 0, 0) + * const value = buf.slice(0) + * ``` + */ + + /** + * Set the value of a given setting. + * + * ``` + * const key = string0(buf, 0, 0) + * const value = buf.slice(0) + * ``` + */ Set = 0x81, - /** Argument: key string (bytes). Delete a given setting. */ + /** + * Argument: key string (bytes). Delete a given setting. + */ Delete = 0x84, - /** Argument: results pipe (bytes). Return keys of all settings. */ + /** + * Argument: results pipe (bytes). Return keys of all settings. + */ ListKeys = 0x82, - /** Argument: results pipe (bytes). Return keys and values of all settings. */ + /** + * Argument: results pipe (bytes). Return keys and values of all settings. + */ List = 0x83, } - // pipe_report ListedEntry - // const key = string0(buf, 0, 0) - // const value = buf.slice(0) + + /** + * pipe_report ListedEntry + * ``` + * const key = string0(buf, 0, 0) + * const value = buf.slice(0) + * ``` + */ } @@ -1031,7 +1396,9 @@ namespace jacdac { // Service: Slider export const SRV_SLIDER = 0x1f274746 export const enum SliderReg { - /** Read-only ratio uint16_t. The relative position of the slider between `0x0000` and `0xffff`. */ + /** + * Read-only ratio uint16_t. The relative position of the slider between `0x0000` and `0xffff`. + */ Position = 0x101, } @@ -1046,21 +1413,28 @@ namespace jacdac { } export const enum TCPCmd { - /** Argument: inbound pipe (bytes). Open pair of pipes between network peripheral and a controlling device. In/outbound refers to direction from/to internet. */ + /** + * Argument: inbound pipe (bytes). Open pair of pipes between network peripheral and a controlling device. In/outbound refers to direction from/to internet. + */ Open = 0x80, } export const enum TCPPipeCmd { - // const [tcpPort] = buf.unpack("H") - // const hostname = buf.slice(2).toString() /** * Open an SSL connection to a given host:port pair. Can be issued only once on given pipe. * After the connection is established, an empty data report is sent. * Connection is closed by closing the pipe. + * + * ``` + * const [tcpPort] = buf.unpack("H") + * const hostname = buf.slice(2).toString() + * ``` */ OpenSsl = 0x1, - /** Argument: error TcpError (int32_t). Reported when an error is encountered. Negative error codes come directly from the SSL implementation. */ + /** + * Argument: error TcpError (int32_t). Reported when an error is encountered. Negative error codes come directly from the SSL implementation. + */ Error = 0x0, } @@ -1069,7 +1443,9 @@ namespace jacdac { // Service: Temperature export const SRV_TEMPERATURE = 0x1421bac7 export const enum TemperatureReg { - /** Read-only °C u22.10 (uint32_t). The temperature. */ + /** + * Read-only °C u22.10 (uint32_t). The temperature. + */ Temperature = 0x101, } @@ -1093,34 +1469,54 @@ namespace jacdac { } export const enum WifiCmd { - /** Argument: results pipe (bytes). Initiate search for WiFi networks. Results are returned via pipe, one entry per packet. */ + /** + * Argument: results pipe (bytes). Initiate search for WiFi networks. Results are returned via pipe, one entry per packet. + */ Scan = 0x80, - // const ssid = string0(buf, 0, 0) - // const password = string0(buf, 0, 1) - /** Connect to named network. */ + /** + * Connect to named network. + * + * ``` + * const ssid = string0(buf, 0, 0) + * const password = string0(buf, 0, 1) + * ``` + */ Connect = 0x81, - /** No args. Disconnect from current WiFi network if any. */ + /** + * No args. Disconnect from current WiFi network if any. + */ Disconnect = 0x82, } - // pipe_report Results - // const [flags, reserved, rssi, channel] = buf.unpack("LLbB") - // const bssid = buf.slice(10, 6) - // const ssid = buf.slice(16).toString() + + /** + * pipe_report Results + * ``` + * const [flags, reserved, rssi, channel] = buf.unpack("LLbB") + * const bssid = buf.slice(10, 6) + * const ssid = buf.slice(16).toString() + * ``` + */ export const enum WifiReg { - /** Read-only bool (uint8_t). Indicates whether or not we currently have an IP address assigned. */ + /** + * Read-only bool (uint8_t). Indicates whether or not we currently have an IP address assigned. + */ Connected = 0x180, } export const enum WifiEvent { - /** Emitted upon successful join and IP address assignment. */ + /** + * Emitted upon successful join and IP address assignment. + */ GotIp = 0x1, - /** Emitted when disconnected from network. */ + /** + * Emitted when disconnected from network. + */ LostIp = 0x2, } diff --git a/switchclient.ts b/switchclient.ts index ddf7ad12f..46662df05 100644 --- a/switchclient.ts +++ b/switchclient.ts @@ -2,7 +2,7 @@ namespace jacdac { //% fixedInstances export class SwitchClient extends SensorClient { constructor(requiredDevice: string = null) { - super("switch", jd_class.SWITCH, requiredDevice); + super("switch", SRV_SWITCH, requiredDevice); } /** @@ -23,7 +23,7 @@ namespace jacdac { */ //% blockId=jacdacswitchonevent block="jacdac %switch on %event" //% group="Switch" - onEvent(event: JDSwitchDirection, handler: () => void) { + onEvent(event: SwitchDirection, handler: () => void) { this.registerEvent(event, handler); } } diff --git a/wificlient.ts b/wificlient.ts index fd41f7793..4a9b68795 100644 --- a/wificlient.ts +++ b/wificlient.ts @@ -29,7 +29,7 @@ namespace jacdac { } handlePacket(p: JDPacket) { - if (p.service_command == CMD_EVENT) { + if (p.service_command == SystemCmd.Event) { switch (p.data[0]) { case EV_GOT_IP: this.gotIP = true