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 let storageConfiguration
: StorageConfiguration
= {
56 type: StorageType
.JSON_FILE
,
57 URI
: this.getDefaultPerformanceStorageURI(StorageType
.JSON_FILE
)
59 if (Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'performanceStorage')) {
60 storageConfiguration
=
62 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().performanceStorage
, 'enabled') && { enabled
: Configuration
.getConfig().performanceStorage
.enabled
},
63 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().performanceStorage
, 'type') && { type: Configuration
.getConfig().performanceStorage
.type },
64 ...Configuration
.objectHasOwnProperty(Configuration
.getConfig().performanceStorage
, 'URI')
65 ? { URI
: Configuration
.getConfig().performanceStorage
.URI
}
66 : { URI
: this.getDefaultPerformanceStorageURI(Configuration
.getConfig()?.performanceStorage
?.type ?? StorageType
.JSON_FILE
) }
69 return storageConfiguration
;
72 static getAutoReconnectMaxRetries(): number {
73 Configuration
.warnDeprecatedConfigurationKey('autoReconnectTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
74 Configuration
.warnDeprecatedConfigurationKey('connectionTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
75 Configuration
.warnDeprecatedConfigurationKey('autoReconnectMaxRetries', null, 'Use it in charging station template instead');
77 if (Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'autoReconnectMaxRetries')) {
78 return Configuration
.getConfig().autoReconnectMaxRetries
;
82 static getStationTemplateURLs(): StationTemplateURL
[] {
83 Configuration
.getConfig().stationTemplateURLs
.forEach((stationURL
: StationTemplateURL
) => {
84 if (!Configuration
.isUndefined(stationURL
['numberOfStation'])) {
85 console
.error(chalk
`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${stationURL.file}' in 'stationTemplateURLs'. Use 'numberOfStations' instead}`);
89 return Configuration
.getConfig().stationTemplateURLs
;
92 static getWorkerProcess(): WorkerProcessType
{
93 Configuration
.warnDeprecatedConfigurationKey('useWorkerPool;', null, 'Use \'workerProcess\' to define the type of worker process to use instead');
94 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'workerProcess') ? Configuration
.getConfig().workerProcess
: WorkerProcessType
.WORKER_SET
;
97 static getWorkerStartDelay(): number {
98 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'workerStartDelay') ? Configuration
.getConfig().workerStartDelay
: Constants
.WORKER_START_DELAY
;
101 static getWorkerPoolMinSize(): number {
102 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'workerPoolMinSize') ? Configuration
.getConfig().workerPoolMinSize
: Constants
.DEFAULT_WORKER_POOL_MIN_SIZE
;
105 static getWorkerPoolMaxSize(): number {
106 Configuration
.warnDeprecatedConfigurationKey('workerPoolSize;', null, 'Use \'workerPoolMaxSize\' instead');
107 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'workerPoolMaxSize') ? Configuration
.getConfig().workerPoolMaxSize
: Constants
.DEFAULT_WORKER_POOL_MAX_SIZE
;
110 static getWorkerPoolStrategy(): WorkerChoiceStrategy
{
111 return Configuration
.getConfig().workerPoolStrategy
;
114 static getChargingStationsPerWorker(): number {
115 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'chargingStationsPerWorker') ? Configuration
.getConfig().chargingStationsPerWorker
: Constants
.DEFAULT_CHARGING_STATIONS_PER_WORKER
;
118 static getLogConsole(): boolean {
119 Configuration
.warnDeprecatedConfigurationKey('consoleLog', null, 'Use \'logConsole\' instead');
120 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logConsole') ? Configuration
.getConfig().logConsole
: false;
123 static getLogFormat(): string {
124 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logFormat') ? Configuration
.getConfig().logFormat
: 'simple';
127 static getLogRotate(): boolean {
128 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logRotate') ? Configuration
.getConfig().logRotate
: true;
131 static getLogMaxFiles(): number {
132 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logMaxFiles') ? Configuration
.getConfig().logMaxFiles
: 7;
135 static getLogLevel(): string {
136 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logLevel') ? Configuration
.getConfig().logLevel
: 'info';
139 static getLogFile(): string {
140 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logFile') ? Configuration
.getConfig().logFile
: 'combined.log';
143 static getLogErrorFile(): string {
144 Configuration
.warnDeprecatedConfigurationKey('errorFile', null, 'Use \'logErrorFile\' instead');
145 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'logErrorFile') ? Configuration
.getConfig().logErrorFile
: 'error.log';
148 static getSupervisionURLs(): string[] {
150 return Configuration
.getConfig().supervisionURLs
;
153 static getDistributeStationsToTenantsEqually(): boolean {
154 Configuration
.warnDeprecatedConfigurationKey('distributeStationToTenantEqually', null, 'Use \'distributeStationsToTenantsEqually\' instead');
155 return Configuration
.objectHasOwnProperty(Configuration
.getConfig(), 'distributeStationsToTenantsEqually') ? Configuration
.getConfig().distributeStationsToTenantsEqually
: true;
158 private static logPrefix(): string {
159 return new Date().toLocaleString() + ' Simulator configuration |';
162 private static warnDeprecatedConfigurationKey(key
: string, sectionName
?: string, logMsgToAppend
= '') {
163 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
164 if (sectionName
&& !Configuration
.isUndefined(Configuration
.getConfig()[sectionName
]) && !Configuration
.isUndefined(Configuration
.getConfig()[sectionName
][key
])) {
165 console
.error(chalk
`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${logMsgToAppend && '. ' + logMsgToAppend}}`);
166 } else if (!Configuration
.isUndefined(Configuration
.getConfig()[key
])) {
167 console
.error(chalk
`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${logMsgToAppend && '. ' + logMsgToAppend}}`);
171 // Read the config file
172 private static getConfig(): ConfigurationData
{
173 if (!Configuration
.configuration
) {
175 Configuration
.configuration
= JSON
.parse(fs
.readFileSync(Configuration
.configurationFilePath
, 'utf8')) as ConfigurationData
;
177 Configuration
.handleFileException(Configuration
.logPrefix(), 'Configuration', Configuration
.configurationFilePath
, error
);
179 if (!Configuration
.configurationFileWatcher
) {
180 Configuration
.configurationFileWatcher
= Configuration
.getConfigurationFileWatcher();
183 return Configuration
.configuration
;
186 private static getConfigurationFileWatcher(): fs
.FSWatcher
{
188 return fs
.watch(Configuration
.configurationFilePath
, async (event
, filename
): Promise
<void> => {
189 if (filename
&& event
=== 'change') {
190 // Nullify to force configuration file reading
191 Configuration
.configuration
= null;
192 if (!Configuration
.isUndefined(Configuration
.configurationChangeCallback
)) {
193 await Configuration
.configurationChangeCallback();
198 Configuration
.handleFileException(Configuration
.logPrefix(), 'Configuration', Configuration
.configurationFilePath
, error
);
202 private static getDefaultPerformanceStorageURI(storageType
: StorageType
) {
203 const SQLiteFileName
= `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
204 switch (storageType
) {
205 case StorageType
.JSON_FILE
:
206 return `file://${path.join(path.resolve(__dirname, '../../'), Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME)}`;
207 case StorageType
.SQLITE
:
208 return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`;
210 throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
214 private static objectHasOwnProperty(object
: unknown
, property
: string): boolean {
215 return Object.prototype
.hasOwnProperty
.call(object
, property
) as boolean;
218 private static isUndefined(obj
: unknown
): boolean {
219 return typeof obj
=== 'undefined';
222 private static handleFileException(logPrefix
: string, fileType
: string, filePath
: string, error
: NodeJS
.ErrnoException
): void {
223 const prefix
= logPrefix
.length
!== 0 ? logPrefix
+ ' ' : '';
224 if (error
.code
=== 'ENOENT') {
225 console
.error(chalk
.green(prefix
) + chalk
.red(fileType
+ ' file ' + filePath
+ ' not found: '), error
);
226 } else if (error
.code
=== 'EEXIST') {
227 console
.error(chalk
.green(prefix
) + chalk
.red(fileType
+ ' file ' + filePath
+ ' already exists: '), error
);
228 } else if (error
.code
=== 'EACCES') {
229 console
.error(chalk
.green(prefix
) + chalk
.red(fileType
+ ' file ' + filePath
+ ' access denied: '), error
);
231 console
.error(chalk
.green(prefix
) + chalk
.red(fileType
+ ' file ' + filePath
+ ' error: '), error
);