use jdpack as much as possible (#35)

* use jdpack as much as possible

* updated brightness

* a few more cleanups
This commit is contained in:
Peli de Halleux 2021-02-11 07:56:46 +01:00 коммит произвёл GitHub
Родитель 74e2cc8e85
Коммит c3b0113c91
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
35 изменённых файлов: 49 добавлений и 1248 удалений

Просмотреть файл

@ -1,6 +1,6 @@
namespace modules {
//% fixedInstances
export class AccelerometerClient extends jacdac.BufferedSensorClient<number[]> {
export class AccelerometerClient extends jacdac.BufferedSensorClient<[number, number, number]> {
constructor(role: string) {
super(jacdac.SRV_ACCELEROMETER, role);
}
@ -80,5 +80,5 @@ namespace modules {
}
//% fixedInstance whenUsed
export const accelerometer = new AccelerometerClient("acc");
export const accelerometer = new AccelerometerClient("accelerometer");
}

Просмотреть файл

@ -1,31 +1,4 @@
namespace jacdac {
export class ActuatorService extends Host {
state: Buffer;
intensity: number;
constructor(name: string, deviceClass: number, stateLength: number) {
super(name, deviceClass);
this.state = control.createBuffer(stateLength);
this.intensity = 0
}
public handlePacket(packet: JDPacket) {
this.stateUpdated = false
this.intensity = this.handleRegUInt32(packet, SystemReg.Intensity, this.intensity)
this.state = this.handleRegBuffer(packet, SystemReg.Value, this.state)
if (this.stateUpdated)
this.handleStateChanged();
else
this.handleCustomCommand(packet)
}
protected handleCustomCommand(pkt: JDPacket): void { }
protected handleStateChanged(): void { }
}
export class ActuatorClient extends Client {
protected state: Buffer;

Просмотреть файл

@ -40,5 +40,5 @@ namespace modules {
}
//% fixedInstance whenUsed
export const button = new ButtonClient("btn");
export const button = new ButtonClient("button");
}

Просмотреть файл

@ -1,15 +0,0 @@
namespace jacdac {
// Service: CODAL Message Bus
export const SRV_CODAL_MESSAGE_BUS = 0x16ad7cd5
export const enum CodalMessageBusCmd {
/**
* Sends a new event on the message bus.
*
* ```
* const [id, event] = jdunpack<[number, number]>(buf, "u16 u16")
* ```
*/
Send = 0x80,
}
}

Просмотреть файл

@ -1,59 +0,0 @@
namespace jacdac {
// Service: LED Matrix Controller
export const SRV_LED_MATRIX_CONTROLLER = 0x1d35e393
export const enum LedMatrixControllerReg {
/**
* Read-write bytes. Read or writes the state of the screen where pixel on/off state is
* stored as a bit, column by column. The column should be byte aligned.
*
* ```
* const [leds] = jdunpack<[Buffer]>(buf, "b")
* ```
*/
Leds = 0x80,
/**
* Read-write bool (uint8_t). Disables or enables the whole screen.
*
* ```
* const [enabled] = jdunpack<[number]>(buf, "u8")
* ```
*/
Enabled = 0x81,
/**
* Read-write uint8_t. Sets the general brightness of the LEDs.
*
* ```
* const [brightness] = jdunpack<[number]>(buf, "u8")
* ```
*/
Brightness = 0x82,
/**
* Constant # uint16_t. Number of rows on the screen
*
* ```
* const [rows] = jdunpack<[number]>(buf, "u16")
* ```
*/
Rows = 0x83,
/**
* Constant # uint16_t. Number of columns on the screen
*
* ```
* const [columns] = jdunpack<[number]>(buf, "u16")
* ```
*/
Columns = 0x84,
}
export const enum LedMatrixControllerCmd {
/**
* No args. Shorthand command to clear all the LEDs on the screen.
*/
Clear = 0x80,
}
}

Просмотреть файл

@ -1,16 +0,0 @@
namespace jacdac {
// Service: LED Matrix Display
export const SRV_LED_MATRIX_DISPLAY = 0x110d154b
export const enum LedMatrixDisplayReg {
/**
* Read-only bytes. Streams the state of the screen where pixel on/off state is
* stored as a bit, column by column. The column should be byte aligned.
*
* ```
* const [leds] = jdunpack<[Buffer]>(buf, "b")
* ```
*/
Leds = 0x101,
}
}

Просмотреть файл

@ -1,9 +1,9 @@
namespace modules {
//% fixedInstances
//% blockGap=8
export class LightClient extends jacdac.Client {
export class LedPixelClient extends jacdac.Client {
constructor(role: string) {
super(jacdac.SRV_LIGHT, role);
super(jacdac.SRV_LED_PIXEL, role);
}
_length = 10
@ -17,11 +17,11 @@ namespace modules {
//% weight=0
//% numpixels.min=0
//% numpixels.defl=30
configure(numpixels: number, type = jacdac.LightLightType.WS2812B_GRB, maxpower = 500): void {
configure(numpixels: number, type = jacdac.LedPixelLightType.WS2812B_GRB, maxpower = 500): void {
this._length = numpixels >> 0;
this.setRegInt(jacdac.LightReg.NumPixels, this._length)
this.setRegInt(jacdac.LightReg.LightType, type)
this.setRegInt(jacdac.LightReg.MaxPower, maxpower)
this.setReg(jacdac.LedPixelReg.NumPixels, "u16", [this._length])
this.setReg(jacdac.LedPixelReg.LightType, "u8", [type])
this.setReg(jacdac.LedPixelReg.MaxPower, "u16", [maxpower])
}
/**
@ -33,18 +33,19 @@ namespace modules {
//% weight=2 blockGap=8
//% group="Light"
setBrightness(brightness: number): void {
this.setRegInt(jacdac.LightReg.Brightness, brightness)
// jacdac expects brightness between 0...1, MakeCode usually uses 0..255
this.setReg(jacdac.LedPixelReg.Brightness, "u0.8", [brightness / 0xff])
}
runProgram(prog: Buffer) {
this.currAnimation++
this.sendCommandWithAck(jacdac.JDPacket.from(jacdac.LightCmd.Run, prog))
this.sendCommandWithAck(jacdac.JDPacket.from(jacdac.LedPixelCmd.Run, prog))
}
runEncoded(prog: string, args?: number[]) {
if (!args) args = []
this.currAnimation++
this.sendCommand(jacdac.JDPacket.from(jacdac.LightCmd.Run, jacdac.lightEncode(prog, args)))
this.sendCommand(jacdac.JDPacket.from(jacdac.LedPixelCmd.Run, jacdac.lightEncode(prog, args)))
}
set(idx: number, rgb: number) {
@ -358,5 +359,5 @@ namespace modules {
}
//% fixedInstance whenUsed
export const light = new LightClient("rgb_pixels");
export const ledPixel = new LedPixelClient("ledPixel");
}

Просмотреть файл

Просмотреть файл

@ -1,7 +1,7 @@
{
"name": "jacdac-light",
"name": "jacdac-ledpixel",
"version": "0.3.0",
"description": "MakeCode support for JACDAC Light service",
"description": "MakeCode support for JACDAC LED pixel",
"dependencies": {
"core": "*",
"jacdac": "github:microsoft/pxt-jacdac"

Просмотреть файл

@ -1,26 +1,26 @@
namespace modules {
//% fixedInstances
export class MonoLightAnimation {
export class LEDAnimation {
constructor(public buffer: Buffer) { }
}
export namespace mono {
export namespace ledAnimations {
//% fixedInstance whenUsed
//% block="slow glow"
export const slowGlow = new MonoLightAnimation(hex`000f dc05 ffff dc05 000f 0100`)
export const slowGlow = new LEDAnimation(hex`000f dc05 ffff dc05 000f 0100`)
//% fixedInstance whenUsed
//% block="stable"
export const stable = new MonoLightAnimation(hex`ffff e803 ffff 0000`)
export const stable = new LEDAnimation(hex`ffff e803 ffff 0000`)
//% fixedInstance whenUsed
//% block="blink"
export const blink = new MonoLightAnimation(hex`ffff f401 ffff 0100 0000 fd01`)
export const blink = new LEDAnimation(hex`ffff f401 ffff 0100 0000 fd01`)
}
//% fixedInstances
//% blockGap=8
export class MonoLightClient extends jacdac.Client {
export class LEDClient extends jacdac.Client {
constructor(role: string) {
super(jacdac.SRV_MONO_LIGHT, role);
super(jacdac.SRV_LED, role);
}
// set to negative for infinity
@ -28,7 +28,8 @@ namespace modules {
numIters |= 0
if (numIters < 0 || numIters >= 0xffff) numIters = 0xffffffff
else if (numIters) numIters--
this.setRegInt(jacdac.MonoLightReg.MaxIterations, numIters)
// this.setReg(jacdac.LedReg.MaxIterations, numIters)
throw "TODO"
}
/**
@ -40,7 +41,7 @@ namespace modules {
//% brightness.max=255
//% group="Mono Light"
setBrightness(brightness: number): void {
this.setRegInt(jacdac.MonoLightReg.Brightness, brightness << 8)
this.setReg(jacdac.LedReg.Brightness, "u0.16", [brightness])
}
/**
@ -48,7 +49,7 @@ namespace modules {
*/
//% blockId=jacdacmonolightshowanimation block="%monoLight show $animation animation"
//% group="Mono Light"
showAnimation(animation: MonoLightAnimation, speed = 100) {
showAnimation(animation: LEDAnimation, speed = 100) {
const anim = animation.buffer.slice()
if (speed != 100) {
for (let i = 0; i < anim.length; i += 4) {
@ -58,10 +59,10 @@ namespace modules {
anim.setNumber(NumberFormat.UInt16LE, i + 2, adj)
}
}
this.setRegBuffer(jacdac.MonoLightReg.Steps, anim)
this.setRegBuffer(jacdac.LedReg.Steps, anim)
}
}
//% fixedInstance whenUsed
export const monoLight = new MonoLightClient("mono_light");
export const led = new LEDClient("led");
}

Просмотреть файл

@ -1,7 +1,7 @@
{
"name": "jacdac-mono-light",
"name": "jacdac-led",
"version": "0.3.0",
"description": "MakeCode support for JACDAC Mono Light service",
"description": "MakeCode support for JACDAC LED service",
"dependencies": {
"core": "*",
"jacdac": "github:microsoft/pxt-jacdac"

Просмотреть файл

@ -1,73 +0,0 @@
namespace jacdac {
//% fixedInstances
export class ColorSensorClient extends SensorClient {
constructor(role: string) {
super("cols", jd_class.COLOR_SENSOR, role);
}
/**
* Uses a color sensor to capture the ambient color as a RGB value.
*/
//% blockId=jdsensor_lightcolor block="%colorsensor light color"
//% group="Color Sensor"
lightColor(): number {
const s = this.state;
if (!s || s.length < 4) return 0;
return s.getNumber(NumberFormat.UInt32LE, 0);
}
/**
* Returns the hue of the color
*/
lightHue(): number {
const c = this.lightColor();
const h = ColorSensorClient.mapRgbToColor(c);
console.log(`color ${c} -> ${h}`)
return h;
}
private static mapRgbToColor(col: number): number {
const r = ((col >> 16) & 0xff) / 255;
const g = ((col >> 8) & 0xff) / 255;
const b = ((col) & 0xff) / 255;
const cmax = Math.max(r, Math.max(g, b));
const cmin = Math.min(r, Math.min(g, b));
const c = cmax - cmin;
let hue: number;
if (c == 0) {
hue = 0;
} else {
switch (cmax) {
case r: {
const segment = (g - b) / c;
let shift = 0 / 60; // R° / (360° / hex sides)
if (segment < 0) { // hue > 180, full rotation
shift = 360 / 60; // R° / (360° / hex sides)
}
hue = segment + shift;
break;
}
case g: {
const segment = (b - r) / c;
const shift = 120 / 60; // G° / (360° / hex sides)
hue = segment + shift;
break;
}
case b: {
const segment = (r - g) / c;
const shift = 240 / 60; // B° / (360° / hex sides)
hue = segment + shift;
break;
}
}
}
hue = hue / 0.6 * 255; // hue is in [0,6], scale it up
return hue | 0;
}
}
//% fixedInstance whenUsed block="color sensor"
export const colorSensorClient = new ColorSensorClient();
}

Просмотреть файл

@ -1,100 +0,0 @@
enum JDGamepadButton {
//% enumval=0
B = 0,
//% enumval=1
A = 1,
//% enumval=2
Y = 2,
//% enumval=3
X = 3,
//% block="left bumper"
//% enumval=4
LeftBumper = 4,
//% block="right bumper"
//% enumval=5
RightBumper = 5,
//% block="left trigger"
//% enumval=6
LeftTrigger = 6,
//% block="right trigger"
//% enumval=7
RightTrigger = 7,
//% block="select"
//% enumval=8
Select = 8,
//% block="start"
//% enumval=9
Start = 9,
//% block="left stick"
//% enumval=10
LeftStick = 10,
//% block="right stick"
//% enumval=11
RightStick = 11,
//% block="up"
//% enumval=12
Up = 12,
//% block="down"
//% enumval=13
Down = 13,
//% block="left"
//% enumval=14
Left = 14,
//% block="right"
//% enumval=15
Right = 15
}
namespace jacdac {
/**
* Maps to a standard layout button to the button index
* @param button the name of the button
*/
//% blockId=jdjoystickStandardButton block="%button"
//% shim=TD_ID blockHidden=1
export function gamepadButton(button: JDGamepadButton): number {
return button;
}
//% fixedInstances
export class GamepadClient extends Client {
constructor(role: string) {
super("gpad", jd_class.GAMEPAD, role);
}
/**
* Sets the button state to down
*/
//% blockId=jdjoystickSetButton block="%gamepad button %index=jdjoystickStandardButton|%down=toggleDownUp"
//% weight=100 group="Gamepad"
setButton(index: number, down: boolean): void {
this.sendPackedCommand(JDGamepadCommand.Button, "Bb", [index, down ? 1 : 0])
}
/**
* Sets the current move on the gamepad
**/
//% blockId=gamepadMove block="%gamepad %index|move by x %x|y %y"
//% help=gamepad/move
//% index.min=0 index.max=1
//% blockGap=8 group="Gamepad"
move(index: number, x: number, y: number): void {
this.sendPackedCommand(JDGamepadCommand.Move, "Bbb", [index, x, y])
}
/**
* Sets the throttle state
*/
//% blockId=gamepadSetThrottle block="%gamepad set throttle %index|to %value"
//% gamepad/set-throttle blockHidden=1
//% index.min=0 index.max=1
//% value.min=0 value.max=31
//% group="Gamepad"
setThrottle(index: number, value: number): void {
this.sendPackedCommand(JDGamepadCommand.Throttle, "Bb", [index, value])
}
}
//% fixedInstance whenUsed block="gamepad client"
export const gamepadClient = new GamepadClient();
}

Просмотреть файл

@ -1,154 +0,0 @@
enum JDKeyboardMediaKey {
//% block="mute"
Mute = 0,
//% block="volume up"
VolumeUp = 1,
//% block="volume down"
VolumeDown = 2,
//% block="play pause"
PlayPause = 3,
//% block="stop"
Stop = 4,
//% block="previous track"
PreviousTrack = 5,
//% block="next track"
NextTrack = 6,
//% block="mail"
Mail = 7,
//% block="calculator"
Calculator = 8,
//% block="web search"
WebSearch = 9,
//% block="web home"
WebHome = 10,
//% block="web favourites"
WebFavourites = 11,
//% block="web refresh"
WebRefresh = 12,
//% block="web stop"
WebStop = 13,
//% block="web forward"
WebForward = 14,
//% block="web back"
WebBack = 15,
}
enum JDKeyboardFunctionKey {
//% block="F1"
F1Key = 0,
//% block="F2"
F2Key = 1,
//% block="F3"
F3Key = 2,
//% block="F4"
F4Key = 3,
//% block="F5"
F5Key = 4,
//% block="F6"
F6Key = 5,
//% block="F7"
F7Key = 6,
//% block="F8"
F8Key = 7,
//% block="F9"
F9Key = 8,
//% block="F0"
F10Key = 9,
//% block="F11"
F11Key = 10,
//% block="F12"
F12Key = 11,
//% block="print screen"
PrintScreen = 12,
//% block="scroll lock"
ScrollLock = 13,
//% block="pause"
Pause = 14,
//% block="insert"
Insert = 15,
//% block="home"
Home = 16,
//% block="page up"
PageUp = 17,
//% block="delete"
DeleteForward = 18,
//% block="end"
End = 19,
//% block="page down"
PageDown = 20,
//% block="right arrow"
RightArrow = 21,
//% block="left arrow"
LeftArrow = 22,
//% block="down arrow"
DownArrow = 23,
//% block="up arrow"
UpArrow = 24,
}
enum JDKeyboardKeyEvent {
//% block="press"
Press = 0,
//% block="up"
Up = 1,
//% block="down"
Down = 2,
}
namespace jacdac {
//% fixedInstances
export class KeyboardClient extends Client {
constructor(role: string) {
super("keyb", SRV_KEYBOARD, role);
}
/**
* Sends a sequence of keystrokes to the keyboard
*/
//% blockId=jdkeyboardType block="%keyboard type %text"
//% blockGap=8 weight=100
//% text.shadowOptions.toString=true
//% group="Keyboard"
type(type: string) {
const bufs = Buffer.chunkedFromUTF8(type, JD_SERIAL_MAX_PAYLOAD_SIZE)
for (let buf of bufs)
this.sendCommand(JDPacket.from(JDKeyboardCommand.Type, buf))
}
/**
* Sends a key command
*/
//% blockId=jdkeyboardStandardKey block="%keyboard key %key|%event"
//% blockGap=8 weight=99
//% group="Keyboard"
key(key: string, event: JDKeyboardKeyEvent) {
this.sendPackedCommand(JDKeyboardCommand.Key, "HH", [event, key.charCodeAt(0)])
}
/**
* Sends a media key command
*/
//% blockId=jdkeyboardMediaKey block="%keyboard media key %key|%event"
//% blockGap=8
//% group="Keyboard"
mediaKey(key: JDKeyboardMediaKey, event: JDKeyboardKeyEvent) {
this.sendPackedCommand(JDKeyboardCommand.MediaKey, "HH", [event, key])
}
/**
*
*/
//% blockId=keyboardFunctionKey block="%keyboard function key %key|%event"
//% blockGap=8
//% group="Keyboard"
functionKey(key: JDKeyboardFunctionKey, event: JDKeyboardKeyEvent) {
this.sendPackedCommand(JDKeyboardCommand.FunctionKey, "HH", [event, key])
}
}
//% fixedInstance whenUsed block="keyboard client"
export const keyboardClient = new KeyboardClient();
}

Просмотреть файл

@ -1,102 +0,0 @@
namespace jacdac {
const enum JDLCDFlags {
None,
Display = 1 << 0,
Blink = 1 << 1,
Cursor = 1 << 2
}
//% fixedInstances
export class LCDClient extends ActuatorClient {
constructor(role: string) {
super("lcd", jd_class.LCD, 17, role);
this.setDisplay(true);
}
/**
* Shows a string on the LCD screen
* @param text the text to show
*/
//% blockId=jdlcdshowstring block="%lcd show string %text"
//% group="LCD" blockGap=8
showString(text: string) {
// test for change
const n = text.length;
let changed = false;
for (let i = 1; i < this.state.length; ++i) {
const c = i < n ? text.charCodeAt(i) : 0;
changed = changed || this.state[i] != c;
this.state[i] = c;
}
if (changed)
this.notifyChange();
}
/**
* Shows a number on the LCD screen
* @param value the number to show
*/
//% blockId=jdlcdshownumber block="%lcd show number %value"
//% group="LCD" blockGap=8
showNumber(value: number) {
this.showString(value.toString());
}
/**
* Clears the screen
*/
//% blockId=jdlcdclear block="clear %lcd"
//% group="LCD" blockGap=8
clear() {
this.showString("");
}
private setFlag(flag: JDLCDFlags, enabled: boolean) {
if (!!(this.state[0] & flag) == enabled) return;
if (enabled)
this.state[0] = this.state[0] | flag;
else
this.state[0] = ~(~this.state[0] | flag);
this.notifyChange();
}
/**
* Enables or disables display
* @param enabled true to turn the display on; false otherwise
*/
//% blockId=jdlcdsetdisplay block="set %lcd display %enabled"
//% enabled.shadow=toggleOnOff
//% group="LCD" blockGap=8
setDisplay(enabled: boolean) {
this.setFlag(JDLCDFlags.Display, enabled);
}
/**
* Enables or disables blinking
* @param enabled true to blink
*/
//% blockId=jdlcdsetblink block="set %lcd blink %enabled"
//% enabled.shadow=toggleOnOff
//% group="LCD" blockGap=8
setBlink(enabled: boolean) {
this.setFlag(JDLCDFlags.Blink, enabled);
}
/**
* Show or hide cursor
* @param enabled true to display cursor, false otherwise
*/
//% blockId=jdlcdsetcursor block="set %lcd cursor %enabled"
//% enabled.shadow=toggleOnOff
//% group="LCD" blockGap=8
setCursor(enabled: boolean) {
this.setFlag(JDLCDFlags.Cursor, enabled);
}
}
/**
* A character LCD client
*/
//% fixedInstance whenUsed block="lcd client"
export const lcdClient = new LCDClient();
}

Просмотреть файл

@ -1,51 +0,0 @@
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(role: string) {
super("lis", jd_class.LIGHT_SENSOR, role);
}
/**
* Reads the current x value from the sensor
*/
//% blockId=jacdaclightsensorlevel block="%lightsensor light level"
//% group="Light sensor"
get lightLevel(): number {
const s = this.state;
if (!s || s.length < 1) return 0;
return s.getNumber(NumberFormat.UInt8LE, 0);
}
/**
* Runs code when an event happens on the sensor
* @param gesture
* @param handler
*/
//% blockId=jacadaclightsensoronevent block="on %lightSensor %event"
//% group="Light sensor"
onEvent(event: JDLightCondition, handler: () => void) {
this.registerEvent(event, handler);
}
/**
* Sets the threshold value for the event
* @param level
* @param value
*/
//% blockId=jacdaclightsetthrshold block="%lightsensor set threshold %level to %value"
//% group="Light sensor"
setLightConditionThreshold(level: JDLightCondition, value: number) {
this.setThreshold(level == JDLightCondition.Dark, value);
}
}
//% fixedInstance whenUsed block="light sensor client"
export const lightSensorClient = new LightSensorClient();
}

Просмотреть файл

@ -1,69 +0,0 @@
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(role: string) {
super("lspec", jd_class.LIGHT_SPECTRUM_SENSOR, role);
}
/**
* Reads the full spectrum
*/
//% blockId=jdlightspectrumfull block="%lightSpectrumSensor full"
//% group="Light spectrum sensor"
get full(): number {
const s = this.state;
if (!s || s.length < 6) return -1;
return s.getNumber(NumberFormat.UInt16LE, 0);
}
/**
* Reads the full spectrum
*/
//% blockId=jdlightspectruminfrared block="%lightSpectrumSensor infrared"
//% group="Light spectrum sensor"
get infrared(): number {
const s = this.state;
if (!s || s.length < 6) return -1;
return s.getNumber(NumberFormat.UInt16LE, 2);
}
/**
* Reads the full spectrum
*/
//% blockId=jdlightspectrumvisible block="%lightSpectrumSensor visible"
//% group="Light spectrum sensor"
get visible(): number {
const s = this.state;
if (!s || s.length < 6) return -1;
return s.getNumber(NumberFormat.UInt16LE, 4);
}
/**
* Runs code when an event happens on the sensor
* @param gesture
* @param handler
*/
//% blockId=jacadaclightsensorspectrumonevent block="on %lightSpectrumSensor %event"
//% group="Light sensor"
onEvent(event: JDLightSpectrumEvent, handler: () => void) {
this.registerEvent(event, handler);
}
}
//% fixedInstance whenUsed block="light spectrum sensor client"
export const lightSpectrumSensorClient = new LightSpectrumSensorClient();
}

Просмотреть файл

@ -1,107 +0,0 @@
namespace jacdac {
// events are send with this device ID
export const JD_MESSAGE_BUS_ID = 2000;
/**
* A driver that listens for message bus events
*/
export class MessageBusService extends Broadcast {
suppressForwarding: boolean;
static NAME = "bus";
constructor() {
super(MessageBusService.NAME, jd_class.MESSAGE_BUS);
this.suppressForwarding = false;
}
raiseEvent(id: number, value: number) {
this.start();
this.sendReport(
JDPacket.jdpacked(CMD_EVENT, "u32 u32", [id, value]))
}
broadcastEvent(id: number, value: number) {
this.start();
//control.dmesg(`jd> msgbus> listen event ${id} ${value}`)
control.onEvent(id, value, () => {
if (this.suppressForwarding) return;
this.raiseEvent(id, value);
})
}
handlePacket(packet: JDPacket) {
if (packet.serviceCommand == CMD_EVENT) {
const [id, value] = jdunpack<[number, number]>(packet.data, "u32 u32")
this.suppressForwarding = true;
control.raiseEvent(id, value);
this.suppressForwarding = false;
}
}
}
//% fixedInstance whenUsed block="message bus service"
export const messageBusService = new MessageBusService();
/**
* Pipes specific events through JACDAC
*/
//% block="broadcast events|from %src|with value %value" weight=5
//% group="Control"
export function broadcastEvent(src: number, value: number) {
messageBusService.broadcastEvent(src, value);
}
/**
* Gets the message code
*/
//% blockHidden=1 shim=ENUM_GET
//% blockId=jacdacMessageCode block="%msg" enumInitialMembers="message1"
//% enumName=JacDacMessage enumMemberName=msg enumPromptHint="e.g. Start, Stop, Jump..."
//% group="Broadcast"
//% enumIsHash
export function __message(msg: number): number {
return msg;
}
/**
* Sends an event over JacDac
* @param id
* @param value
*/
//% blockid=jacdacraisevent
//% block="raise event|from %src|with value %value" weight=5
//% group="Control"
export function raiseEvent(src: number, value: number) {
messageBusService.raiseEvent(src, value);
}
/**
* Broadcasts a message over JacDac
* @param msg
*/
//% blockId=jacdacBroadcastMessage block="send $msg"
//% msg.shadow=jacdacMessageCode draggableParameters
//% weight=200
//% blockGap=8
//% help=jacdac/send-message
//% group="Broadcast"
export function sendMessage(msg: number): void {
// 0 is MICROBIT_EVT_ANY, shifting by 1
messageBusService.raiseEvent(JD_MESSAGE_BUS_ID, msg + 1);
}
/**
* Registers code to run for a particular message
* @param msg
* @param handler
*/
//% blockId=jacdacOnMessageReceived block="on $msg received"
//% msg.shadow=jacdacMessageCode draggableParameters
//% weight=199
//% help=jacdac/on-received-message
//% group="Broadcast"
export function onReceivedMessage(msg: number, handler: () => void) {
messageBusService.start();
control.onEvent(JD_MESSAGE_BUS_ID, msg + 1, handler);
}
}

Просмотреть файл

@ -1,52 +0,0 @@
const enum JDMouseButton {
//% block="right" enumval=1
Right = 0x01,
//% block="middle" enumval=4
Middle = 0x04,
//% block="left" enumval=2
Left = 0x02,
}
namespace jacdac {
//% fixedInstances
export class MouseClient extends Client {
constructor(role: string) {
super("mous", SRV_MOUSE, role);
}
/**
* Sets the mouse button state to down
*/
//% blockId=jdmouseSetButton block="%mouse button %index|%down=toggleDownUp"
//% group="Mouse"
setButton(button: MouseButton, down: boolean): void {
this.sendPackedCommand(MouseCmd.SetButton, "BB", [button, down ? 1 : 0])
}
/**
* Moves the mouse
**/
//% help=mouse/move
//% blockId=mouseMove block="%mouse move x %x|y %y"
//% x.min=-128 x.max=127
//% y.min=-128 y.max=127
//% group="Mouse"
move(x: number, y: number): void {
this.sendPackedCommand(MouseCmd.Move, "bb", [x, y])
}
/**
* Moves the mouse
**/
//% help=mouse/wheel
//% blockId=mouseWheel block="%mouse turn wheel %w"
//% w.min=-128 w.max=127
//% group="Mouse"
turnWheel(w: number): void {
this.sendPackedCommand(MouseCmd.Wheel, "b", [w])
}
}
//% fixedInstance whenUsed block="mouse client"
export const mouseClient = new MouseClient();
}

Просмотреть файл

@ -1,39 +0,0 @@
namespace jacdac {
//% fixedInstances
export class PixelClient extends ActuatorClient {
constructor(role: string) {
super("pixel", jd_class.PIXEL, 4, role);
}
/**
* Set the brightness of the neopixel. This flag only applies to future operations.
* @param brightness a measure of LED brightness in 0-255. eg: 20
*/
//% blockId="jacdacpixelsetbrightess" block="set %pixel brightness %brightness"
//% weight=98
//% brightness.min=0 brightness.max=255
//% group="Pixel"
setBrightness(value: number) {
this.state.setNumber(NumberFormat.UInt8LE, 0, value & 0xff);
this.notifyChange();
}
/**
* Set the on-board pixel to a given color.
* @param color RGB color of the LED
*/
//% blockId="jadacpixelsetcolor" block="set %pixel color %rgb=colorNumberPicker"
//% weight=99
//% blockGap=8
//% group="Pixel"
setColor(value: number) {
this.state.setNumber(NumberFormat.UInt8BE, 1, (value >> 16) & 0xff)
this.state.setNumber(NumberFormat.UInt8BE, 2, (value >> 8) & 0xff)
this.state.setNumber(NumberFormat.UInt8BE, 3, (value >> 0) & 0xff)
this.notifyChange();
}
}
//% fixedInstance whenUsed block="pixel client"
export const pixelClient = new PixelClient();
}

Просмотреть файл

@ -1,39 +0,0 @@
namespace jacdac {
const enum JDPromixityEvent {
Close = DAL.LEVEL_THRESHOLD_LOW,
Far = DAL.LEVEL_THRESHOLD_HIGH
}
//% fixedInstances
export class ProximityClient extends SensorClient {
constructor(role: string) {
super("proxi", jd_class.PROXIMITY, role);
}
/**
* Gets the distance measure by the sensor. Negative if missing
*/
//% blockId=jdproximtitydistance block="%proximity distance"
//% group="Promixity"
get distance(): number {
const s = this.state;
if (!s || s.length < 4) return -1;
return (s.getNumber(NumberFormat.UInt32LE, 0) / 10);
}
/**
* Runs code when an event happens on the sensor
* @param gesture
* @param handler
*/
//% blockId=jdproximityevent block="on %proximity %event"
//% group="Promixity"
onEvent(event: JDPromixityEvent, handler: () => void) {
this.registerEvent(event, handler);
}
}
//% fixedInstance whenUsed
export const proximityClient = new ProximityClient();
}

Просмотреть файл

@ -1,35 +0,0 @@
namespace jacdac {
//% fixedInstances
export class RGBLEDClient extends Client {
constructor(role: string) {
super("RGBLED", jd_class.RGB_LED, role);
}
/**
* Set the brightness of the strip. This flag only applies to future operation.
* @param brightness a measure of LED brightness in 0-255. eg: 20
*/
//% blockId="jdrgbled_set_brightness" block="set %strip brightness %brightness"
//% brightness.min=0 brightness.max=255
//% weight=2 blockGap=8
//% group="Light"
setBrightness(brightness: number): void {
this.setRegInt(REG_INTENSITY, brightness)
}
/**
* Set the colour of the RGB led in hex format.
*
* Upper most byte is red, middle byte green, lower byte blue.
*/
//% blockId="jdrgbled_set_color" block="set %strip color %colorcode"
//% brightness.min=0 brightness.max=255
//% weight=2 blockGap=8
//% group="RGBLED"
setColor(colorCode: number): void {
this.sendCommand(JDPacket.jdpacked(JDRGBLEDCommand.SetColor, "u32", [colorCode]))
}
}
//% fixedInstance whenUsed block="light client"
export const rgbledClient = new RGBLEDClient();
}

Просмотреть файл

@ -1,33 +0,0 @@
namespace jacdac {
//% fixedInstances
export class SwitchClient extends SensorClient {
constructor(role: string) {
super("switch", SRV_SWITCH, role);
}
/**
* Reads the current x value from the sensor
*/
//% blockId=jacdacswitchright block="%switch right"
//% group="Switch"
right(): boolean {
const s = this.state;
if (!s || s.length < 1) return false;
return !!s.getNumber(NumberFormat.UInt8LE, 0);
}
/**
* Runs code when an event happens on the sensor
* @param gesture
* @param handler
*/
//% blockId=jacdacswitchonevent block="on %switch %event"
//% group="Switch"
onEvent(event: SwitchDirection, handler: () => void) {
this.registerEvent(event, handler);
}
}
//% fixedInstance whenUsed block="switch client"
export const switchClient = new SwitchClient();
}

Просмотреть файл

@ -1,72 +0,0 @@
namespace jacdac {
//% fixedInstances
export class TouchButtonClient extends SensorClient {
constructor(role: string) {
super("touch", jd_class.TOUCHBUTTON, role);
}
/**
* Reads the current x value from the sensor
*/
//% blockId=jacadactouchispressed block="%button value"
//% group="Touch"
value(): number {
const s = this.state;
if (!s || s.length < 2) return -1;
return s.getNumber(NumberFormat.UInt16LE, 0);
}
/**
* Runs code when an event happens on the sensor
* @param gesture
* @param handler
*/
//% blockId=jacadactouchonevent block="on %button %event"
//% group="Touch"
onEvent(event: JDButtonEvent, handler: () => void) {
this.registerEvent(event, handler);
}
}
//% fixedInstance whenUsed block="touch button client"
export const touchButtonClient = new TouchButtonClient("touch");
/**
* A client of multiple buttons
*/
export class TouchButtonsClient extends SensorClient {
constructor(role: string) {
super("mtouch", jd_class.TOUCH_BUTTONS, role);
}
/**
* Reads the current x value from the sensor
*/
//% blockId=jdtoubhbuttonsvalue block="%button value"
//% group="Touch"
value(index: number): number {
const s = this.state;
if (!s || s.length + 1 < 2 * index) return -1;
return s.getNumber(NumberFormat.UInt16LE, index * 2);
}
/**
* Runs code when an event happens on the sensor
* @param gesture
* @param handler
*/
//% blockId=jdtouchbuttonsevent block="%touchButton %index on %event"
//% group="Touch"
onEvent(index: number, event: JDButtonEvent, handler: () => void) {
const j = jacdac.BUTTON_EVENTS.indexOf(<number>event);
if (j > -1) {
const k = DAL.ACCELEROMETER_EVT_SHAKE + 1
+ index * jacdac.BUTTON_EVENTS.length + j;
this.registerEvent(k, handler);
}
}
}
//% fixedInstance whenUsed block="touch buttons client"
export const touchButtonsClient = new TouchButtonsClient();
}

Просмотреть файл

@ -1,87 +0,0 @@
namespace jacdac {
// Service: Light
export const SRV_LIGHT = 0x126f00e0
export const enum LightLightType { // uint8_t
WS2812B_GRB = 0x0,
APA102 = 0x10,
SK9822 = 0x11,
}
export const enum LightReg {
/**
* Read-write ratio uint8_t. Set the luminosity of the strip.
* At `0` the power to the strip is completely shut down.
*
* ```
* const [brightness] = jdunpack<[number]>(buf, "u8")
* ```
*/
Brightness = 0x1,
/**
* Read-only ratio uint8_t. This is the luminosity actually applied to the strip.
* May be lower than `brightness` if power-limited by the `max_power` register.
* It will rise slowly (few seconds) back to `brightness` is limits are no longer required.
*
* ```
* const [actualBrightness] = jdunpack<[number]>(buf, "u8")
* ```
*/
ActualBrightness = 0x180,
/**
* Read-write LightType (uint8_t). Specifies the type of light strip connected to controller.
* Controllers which are sold with lights should default to the correct type
* and could not allow change.
*
* ```
* const [lightType] = jdunpack<[LightLightType]>(buf, "u8")
* ```
*/
LightType = 0x80,
/**
* Read-write uint16_t. Specifies the number of pixels in the strip.
* Controllers which are sold with lights should default to the correct length
* and could not allow change.
* Increasing length at runtime leads to ineffective use of memory and may lead to controller reboot.
*
* ```
* const [numPixels] = jdunpack<[number]>(buf, "u16")
* ```
*/
NumPixels = 0x81,
/**
* Read-write mA uint16_t. Limit the power drawn by the light-strip (and controller).
*
* ```
* const [maxPower] = jdunpack<[number]>(buf, "u16")
* ```
*/
MaxPower = 0x7,
/**
* Constant uint16_t. The maximum supported number of pixels.
* All writes to `num_pixels` are clamped to `max_pixels`.
*
* ```
* const [maxPixels] = jdunpack<[number]>(buf, "u16")
* ```
*/
MaxPixels = 0x181,
}
export const enum LightCmd {
/**
* Argument: program bytes. Run the given light "program". See service description for details.
*
* ```
* const [program] = jdunpack<[Buffer]>(buf, "b")
* ```
*/
Run = 0x81,
}
}

Просмотреть файл

Просмотреть файл

@ -27,7 +27,7 @@ namespace jacdac {
autoInvoke(numSamples = 10) {
this._autoInv = numSamples
this.setRegInt(ModelRunnerReg.AutoInvokeEvery, numSamples)
this.setReg(ModelRunnerReg.AutoInvokeEvery, "u16", [numSamples])
}
handlePacket(pkt: JDPacket) {

Просмотреть файл

@ -1,64 +0,0 @@
namespace jacdac {
// Service: Mono Light
export const SRV_MONO_LIGHT = 0x1fb57453
export const enum MonoLightReg {
/**
* Read-write ratio uint16_t. Set the luminosity of the strip. The value is used to scale `start_intensity` in `steps` register.
* At `0` the power to the strip is completely shut down.
*
* ```
* const [brightness] = jdunpack<[number]>(buf, "u16")
* ```
*/
Brightness = 0x1,
/**
* Read-write mA uint16_t. Limit the power drawn by the light-strip (and controller).
*
* ```
* const [maxPower] = jdunpack<[number]>(buf, "u16")
* ```
*/
MaxPower = 0x7,
/**
* Constant uint8_t. Maximum number of steps allowed in animation definition. This determines the size of the `steps` register.
*
* ```
* const [maxSteps] = jdunpack<[number]>(buf, "u8")
* ```
*/
MaxSteps = 0x180,
/**
* The steps of current animation. Setting this also sets `current_iteration` to `0`.
* Step with `duration == 0` is treated as an end marker.
*
* ```
* const [rest] = jdunpack<[([number, number])[]]>(buf, "r: u16 u16")
* const [startIntensity, duration] = rest[0]
* ```
*/
Steps = 0x82,
/**
* Read-write uint16_t. Currently excecuting iteration of animation. Can be set to `0` to restart current animation.
* If `current_iteration > max_iterations`, then no animation is currently running.
*
* ```
* const [currentIteration] = jdunpack<[number]>(buf, "u16")
* ```
*/
CurrentIteration = 0x80,
/**
* Read-write uint16_t. The animation will be repeated `max_iterations + 1` times.
*
* ```
* const [maxIterations] = jdunpack<[number]>(buf, "u16")
* ```
*/
MaxIterations = 0x81,
}
}

Просмотреть файл

@ -18,10 +18,10 @@ namespace modules {
run(speed: number): void {
speed = Math.clamp(-100, 100, speed)
if (speed == 0)
this.setRegInt(jacdac.MotorReg.Enabled, 0)
this.setReg(jacdac.MotorReg.Enabled, "u8", [0])
else {
this.setRegInt(jacdac.MotorReg.Duty, Math.clamp(-0x7fff, 0x7fff, (speed * 327.67) | 0))
this.setRegInt(jacdac.MotorReg.Enabled, 1)
this.setReg(jacdac.MotorReg.Duty, "u1.15", [Math.clamp(-0x7fff, 0x7fff, (speed * 327.67) | 0)])
this.setReg(jacdac.MotorReg.Enabled, "u8", [1])
}
}
}

Просмотреть файл

@ -374,9 +374,10 @@ namespace jacdac {
}
// this will be re-sent on (re)attach
setRegInt(reg: number, value: number) {
this.start()
this.config.send(JDPacket.jdpacked(CMD_SET_REG | reg, "i32", [value]))
setReg(reg: number, format: string, values: (string | number | Buffer)[]) {
this.start();
const payload = JDPacket.jdpacked(CMD_SET_REG | reg, format, values);
this.config.send(payload);
}
setRegBuffer(reg: number, value: Buffer) {

Просмотреть файл

@ -37,7 +37,7 @@ namespace jacdac {
}
announceCallback() {
this.setRegInt(SensorReg.StreamingSamples, 255)
this.setReg(SensorReg.StreamingSamples, "u8", [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(SensorReg.StreamingInterval, this.samplingInterval)
coll.setRegInt(SensorReg.StreamingSamples, 255)
coll.setReg(SensorReg.StreamingInterval, "u32", [this.samplingInterval])
coll.setReg(SensorReg.StreamingSamples, "u8", [255])
this.collectors.push(coll)
frameSz += coll.lastSample.length
off += entrySize

Просмотреть файл

@ -21,7 +21,7 @@ namespace jacdac {
announceCallback() {
if (this.isStreaming)
this.setRegInt(SystemReg.StreamingSamples, this.isStreaming ? 255 : 0)
this.setReg(SystemReg.StreamingSamples, "u8", [this.isStreaming ? 255 : 0])
}
/**
@ -31,9 +31,9 @@ namespace jacdac {
public setStreaming(on: boolean, interval?: number) {
this.start();
this.isStreaming = on
this.setRegInt(SystemReg.StreamingSamples, this.isStreaming ? 255 : 0)
this.setReg(SystemReg.StreamingSamples, "u8", [this.isStreaming ? 255 : 0])
if (interval != undefined)
this.setRegInt(SystemReg.StreamingInterval, interval)
this.setReg(SystemReg.StreamingInterval, "u32", [interval])
}
/**
@ -72,10 +72,6 @@ namespace jacdac {
protected handleVirtualState(state: Buffer) {
}
protected setThreshold(low: boolean, value: number) {
this.setRegInt(low ? SystemReg.LowThreshold : SystemReg.HighThreshold, value)
}
}
export class BufferedSensorClient<T> extends SensorClient {

Просмотреть файл

@ -5,8 +5,6 @@ namespace jacdac {
export class SensorHost extends Host {
public streamingInterval: number; // millis
public streamingSamples: number;
protected lowThreshold: number
protected highThreshold: number
constructor(name: string, deviceClass: number) {
super(name, deviceClass);
@ -17,8 +15,6 @@ namespace jacdac {
public handlePacket(packet: JDPacket) {
this.log(`hpkt ${packet.serviceCommand}`);
this.stateUpdated = false
this.lowThreshold = this.handleRegInt32(packet, SystemReg.LowThreshold, this.lowThreshold)
this.highThreshold = this.handleRegInt32(packet, SystemReg.HighThreshold, this.highThreshold)
this.streamingInterval = this.handleRegUInt32(packet, SystemReg.StreamingInterval, this.streamingInterval)
const samples = this.handleRegValue(packet, SystemReg.StreamingSamples, "u8", this.streamingSamples)
this.setStreaming(samples)

Просмотреть файл

@ -15,10 +15,10 @@ namespace modules {
if (n === this.pulse)
return
if (n == null) {
this.setRegInt(jacdac.SystemReg.Intensity, 0)
this.setReg(jacdac.ServoReg.Enabled, "u8", [0])
} else {
this.setRegInt(jacdac.SystemReg.Value, n | 0)
this.setRegInt(jacdac.SystemReg.Intensity, 1)
this.setReg(jacdac.ServoReg.Angle, "u8", [n | 0])
this.setReg(jacdac.ServoReg.Enabled, "u8", [1])
}
this.pulse = n
}

Просмотреть файл

@ -48,5 +48,5 @@ namespace modules {
}
//% fixedInstance whenUsed
export const thermometer = new ThermometerClient("temp");
export const thermometer = new ThermometerClient("thermometer");
}