UNPKG

emotiv-ts

Version:

A Typescript library that wraps the Cortex API functionalities to communicate with Emotiv headsets

50 lines (49 loc) 2.15 kB
import { RequestAccess } from "../models/requests/authentication/request-access"; import { Authorize } from "../models/requests/authentication/authorize"; import { LicenseInfo } from "../models/requests/authentication/license-info"; import { Access } from "../models/responses/authentication/access"; import { Authorisation } from "../models/responses/authentication/authorisation"; import { License } from "../models/responses/authentication/license"; export class AuthenticationService { socket; static authorisation; constructor(socket) { this.socket = socket; } requestAccess(application) { return this.requestCortexAPI(this, new RequestAccess(application), data => new Access(data.result.accessGranted, data.result.message)); } authorize(application) { return this.requestCortexAPI(this, new Authorize(application), data => { AuthenticationService.authorisation = new Authorisation(data.result.cortexToken, data.result.warning); return AuthenticationService.authorisation; }); } getLicenseInfo() { return this.requestCortexAPI(this, new LicenseInfo(AuthenticationService.authorisation.token), data => new License(data.result.isOnline, data.result.license)); } static getAuthToken() { return this.authorisation.token; } requestCortexAPI(context, request, onSuccess, onError) { return new Promise((resolve, reject) => { context.socket.send(JSON.stringify(request)); context.socket.onmessage = (message) => { try { let data = JSON.parse(message.data); if (data['id'] == request.id) { console.debug(`Cortex Response for the request ${request.method}:`, data); resolve(onSuccess(data)); } } catch (error) { console.error(error); if (onError) { onError(error); } reject(error); } }; }); } }