import axios, { AxiosResponse } from 'axios'; import { eiotAppManagerService } from './app-manager/eiot-app-manager.service'; import { eiotDeviceManagerService } from './device-manager/eiot-device-manager.service'; import { eiotSessionVarsService } from './session-vars/eiot-session-vars.service'; // import { eiotAppDictionaryService } from './device-manager/common/eiot-app-dictionary.service'; import { eiotTraceService } from './app-manager/common/eiot-trace.service'; import { eiotSQLiteService } from './app-manager/common/eiot-sqlite.service'; import { eiotGPSService } from './app-components/eiot-gps.service'; import { eiotWeatherStationService } from './app-components/eiot-weather-station.service'; import { EIOT_EMULATE_VALUES } from './lib-constants/emulate.const'; const TIMEOUT_MS = 10000; // Timeout duration in milliseconds for fetch IP address again. const MAX_RETRIES = 3; // Maximum number of retry attempts for fetch IP address again. class EIoTSessionStartService { private eiotSessionRes:any = new Object(); private isEmulateMode = false; private isExcludeAppManager = false; private deviceConfig:any = new Object(); private eiotDeviceInfo:any = new Object(); private logInfo:any = new Object(); private applicaionGPSCoords = ''; //#region public methods async createSession( isEmulateMode: boolean, isExcludeAppManager: boolean, ) { this.isEmulateMode = isEmulateMode this.isExcludeAppManager = isExcludeAppManager if (this.isExcludeAppManager) { return await this.defaultSiteData(); } else { await this.connectToAppMgr(); return { ...this.eiotSessionRes, Logs: this.logInfo }; } } //#endregion public methods //#region private methods async defaultSiteData() { if (!this.isEmulateMode) { await eiotDeviceManagerService.tryToConn(); await this.checkStatus(); } else { console.log('App is running on Emulate Mode.'); if (localStorage.getItem('BitDeviceInfo')) { const BitDeviceInfo = JSON.parse(localStorage.getItem('BitDeviceInfo') as string); this.eiotSessionRes['DeviceID'] = this.eiotDeviceInfo['DeviceID'] = BitDeviceInfo['externalId']; this.eiotSessionRes['DeviceName'] = this.eiotDeviceInfo['DeviceName'] = BitDeviceInfo['name']; } else { this.eiotSessionRes['DeviceID'] = this.eiotDeviceInfo['DeviceID'] = ''; this.eiotSessionRes['DeviceName'] = this.eiotDeviceInfo['DeviceName'] = ''; } eiotSessionVarsService.EIoTDeviceInfo = this.eiotDeviceInfo; await this.finalAction(); } return { ...this.eiotSessionRes, Logs: this.logInfo } } async connectToAppMgr() { console.log('Starting to connect Application Manager.'); this.logInfo['EIoT ApplicationMgr connected'] = false; await eiotAppManagerService.tryToConn().then(async (data:any) => { console.log("Returned => ", data); if (data === true) { this.logInfo['EIoT ApplicationMgr connected'] = true console.log('Successfully Application Manager Connected.'); console.log("Start fetching Device Config."); this.logInfo['EIoT device configuration found'] = false await new Promise((resolve) => { const execute = async () => { const result:any = await eiotSQLiteService.getDeviceConfig() // console.log(JSON.stringify(result)); if (result['Response']) { console.log('Device Config Fetched.'); this.logInfo['EIoT device configuration found'] = true this.deviceConfig = JSON.parse(result["Response"]); this.eiotSessionRes['DeviceID'] = this.eiotDeviceInfo['DeviceID'] = this.deviceConfig['ID']; this.eiotSessionRes['DeviceName'] = this.eiotDeviceInfo['DeviceName'] = this.deviceConfig['KioskName']; eiotSessionVarsService.EIoTDeviceInfo = this.eiotDeviceInfo; // if (!environment.runningAppInLockdown) { // await this.startSesion() // } else { const res:any = await this.startSesion() //console.log(res); if (!res) { await this.callPageNavigation(); } // } resolve(true) } else { resolve(false) console.log('Unable to fetch EIoT device configuration'); this.eiotSessionRes['Success'] = false return; } } execute() }) } else { console.log('Unable to connect Application Manager, Connection time..'); this.eiotSessionRes['Success'] = false return; } }).catch((error:any) => { console.log('Unable to connect Application Manager, Something went wrong..'); console.error(error) this.eiotSessionRes['Success'] = false return; }); } async startSesion() { return await new Promise((resolve) => { const execute = async () => { const res:any = await eiotTraceService.sessionStart() console.info("Session Start =" + JSON.stringify(res)); if (res.Response || res.Type === "success") { console.log('Session Started.'); await this.callPageNavigation(); resolve(true) } else { resolve(false) } } execute() }) } async callPageNavigation() { return await new Promise((resolve) => { const execute = async () => { const res:any = await eiotTraceService.pageNavigateStart(); console.info("Page Navigate Start =" + JSON.stringify(res)); if (res.Response || res.Type === "success") { console.log('Page Navigate Started.'); } const isDeviceMgrStarted = await eiotDeviceManagerService.tryToConn(); if (isDeviceMgrStarted) { await this.checkStatus(); resolve(true) } else { this.logInfo['EIoT DeviceMgr service ready'] = false console.log('Unable to connect Device Manager, Connection time..'); this.eiotSessionRes['Success'] = false resolve(false) return; } } execute() }) } async checkStatus() { console.log("Check status of DeviceManager"); const state = await eiotDeviceManagerService.getServiceStatus(); console.log("Received status of DeviceManager is : "+ state); if (state === 1) { this.logInfo['EIoT DeviceMgr service ready'] = true console.log("DeviceManager Service is Ready."); await this.beginInit(); } else { this.logInfo['EIoT DeviceMgr service ready'] = false console.log("DeviceManager Service is not ready."); // await new Promise((resolve) => { // setTimeout(async () => { // await this.checkStatus(); // resolve(true) // }, 1000); // }) } } async beginInit() { let comps: any = await eiotDeviceManagerService.getActiveComps() comps = comps || []; if (comps.length > 0) { let ActivedDeviceComp = '' comps.forEach((element:any) => { ActivedDeviceComp += element['ComponentTypeName'] + ', ' }); console.log('Total '+comps.length+' active device component founds : ' +ActivedDeviceComp); const appComp = comps.find( (comp: any) => comp.ComponentTypeName === "Application" && comp.IsActive ); let appCompEle = {}; if (appComp) { appCompEle = { Idx: appComp.CompIdx, Interface: appComp.DeviceManagerInterface, }; } const cpuComp = comps.find( (comp: any) => comp.ComponentTypeName === "CPU" && comp.IsActive ); let cpuCompEle = {}; if (cpuComp) { cpuCompEle = { Idx: cpuComp.CompIdx, Interface: cpuComp.DeviceManagerInterface, }; } const ioComp = comps.find( (comp: any) => comp.ComponentTypeName === "IO_Module" && comp.IsActive ); let ioCompEle = {}; if (ioComp) { ioCompEle = { Idx: ioComp.CompIdx, Interface: ioComp.DeviceManagerInterface, }; } let speechCompEle = undefined; const speechComp = comps.find( (comp: any) => comp.ComponentTypeName === "Speech" && comp.IsActive ); if (speechComp) { speechCompEle = { Idx: speechComp.CompIdx, Interface: speechComp.DeviceManagerInterface, }; } let weatherCompEle = undefined; const weatherComp = comps.find( (comp: any) => comp.ComponentTypeName === "Weather_Station" && comp.IsActive ); if (weatherComp) { weatherCompEle = { Idx: weatherComp.CompIdx, Interface: weatherComp.DeviceManagerInterface, }; } let webcamCompEle = undefined; const webcamComp = comps.find( (comp: any) => comp.ComponentTypeName === "Webcam" && comp.IsActive ); if (webcamComp) { webcamCompEle = { Idx: webcamComp.CompIdx, Interface: webcamComp.DeviceManagerInterface } } let gpsCompEle = undefined; const gpsComp = comps.find( (comp: any) => comp.ComponentTypeName === "IoT" && comp.IsActive ); if (gpsComp) { this.logInfo['GPS component connnected'] = true gpsCompEle = { Idx: gpsComp.CompIdx, Interface: gpsComp.DeviceManagerInterface } } else { this.logInfo['GPS component connnected'] = false } if ( (this.isEmulateMode && appComp && cpuComp && speechComp) || (!this.isEmulateMode && appComp && cpuComp && ioComp && speechComp && weatherComp) || (!this.isEmulateMode && appComp && cpuComp && webcamComp && gpsComp) ) { let sessionComp = {}; if (this.isEmulateMode) { sessionComp = { appDict: appCompEle, speech: speechCompEle, }; } else { sessionComp = { appDict: appCompEle, cpu: cpuCompEle, ioModule: ioCompEle, speech: speechCompEle, weather: weatherCompEle, webcam: webcamCompEle, gps: gpsCompEle, }; } eiotSessionVarsService.DevMgrComps = sessionComp; return await this.finalAction(); } else { console.log("Invalid component configuration"); return false; } } else { console.log("No components configured"); return false; } } async finalAction() { return await new Promise((resolve) => { const execute = async () => { if (this.isEmulateMode) { const temp_WEATHER_DATA: any = EIOT_EMULATE_VALUES.WEATHER_DATA eiotSessionVarsService.WeatherData = temp_WEATHER_DATA; if (temp_WEATHER_DATA && Object.keys(temp_WEATHER_DATA).length > 0 && temp_WEATHER_DATA?.GPSLocation) { await this.StoreGeoLocation(temp_WEATHER_DATA.GPSLocation) } } if (!this.isExcludeAppManager) { // if (eiotSessionVarsService.EIOT) { // const res_DeviceConfig:any = await eiotAppDictionaryService.getDeviceConfig() // if (res_DeviceConfig['ByPassAuth']=='true') { // eiotSessionVarsService.EIoTByPassAuth = true; // if (res_DeviceConfig['AuthToken']) { // localStorage.setItem('token', String(res_DeviceConfig['AuthToken'])) // } // if (res_DeviceConfig['AuthTokenID']) { // localStorage.setItem('token_id', String(res_DeviceConfig['AuthTokenID'])) // } // } // this.eiotDeviceInfo['DeviceType'] = res_DeviceConfig['EndUserDeviceType']; // eiotSessionVarsService.EIoTDeviceInfo = this.eiotDeviceInfo; // } await Promise.all([ this.initWeatherComp(), this.initWebCamComp(), this.GetBitDeviceInfo() ]).then(() => { resolve(true) }).catch((error:any) => { resolve(true) console.error(error) }); } else { if (localStorage.getItem('BitDeviceInfo')) { const BitDeviceInfo = JSON.parse(localStorage.getItem('BitDeviceInfo') as string); eiotSessionVarsService.BitDeviceInfo = BitDeviceInfo; this.logInfo['Kiosk registered in BIT platform'] = true this.eiotSessionRes['Success'] = true; } else { this.logInfo['Kiosk registered in BIT platform'] = false this.eiotSessionRes['Success'] = false } resolve(true) } } execute() }) } //#endregion private methods //#region Application Components async initWebCamComp() { const WebcamCompFound = await this.deviceConfig['Components'].find((obj:any) => { return obj.ComponentTypeName === "Webcam" && obj.IsActive }); if (WebcamCompFound) { console.log('EIoT Webcam Device Found.'); } else { console.log('EIoT Webcam Device Not Connected.'); } } async initWeatherComp() { const WeatherCompFound = await this.deviceConfig['Components'].find((obj:any) => { return obj.ComponentTypeName === "Weather_Station" && obj.IsActive }); if (WeatherCompFound) { console.log('Weather Device Found.'); return await new Promise((resolve) => { const execute = async () => { const DisplayFields: string[] = ['GPSLocation', 'RelWindDir', 'RelWindSpeed', 'Temperature', 'Dewpoint', 'RelHumidity', 'RainPresent', 'Pressure'] let GPSLocation: string; await eiotWeatherStationService.tryConnect() const res_getStatus:any = await eiotWeatherStationService.getStatus() //const list:any[] = [] // console.log(res_getStatus); // console.log(Object.keys(res_getStatus).length); // Object.keys(res_getStatus).forEach(o => { // if (DisplayFields.includes(o)) { // const new_o:any = new Object(); // new_o['title'] = o; // new_o['value'] = res_getStatus[o]; // list.push(Object.assign({}, new_o)); // } // }) //if (list.length) { // console.log('Weather Data Found.'); // eiotSessionVarsService.WeatherData = list; // this.eiotSessionRes['WeatherData'] = list // GPSLocation = list.find(i => i.title=='GPSLocation').value // //console.log(GPSLocation); // await this.StoreGeoLocation(GPSLocation) //} if (res_getStatus && Object.keys(res_getStatus).length > 0) { console.log('Weather Data Found.'); eiotSessionVarsService.WeatherData = res_getStatus; this.eiotSessionRes['WeatherData'] = res_getStatus Object.keys(res_getStatus).forEach(async (o) => { if(o == 'GPSLocation') { GPSLocation = res_getStatus[o] await this.StoreGeoLocation(GPSLocation) } }) } resolve(true) return; } execute() }) } else { console.log('Weather Device Not Connected.'); return await this.initGPSComp(); } } async initGPSComp() { // GPS Comp const GPSCompFound = await this.deviceConfig['Components'].find((obj:any) => { return obj.ComponentTypeName === "IoT" && obj.IsActive }); if (GPSCompFound) { console.log('GPS Component Found.'); await new Promise((resolve) => { const execute = async () => { await eiotGPSService.start(); const res_tryStart = await eiotGPSService.tryStart() if (res_tryStart) { console.log('GPS Started.'); const coord = await eiotGPSService.tryGetCoordinates() console.log('Coordinates Data Found.'); console.log(JSON.stringify(coord)); await this.StoreGeoLocation(coord['Latitude'] + ':' + coord['Longitude']) resolve(true) } else { this.eiotSessionRes['IsGPSNotStarted'] = true this.eiotSessionRes['IsGPSNotFound'] = true console.log('GPS Not Started.'); resolve(true) } resolve(true) } execute() }) } else { console.log('GPS Component Not Found.'); if (this.applicaionGPSCoords) { await this.StoreGeoLocation(this.applicaionGPSCoords); } } } //#endregion Application Components //#region common methods async StoreGeoLocation(GPSLocation: string) { // console.log(GPSLocation); let GeoLocationList:any[] = [] if (GPSLocation && GPSLocation.length) { GeoLocationList = GPSLocation?.split(':') } // console.log(GeoLocationList); const DeviceGeoLocation:any = new Object(); DeviceGeoLocation['latitude'] = Number(GeoLocationList[0]) || 0 DeviceGeoLocation['longitude'] = Number(GeoLocationList[1]) || 0 DeviceGeoLocation['meanSeaLevel'] = Number(GeoLocationList[2]) || 0 // console.log(DeviceGeoLocation); this.eiotSessionRes['GPSData'] = DeviceGeoLocation['latitude'] + ', ' + DeviceGeoLocation['longitude'] eiotSessionVarsService.GPSData = DeviceGeoLocation; try { const ipAddress = await this.getIpAddress(); console.log(`Device IP Address: ${ipAddress}`); return true; } catch (error) { console.error('Maximum number of retries reached. Unable to fetch IP address.'); this.logInfo['IP address fetch successfully'] = false; this.eiotSessionRes['Success'] = false; return false; } } getIpAddress = async (retryCount = 0): Promise => { try { // GetIpAddress using other public domain // https://icanhazip.com // https://ipinfo.io/ip const response: AxiosResponse = await axios.get('https://icanhazip.com', { timeout: TIMEOUT_MS }); const ip = response.data.trim(); this.eiotSessionRes['IPAddress'] = ip; this.eiotDeviceInfo['IPAddress'] = ip; eiotSessionVarsService.EIoTDeviceInfo = this.eiotDeviceInfo; return ip; } catch (error:any) { console.error(`An error occurred while fetching IP address (Retry ${retryCount + 1}):`, error.message); if (retryCount < MAX_RETRIES) { return this.getIpAddress(retryCount + 1); // Retry the request recursively } throw error; } }; async GetBitDeviceInfo() { const bitDevice:any = await eiotSQLiteService.getValueFromUtilityTbl('BitDeviceInfo') console.log('Registered BIT Device Data : '+JSON.stringify(bitDevice)); if(bitDevice && bitDevice['Type']=='success' && bitDevice['Response']?.length>0) { eiotSessionVarsService.BitDeviceInfo = JSON.parse(bitDevice['Response']); this.logInfo['Kiosk registered in BIT platform'] = true this.eiotSessionRes['Success'] = true } else { this.logInfo['Kiosk registered in BIT platform'] = false this.eiotSessionRes['Success'] = false } } //#endregion common methods } export const eiotSessionStartService = new EIoTSessionStartService()