-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
91 lines (71 loc) · 2.72 KB
/
main.ts
File metadata and controls
91 lines (71 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import 'reflect-metadata';
import * as utils from '@iobroker/adapter-core';
import { DependencyContainer } from 'tsyringe';
import { IConnectedServiceAdapter, IConnectedServiceContext } from '@acaad/abstractions';
import { FrameworkContainer, ComponentManager } from '@acaad/core';
import { IoBrokerContext } from './services/IoBroker.Context';
import { IoBrokerCsAdapter } from './services/IoBroker.ConnectedServiceAdapter';
import { Option, pipe } from 'effect';
class Acaad extends utils.Adapter {
private _fwkContainer: DependencyContainer;
private _componentManager: Option.Option<ComponentManager> = Option.none();
// Not using Option here for performance reasons.
private _context: IoBrokerContext | null = null;
public constructor(options: Partial<utils.AdapterOptions> = {}) {
super({
...options,
name: 'acaad'
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
if (!this.config.targetServices) {
this.config.targetServices = [];
}
if (!this.config.auth) {
// TODO: Raise an error later.
// Here the logger is not yet available.
console.log('No auth provided.');
}
this._fwkContainer = this.createDiContainer();
}
private createDiContainer(): DependencyContainer {
const ioBrokerContext = new IoBrokerContext(this);
const contextToken = IoBrokerContext.Token;
return FrameworkContainer.CreateCsContainer<IConnectedServiceAdapter>({
useClass: IoBrokerCsAdapter
})
.WithContext<IConnectedServiceContext>(contextToken, ioBrokerContext)
.Build();
}
private async onReady(): Promise<void> {
const instance = this._fwkContainer.resolve(ComponentManager) as ComponentManager;
this._componentManager = Option.some(instance);
await instance.startAsync();
}
private async onUnload(callback: () => void): Promise<void> {
try {
// TODO: Add AbortController+Signal to limit shutdown duration, if necessary force-stop.
await pipe(
this._componentManager,
Option.match({
onSome: (cm) => cm.shutdownAsync(), // TODO: Add timeout
onNone: () => Promise.resolve()
})
);
} finally {
await this._fwkContainer.dispose();
callback();
}
}
private async onStateChange(id: string, state: ioBroker.State | null | undefined): Promise<void> {
await (this._context ??= this._fwkContainer.resolve(
IoBrokerContext.Token
) as IoBrokerContext).onStateChangeAsync(id, state);
}
}
if (require.main !== module) {
module.exports = (options: Partial<utils.AdapterOptions> | undefined) => new Acaad(options);
} else {
(() => new Acaad())();
}