* move to generated constants

* removing unused command

* cleaning

* more cleanup

* clean acc

* more cleanup

* further cleanpu

* removing keyboard/mouse

* fix buid

* fix

* fixing music

* add music to test

* don't add mixer

* updated readme

* rename role manager

Co-authored-by: Peli de Halleux <peli@Pelis-MacBook-Pro.local>
This commit is contained in:
Peli de Halleux 2020-12-03 00:44:48 -08:00 коммит произвёл GitHub
Родитель bc65d05dea
Коммит f6f4ac92c6
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
30 изменённых файлов: 805 добавлений и 592 удалений

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

@ -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

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

@ -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"

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

@ -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))
}
}
}

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

@ -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:

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

@ -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)

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

@ -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);
}
}

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

@ -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();
}

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

@ -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
}

185
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 */
}

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

@ -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);

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

@ -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))
}
}
}

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

@ -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

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

@ -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) {

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

@ -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) {

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

@ -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) {

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

@ -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) {

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

@ -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)
}
}
}

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

@ -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])
}
}

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

@ -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) {

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

@ -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) {

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

@ -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"
},

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

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

@ -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);
}
}

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

@ -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)

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

@ -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

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

@ -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);
}
}
}

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

@ -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
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

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

@ -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);
}
}

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

@ -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