Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/fan #622

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
"node": true
},
"plugins": ["@typescript-eslint", "prettier", "unused-imports"],
"extends": ["google", "plugin:prettier/recommended"],
"extends": ["google", "plugin:prettier/recommended", "plugin:@typescript-eslint/recommended"],
"ignorePatterns": ["dist"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
"no-nested-ternary": "error",
"curly": "error",
"eqeqeq": "error",
"prettier/prettier": ["error"],
"require-jsdoc": "off",
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# This workflow will do a clean installation of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions

name: Node.js CI
Expand All @@ -15,7 +15,7 @@ jobs:

strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
node-version: [16.x, 18.x]

steps:
- uses: actions/checkout@v2
Expand Down
3 changes: 3 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
always-auth=true
lockfile-version=3
save-exact=true
save-prefix=
8,715 changes: 3 additions & 8,712 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "esphome-ts",
"version": "3.3.0",
"version": "3.4.0-beta.0",
"description": "A TypeScript client for the Esphome Native API interface",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
3 changes: 1 addition & 2 deletions src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ import {
PingResponse,
SubscribeStatesRequest,
} from './protobuf/api';
import { ReadData } from './connection';
import { Observable, of, Subscription } from 'rxjs';
import { MessageTypes } from './requestResponseMatching';
import { filter, switchMap, take, tap } from 'rxjs/operators';
import { Reader } from 'protobufjs/minimal';
import { EspSocket } from './espSocket';
import { EspSocket, ReadData } from './espSocket';
import { voidMessage } from './protobuf/api_options';

export interface Decoder<T> {
Expand Down
88 changes: 0 additions & 88 deletions src/api/connection.ts

This file was deleted.

11 changes: 5 additions & 6 deletions src/api/espDevice.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ReadData } from './connection';
import {
catchError,
distinctUntilChanged,
Expand Down Expand Up @@ -26,7 +25,7 @@ import {
} from './';
import { BaseComponent } from '../components';
import { BehaviorSubject, concat, merge, Observable, of, Subscription } from 'rxjs';
import { EspSocket } from './espSocket';
import { EspSocket, ReadData } from './espSocket';
import { DeviceInfoResponse } from './protobuf/api';

const PING_TIMEOUT = 90 * 1000;
Expand All @@ -49,9 +48,9 @@ export class EspDevice {
public readonly alive$: Observable<boolean>;

constructor(
private readonly host: string,
private readonly password: string = '',
private readonly port: number = 6053,
protected readonly host: string,
protected readonly password: string = '',
protected readonly port: number = 6053,
) {
this.subscription = new Subscription();
this.discovery = new BehaviorSubject<boolean>(false);
Expand Down Expand Up @@ -152,7 +151,7 @@ export class EspDevice {
if (component) {
this.components[id] = this.components[id] ?? component;
} else if (state$) {
this.components[id].provideStateObservable(state$);
this.components[id]?.provideStateObservable(state$);
}
}
}
Expand Down
13 changes: 7 additions & 6 deletions src/api/espSocket.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { from, Observable } from 'rxjs';
import { filter, map, switchMap, take, takeUntil, timeout } from 'rxjs/operators';
import { CommandInterface } from '../components/commandInterface';
import { CommandInterface } from '../components';
import { RxjsSocket, RxjsSocketConfiguration } from './socket';
import { BytePositions, HEADER_FIRST_BYTE, HEADER_SIZE } from './bytePositions';
import { MessageTypes } from './requestResponseMatching';
Expand All @@ -22,12 +22,13 @@ export class EspSocket extends RxjsSocket implements CommandInterface {
let bytesTaken = 0;
const result: Buffer[] = [];
while (bytesTaken < buffer.length) {
const subBuffer = buffer.slice(
bytesTaken,
bytesTaken + HEADER_SIZE + buffer[bytesTaken + BytePositions.LENGTH],
);
const currentPackageSize = buffer[bytesTaken + BytePositions.LENGTH];
if (typeof currentPackageSize !== 'number') {
break;
}
const subBuffer = buffer.slice(bytesTaken, bytesTaken + HEADER_SIZE + currentPackageSize);
result.push(subBuffer);
bytesTaken += HEADER_SIZE + buffer[bytesTaken + BytePositions.LENGTH];
bytesTaken += HEADER_SIZE + currentPackageSize;
}
return from(result);
}),
Expand Down
24 changes: 21 additions & 3 deletions src/api/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { ReadData } from './connection';
import {
BinarySensorStateResponse,
CoverStateResponse,
FanStateResponse,
LightStateResponse,
ListEntitiesBinarySensorResponse,
ListEntitiesFanResponse,
ListEntitiesLightResponse,
ListEntitiesSensorResponse,
ListEntitiesSwitchResponse,
Expand All @@ -17,6 +18,8 @@ import { CommandInterface } from '../components';
import { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';
import { BaseComponent, BinarySensorComponent, LightComponent, SensorComponent, SwitchComponent } from '..';
import { FanComponent } from '../components/fan';
import { ReadData } from './espSocket';

export const stateParser = (data: ReadData): StateResponses | undefined => {
switch (data.type) {
Expand Down Expand Up @@ -98,6 +101,19 @@ export const createComponents = (
component: new SensorComponent(response, state$, emptyCommandInterface),
};
}
case MessageTypes.ListEntitiesFanResponse: {
const response: ListEntitiesFanResponse = decode(ListEntitiesFanResponse, data);
const state$ = transformStates<FanStateResponse>(stateEvents$, response);
return knownComponents.has(response.objectId)
? {
id: response.objectId,
state$,
}
: {
id: response.objectId,
component: new FanComponent(response, state$, connection),
};
}
}
return { id: '' };
};
Expand All @@ -113,8 +129,10 @@ export const transformStates = <T extends StateResponses>(
return stateEvents$.pipe(filter((stateEvent) => stateEvent.key === listEntityResponse.key)) as Observable<T>;
};

type FalsyTypes = null | undefined | false | 0 | 0n | '';

export const isTrue = (val: unknown): val is true => val === true;
export const isTruthy = (val: unknown): boolean => !!val;
export const isTruthy = <T>(val: T | FalsyTypes): val is T => !!val;

export const isFalse = (val: unknown): val is false => val === false;
export const isFalsy = (val: unknown): boolean => !val;
export const isFalsy = <T>(val: T | FalsyTypes): val is FalsyTypes => !val;
1 change: 0 additions & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export * from './bytePositions';
export * from './client';
export * from './connection';
export * from './espDevice';
export * from './helpers';
export * from './interfaces';
Expand Down
1 change: 1 addition & 0 deletions src/api/protobuf/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable */
// @ts-nocheck
import { Reader, Writer } from 'protobufjs/minimal';
import { voidMessage } from './api_options';

Expand Down
1 change: 1 addition & 0 deletions src/api/protobuf/google_descriptor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable */
// @ts-nocheck
import Long from 'long';
import { configure, Reader, util, Writer } from 'protobufjs/minimal';

Expand Down
19 changes: 11 additions & 8 deletions src/api/socket.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Socket } from 'net';
import { BehaviorSubject, fromEvent, Observable, Subject } from 'rxjs';
import { take, takeUntil, tap } from 'rxjs/operators';
import { filter, take, takeUntil, tap } from 'rxjs/operators';

export interface RxjsSocketConfiguration {
reconnectOnTimeout?: boolean;
Expand Down Expand Up @@ -86,33 +86,36 @@ export class RxjsSocket {
return;
}

fromEvent<Error>(this.socket, 'error')
fromEvent(this.socket, 'error')
.pipe(
filter((payload): payload is Error => payload instanceof Error),
tap((err: Error) => this.error.next(err)),
takeUntil(this.terminate),
)
.subscribe();
fromEvent<Buffer>(this.socket, 'data')

fromEvent(this.socket, 'data')
.pipe(
filter((event: unknown): event is Buffer => Buffer.isBuffer(event)),
tap((buffer: Buffer) => this.data.next(buffer)),
takeUntil(this.terminate),
)
.subscribe();
fromEvent<void>(this.socket, 'connect')
fromEvent(this.socket, 'connect')
.pipe(
take(1),
tap(() => this.connected.next(true)),
takeUntil(this.terminate),
)
.subscribe();
fromEvent<void>(this.socket, 'close')
fromEvent(this.socket, 'close')
.pipe(
take(1),
tap(() => this.connected.next(false)),
takeUntil(this.terminate),
)
.subscribe();
fromEvent<void>(this.socket, 'end')
fromEvent(this.socket, 'end')
.pipe(
take(1),
tap(() => this.socket?.end()),
Expand All @@ -122,7 +125,7 @@ export class RxjsSocket {
.subscribe();

if (this.config.timeout && this.config.timeout > 0) {
fromEvent<void>(this.socket, 'timeout')
fromEvent(this.socket, 'timeout')
.pipe(
tap(() => this.timeout.next()),
tap(() => {
Expand All @@ -147,7 +150,7 @@ export class RxjsSocket {

private destroySocket(): void {
this.socket?.destroy();
this.socket = undefined;
delete this.socket;
this.connected.next(false);
}
}
6 changes: 3 additions & 3 deletions src/components/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { StateEvent } from './states';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { debounceTime, filter, take, takeUntil, tap } from 'rxjs/operators';
import { CommandInterface } from './commandInterface';
import { isTrue, MessageTypes } from '../api';
import { isTrue, isTruthy, MessageTypes } from '../api';

export abstract class BaseComponent<L extends ListEntity = ListEntity, S extends StateEvent = StateEvent> {
protected readonly state = new BehaviorSubject<S | undefined>(undefined);
Expand All @@ -20,7 +20,7 @@ export abstract class BaseComponent<L extends ListEntity = ListEntity, S extends
private readonly commandInterface: CommandInterface,
) {
this.commandInPipeline = new BehaviorSubject<boolean>(false);
this.state$ = this.state.pipe(filter((state?: S): state is S => state !== undefined));
this.state$ = this.state.pipe(filter(isTruthy));
this.provideStateObservable(state);
this.commandInPipeline
.pipe(
Expand Down Expand Up @@ -64,7 +64,7 @@ export abstract class BaseComponent<L extends ListEntity = ListEntity, S extends
this.teardown.next();
}

protected queueCommand(type: MessageTypes, dataFn: () => Uint8Array, disableSerialise: boolean = false): void {
protected queueCommand(type: MessageTypes, dataFn: () => Uint8Array, disableSerialise = false): void {
this.commandInPipeline
.pipe(
filter((x: boolean) => !x || disableSerialise),
Expand Down
8 changes: 7 additions & 1 deletion src/components/entities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,10 @@ export interface LightEntity extends ListEntity {
supportsRgb: boolean;
}

export type ComponentType = 'light' | 'binarySensor' | 'sensor' | 'switch';
export interface FanEntity extends ListEntity {
supportsOscillation: boolean;
supportsSpeed: boolean;
supportsDirection: boolean;
}

export type ComponentType = 'light' | 'binarySensor' | 'sensor' | 'switch' | 'fan';
Loading