1 import ConfigurationData
, { StationTemplateUrl
, StorageConfiguration
, UIWebSocketServerConfiguration
} from
'../types/ConfigurationData';
3 import Constants from
'./Constants';
4 import { ServerOptions
} from
'ws';
5 import { StorageType
} from
'../types/Storage';
6 import type { WorkerChoiceStrategy
} from
'poolifier';
7 import { WorkerProcessType
} from
'../types/Worker';
8 import chalk from
'chalk';
10 import path from
'path';
12 export default class Configuration
{
13 private static configurationFilePath
= path
.join(path
.resolve(__dirname
, '../'), 'assets', 'config.json');
14 private static configurationFileWatcher
: fs
.FSWatcher
;
15 private static configuration
: ConfigurationData
| null = null;
16 private static configurationChangeCallback
: () => Promise
<void>;
18 static setConfigurationChangeCallback(cb
: () => Promise
<void>): void {
19 Configuration
.configurationChangeCallback
= cb
;
22 static getLogStatisticsInterval(): number {
23 Configuration
.warnDeprecatedConfigurationKey('statisticsDisplayInterval', null, 'Use \'logStatisticsInterval\' instead');
25 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logStatisticsInterval') ? Configuration
.getConfig().logStatisticsInterval
: 60;
28 static getUIWebSocketServer(): UIWebSocketServerConfiguration
{
29 let options
: ServerOptions
= {
30 host
: Constants
.DEFAULT_UI_WEBSOCKET_SERVER_HOST
,
31 port
: Constants
.DEFAULT_UI_WEBSOCKET_SERVER_PORT
33 let uiWebSocketServerConfiguration
: UIWebSocketServerConfiguration
= {
37 if (Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'uiWebSocketServer')) {
38 if (Configuration
.objectHasOwnProperty(Configuration
.getConfig().uiWebSocketServer
, 'options')) {
40 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().uiWebSocketServer
.options
, 'host') && { host
: Configuration
.getConfig().uiWebSocketServer
.options
.host
},
41 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().uiWebSocketServer
.options
, 'port') && { port
: Configuration
.getConfig().uiWebSocketServer
.options
.port
}
44 uiWebSocketServerConfiguration
=
46 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().uiWebSocketServer
, 'enabled') && { enabled
: Configuration
.getConfig().uiWebSocketServer
.enabled
},
50 return uiWebSocketServerConfiguration
;
53 static getPerformanceStorage(): StorageConfiguration
{
54 Configuration
.warnDeprecatedConfigurationKey('URI', 'performanceStorage', 'Use \'uri\' instead');
55 let storageConfiguration
: StorageConfiguration
= {
57 type: StorageType
.JSON_FILE
,
58 uri
: this.getDefaultPerformanceStorageUri(StorageType
.JSON_FILE
)
60 if (Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'performanceStorage')) {
61 storageConfiguration
=
63 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().performanceStorage
, 'enabled')
64 ? { enabled
: Configuration
.getConfig().performanceStorage
.enabled
}
66 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().performanceStorage
, 'type')
67 ? { type: Configuration
.getConfig().performanceStorage
.type }
68 : { type: StorageType
.JSON_FILE
},
69 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().performanceStorage
, 'uri')
70 ? { uri
: Configuration
.getConfig().performanceStorage
.uri
}
71 : { uri
: this.getDefaultPerformanceStorageUri(Configuration
.getConfig()?.performanceStorage
?.type ?? StorageType
.JSON_FILE
) }
74 return storageConfiguration
;
77 static getAutoReconnectMaxRetries(): number {
78 Configuration
.warnDeprecatedConfigurationKey('autoReconnectTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
79 Configuration
.warnDeprecatedConfigurationKey('connectionTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
80 Configuration
.warnDeprecatedConfigurationKey('autoReconnectMaxRetries', null, 'Use it in charging station template instead');
82 if (Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'autoReconnectMaxRetries')) {
83 return Configuration
.getConfig().autoReconnectMaxRetries
;
87 static getStationTemplateUrls(): StationTemplateUrl
[] {
88 Configuration
.warnDeprecatedConfigurationKey('stationTemplateURLs', null, 'Use \'stationTemplateUrls\' instead');
89 !Configuration
.isUndefined(Configuration
.getConfig()['stationTemplateURLs']) && (Configuration
.getConfig().stationTemplateUrls
= Configuration
.getConfig()['stationTemplateURLs'] as StationTemplateUrl
[]);
90 Configuration
.getConfig().stationTemplateUrls
.forEach((stationUrl
: StationTemplateUrl
) => {
91 if (!Configuration
.isUndefined(stationUrl
['numberOfStation'])) {
92 console
.error(chalk
`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${stationUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead}`);
96 return Configuration
.getConfig().stationTemplateUrls
;
99 static getWorkerProcess(): WorkerProcessType
{
100 Configuration
.warnDeprecatedConfigurationKey('useWorkerPool;', null, 'Use \'workerProcess\' to define the type of worker process to use instead');
101 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'workerProcess') ? Configuration
.getConfig().workerProcess
: WorkerProcessType
.WORKER_SET
;
104 static getWorkerStartDelay(): number {
105 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'workerStartDelay') ? Configuration
.getConfig().workerStartDelay
: Constants
.WORKER_START_DELAY
;
108 static getWorkerPoolMinSize(): number {
109 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'workerPoolMinSize') ? Configuration
.getConfig().workerPoolMinSize
: Constants
.DEFAULT_WORKER_POOL_MIN_SIZE
;
112 static getWorkerPoolMaxSize(): number {
113 Configuration
.warnDeprecatedConfigurationKey('workerPoolSize;', null, 'Use \'workerPoolMaxSize\' instead');
114 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'workerPoolMaxSize') ? Configuration
.getConfig().workerPoolMaxSize
: Constants
.DEFAULT_WORKER_POOL_MAX_SIZE
;
117 static getWorkerPoolStrategy(): WorkerChoiceStrategy
{
118 return Configuration
.getConfig().workerPoolStrategy
;
121 static getChargingStationsPerWorker(): number {
122 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'chargingStationsPerWorker') ? Configuration
.getConfig().chargingStationsPerWorker
: Constants
.DEFAULT_CHARGING_STATIONS_PER_WORKER
;
125 static getLogConsole(): boolean {
126 Configuration
.warnDeprecatedConfigurationKey('consoleLog', null, 'Use \'logConsole\' instead');
127 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logConsole') ? Configuration
.getConfig().logConsole
: false;
130 static getLogFormat(): string {
131 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logFormat') ? Configuration
.getConfig().logFormat
: 'simple';
134 static getLogRotate(): boolean {
135 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logRotate') ? Configuration
.getConfig().logRotate
: true;
138 static getLogMaxFiles(): number {
139 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logMaxFiles') ? Configuration
.getConfig().logMaxFiles
: 7;
142 static getLogLevel(): string {
143 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logLevel') ? Configuration
.getConfig().logLevel
: 'info';
146 static getLogFile(): string {
147 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logFile') ? Configuration
.getConfig().logFile
: 'combined.log';
150 static getLogErrorFile(): string {
151 Configuration
.warnDeprecatedConfigurationKey('errorFile', null, 'Use \'logErrorFile\' instead');
152 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logErrorFile') ? Configuration
.getConfig().logErrorFile
: 'error.log';
155 static getSupervisionUrls(): string[] {
156 Configuration
.warnDeprecatedConfigurationKey('supervisionURLs', null, 'Use \'supervisionUrls\' instead');
157 !Configuration
.isUndefined(Configuration
.getConfig()['supervisionURLs']) && (Configuration
.getConfig().supervisionUrls
= Configuration
.getConfig()['supervisionURLs'] as string[]);
159 return Configuration
.getConfig().supervisionUrls
;
162 static getDistributeStationsToTenantsEqually(): boolean {
163 Configuration
.warnDeprecatedConfigurationKey('distributeStationToTenantEqually', null, 'Use \'distributeStationsToTenantsEqually\' instead');
164 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'distributeStationsToTenantsEqually') ? Configuration
.getConfig().distributeStationsToTenantsEqually
: true;
167 private static logPrefix(): string {
168 return new Date().toLocaleString() + ' Simulator configuration |';
171 private static warnDeprecatedConfigurationKey(key
: string, sectionName
?: string, logMsgToAppend
= '') {
172 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
173 if (sectionName
&& !Configuration
.isUndefined(Configuration
.getConfig()[sectionName
]) && !Configuration
.isUndefined(Configuration
.getConfig()[sectionName
][key
])) {
174 console
.error(chalk
`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${logMsgToAppend && '. ' + logMsgToAppend}}`);
175 } else if (!Configuration
.isUndefined(Configuration
.getConfig()[key
])) {
176 console
.error(chalk
`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${logMsgToAppend && '. ' + logMsgToAppend}}`);
180 // Read the config file
181 private static getConfig(): ConfigurationData
{
182 if (!Configuration
.configuration
) {
184 Configuration
.configuration
= JSON
.parse(fs
.readFileSync(Configuration
.configurationFilePath
, 'utf8')) as ConfigurationData
;
186 Configuration
.handleFileException(Configuration
.logPrefix(), 'Configuration', Configuration
.configurationFilePath
, error
);
188 if (!Configuration
.configurationFileWatcher
) {
189 Configuration
.configurationFileWatcher
= Configuration
.getConfigurationFileWatcher();
192 return Configuration
.configuration
;
195 private static getConfigurationFileWatcher(): fs
.FSWatcher
{
197 return fs
.watch(Configuration
.configurationFilePath
, (event
, filename
): void => {
198 if (filename
&& event
=== 'change') {
199 // Nullify to force configuration file reading
200 Configuration
.configuration
= null;
201 if (!Configuration
.isUndefined(Configuration
.configurationChangeCallback
)) {
202 Configuration
.configurationChangeCallback().catch(() => { /* This is intentional */ });
207 Configuration
.handleFileException(Configuration
.logPrefix(), 'Configuration', Configuration
.configurationFilePath
, error
as Error);
211 private static getDefaultPerformanceStorageUri(storageType
: StorageType
) {
212 const SQLiteFileName
= `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
213 switch (storageType
) {
214 case StorageType
.JSON_FILE
:
215 return `file://${path.join(path.resolve(__dirname, '../../'), Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME)}`;
216 case StorageType
.SQLITE
:
217 return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`;
219 throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
223 private static objectHasOwnProperty(object
: unknown
, property
: string): boolean {
224 return Object.prototype
.hasOwnProperty
.call(object
, property
) as boolean;
227 private static isUndefined(obj
: unknown
): boolean {
228 return typeof obj
=== 'undefined';
231 private static handleFileException(logPrefix
: string, fileType
: string, filePath
: string, error
: NodeJS
.ErrnoException
): void {
232 const prefix
= logPrefix
.length
!== 0 ? logPrefix
+ ' ' : '';
233 if (error
.code
=== 'ENOENT') {
234 console
.error(chalk
.green(prefix
) + chalk
.red(fileType
+ ' file ' + filePath
+ ' not found: '), error
);
235 } else if (error
.code
=== 'EEXIST') {
236 console
.error(chalk
.green(prefix
) + chalk
.red(fileType
+ ' file ' + filePath
+ ' already exists: '), error
);
237 } else if (error
.code
=== 'EACCES') {
238 console
.error(chalk
.green(prefix
) + chalk
.red(fileType
+ ' file ' + filePath
+ ' access denied: '), error
);
240 console
.error(chalk
.green(prefix
) + chalk
.red(fileType
+ ' file ' + filePath
+ ' error: '), error
);