Skip to content

Commit

Permalink
release 3.1.3
Browse files Browse the repository at this point in the history
  • Loading branch information
grzegorz914 committed Sep 6, 2024
1 parent f68a623 commit 4242d86
Show file tree
Hide file tree
Showing 7 changed files with 467 additions and 360 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### After update to v3.0.0 RESTFull and MQTT config settings need to be updated

## [3.1.3] - (06.09.2024)

## Changes

- refactor web and local api connect code
- cleanup

## [3.1.0] - (23.08.2024)

## Changes
Expand Down
89 changes: 63 additions & 26 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ class XboxPlatform {
}
this.accessories = [];

//check if prefs directory exist
//create directory if it doesn't exist
const prefDir = path.join(api.user.storagePath(), 'xboxTv');
if (!fs.existsSync(prefDir)) {
fs.mkdirSync(prefDir);
};
try {
fs.mkdirSync(prefDir, { recursive: true });
} catch (error) {
log.error(`Prepare directory error: ${error.message ?? error}`);
return;
}

api.on('didFinishLaunching', async () => {
for (const device of config.devices) {
Expand Down Expand Up @@ -45,30 +48,64 @@ class XboxPlatform {
};
const debug1 = debugMode ? log.info(`Device: ${deviceHost} ${deviceName}, Config: ${JSON.stringify(config, null, 2)}`) : false;

//check files exists, if not then create it
const postFix = deviceHost.split('.').join('');
const authTokenFile = `${prefDir}/authToken_${postFix}`;
const devInfoFile = `${prefDir}/devInfo_${postFix}`;
const inputsFile = `${prefDir}/inputs_${postFix}`;
const inputsNamesFile = `${prefDir}/inputsNames_${postFix}`;
const inputsTargetVisibilityFile = `${prefDir}/inputsTargetVisibility_${postFix}`;

// Create files if it doesn't exist
try {
const files = [
authTokenFile,
devInfoFile,
inputsFile,
inputsNamesFile,
inputsTargetVisibilityFile,
];

files.forEach((file) => {
if (!fs.existsSync(file)) {
fs.writeFileSync(file, '');
}
});
} catch (error) {
log.error(`Device: ${deviceHost} ${deviceName}, prepare files error: ${error}`);
return;
}

//xbox device
const xboxDevice = new XboxDevice(api, prefDir, device);
xboxDevice.on('publishAccessory', (accessory) => {
api.publishExternalAccessories(CONSTANTS.PluginName, [accessory]);
log.success(`Device: ${deviceHost} ${deviceName}, published as external accessory.`);
})
.on('devInfo', (devInfo) => {
log.info(devInfo);
try {
const xboxDevice = new XboxDevice(api, device, authTokenFile, devInfoFile, inputsFile, inputsNamesFile, inputsTargetVisibilityFile);
xboxDevice.on('publishAccessory', (accessory) => {
api.publishExternalAccessories(CONSTANTS.PluginName, [accessory]);
log.success(`Device: ${deviceHost} ${deviceName}, published as external accessory.`);
})
.on('success', (message) => {
log.success(`Device: ${deviceHost} ${deviceName}, ${message}`);
})
.on('message', (message) => {
log.info(`Device: ${deviceHost} ${deviceName}, ${message}`);
})
.on('debug', (debug) => {
log.info(`Device: ${deviceHost} ${deviceName}, debug: ${debug}`);
})
.on('warn', (warn) => {
log.warn(`warn: ${deviceHost} ${deviceName}, ${warn}`);
})
.on('error', (error) => {
log.error(`Device: ${deviceHost} ${deviceName}, ${error}`);
});
.on('devInfo', (devInfo) => {
log.info(devInfo);
})
.on('success', (message) => {
log.success(`Device: ${deviceHost} ${deviceName}, ${message}`);
})
.on('message', (message) => {
log.info(`Device: ${deviceHost} ${deviceName}, ${message}`);
})
.on('debug', (debug) => {
log.info(`Device: ${deviceHost} ${deviceName}, debug: ${debug}`);
})
.on('warn', (warn) => {
log.warn(`warn: ${deviceHost} ${deviceName}, ${warn}`);
})
.on('error', (error) => {
log.error(`Device: ${deviceHost} ${deviceName}, ${error}`);
});

await xboxDevice.start();
} catch (error) {
log.error(`Device: ${deviceHost} ${deviceName}, Did finish launching error: ${error}`);
}
}
});
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"displayName": "Xbox TV",
"name": "homebridge-xbox-tv",
"version": "3.1.2",
"version": "3.1.3",
"description": "Homebridge plugin to control Xbox game consoles.",
"license": "MIT",
"author": "grzegorz914",
Expand Down
44 changes: 44 additions & 0 deletions src/impulsegenerator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"use strict";
const EventEmitter = require('events');

class ImpulseGenerator extends EventEmitter {
constructor() {
super();
this.timersState = false;
}

start(timers) {
if (this.timersState) {
this.stop();
}

this.timers = [];
for (const timer of timers) {
const newTimer = setInterval(() => {
this.emit(timer.name);
}, timer.sampling);
this.timers.push(newTimer);
};

//update state
this.timersState = true;
this.emit('state', true);
}

stop() {
if (this.timersState) {
this.timers.forEach(timer => clearInterval(timer));
}

//update state
this.timers = [];
this.timersState = false;
this.emit('state', false);
}

state() {
this.emit('state', this.timersState);
return this.timersState;
}
}
module.exports = ImpulseGenerator;
73 changes: 44 additions & 29 deletions src/localApi/xboxlocalapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class XBOXLOCALAPI extends EventEmitter {
super();

this.crypto = new SGCrypto();

this.udpType = Net.isIPv6(config.host) ? 'udp6' : 'udp4';
this.host = config.host;
this.xboxLiveId = config.xboxLiveId;
this.tokensFile = config.tokensFile;
Expand All @@ -33,18 +33,23 @@ class XBOXLOCALAPI extends EventEmitter {
this.mediaRequestId = 0;
this.emitDevInfo = true;
this.startPrepareAccessory = true;
};

//dgram socket
this.connect = () => {
const udpType = Net.isIPv6(this.host) ? 'udp6' : 'udp4';
const socket = Dgram.createSocket(udpType);
//dgram socket
async connect() {
try {
const socket = Dgram.createSocket(this.udpType);
socket.on('error', (error) => {
this.emit('error', `Socket error: ${error}`);
socket.close();
}).on('close', () => {
}).on('close', async () => {
const debug = this.debugLog ? this.emit('debug', 'Socket closed.') : false;
this.isConnected = false;
this.reconnect();
try {
await this.reconnect();
} catch (error) {
this.emit('error', error)
};
}).on('message', async (message, remote) => {
const debug = this.debugLog ? this.emit('debug', `Received message from: ${remote.address}:${remote.port}`) : false;
this.heartBeatStartTime = Date.now();
Expand Down Expand Up @@ -353,14 +358,20 @@ class XBOXLOCALAPI extends EventEmitter {
const prepareAccessory = this.startPrepareAccessory && !this.isConnected ? this.emit('prepareAccessory') : false;
this.startPrepareAccessory = false;
}).bind();
};

this.connect();
return true;
} catch (error) {
throw new Error(`Connect error: ${error}`);
};
};

async reconnect() {
await new Promise(resolve => setTimeout(resolve, 5000));
this.connect();
try {
await this.connect();
} catch (error) {
throw new Error(`Reconnect error: ${error}`);
}
};

async readToken() {
Expand All @@ -370,7 +381,7 @@ class XBOXLOCALAPI extends EventEmitter {
const tokenData = parseData.xsts.Token.length > 0 ? parseData : false;
return tokenData;
} catch (error) {
throw new Error(`Read token error: ${error}`);
throw new Error(`Read token error: ${error}`);
}
}

Expand All @@ -389,7 +400,7 @@ class XBOXLOCALAPI extends EventEmitter {

return true;
} catch (error) {
throw new Error(error);
throw new Error(error);
};
};

Expand All @@ -405,7 +416,7 @@ class XBOXLOCALAPI extends EventEmitter {
await this.sendSocketMessage(message, 'acknowledge');
return true;
} catch (error) {
throw new Error(error);
throw new Error(error);
};
}

Expand All @@ -424,7 +435,7 @@ class XBOXLOCALAPI extends EventEmitter {
await this.sendSocketMessage(message, 'channelStartRequest');
return true;
} catch (error) {
throw new Error(error);
throw new Error(error);
}
}

Expand All @@ -451,7 +462,7 @@ class XBOXLOCALAPI extends EventEmitter {
this.emit('disconnected', 'Power On failed, please try again.');
} catch (error) {
this.emit('disconnected', 'Power On error, please try again.');
throw new Error(error);
throw new Error(error);
};
};

Expand All @@ -472,7 +483,7 @@ class XBOXLOCALAPI extends EventEmitter {
await this.disconnect();
return true;
} catch (error) {
throw new Error(error);
throw new Error(error);
};

};
Expand All @@ -492,7 +503,7 @@ class XBOXLOCALAPI extends EventEmitter {
await this.sendSocketMessage(message, 'recordGameDvr');
return true;
} catch (error) {
throw new Error(error);
throw new Error(error);
};
};

Expand All @@ -506,7 +517,7 @@ class XBOXLOCALAPI extends EventEmitter {
const channelOpen = this.channels[requestId].open;

if (channelCommunicationId === -1 || !channelOpen) {
this.emit('warn', `Channel Id: ${channelCommunicationId}, state: ${channelOpen ? 'Open' : 'Closed'}, trying to open it.`);
this.emit('warn', `Channel Id: ${channelCommunicationId}, state: ${channelOpen ? 'Open' : 'Closed'}, trying to open it.`);
};

command = CONSTANTS.LocalApi.Channels.System[channelName][command];
Expand All @@ -531,7 +542,7 @@ class XBOXLOCALAPI extends EventEmitter {
await this.sendSocketMessage(message, 'gamepadUnpress');
}, 150)
} catch (error) {
this.emit('warn', `Send system input command error: ${error}`)
this.emit('warn', `Send system input command error: ${error}`)
};
break;
case 1:
Expand All @@ -551,7 +562,7 @@ class XBOXLOCALAPI extends EventEmitter {
const message = json.pack(this.crypto, sequenceNumber1, this.sourceParticipantId, channelCommunicationId);
this.sendSocketMessage(message, 'json');
} catch (error) {
this.emit('warn', `Send tv remote command error: ${error}`)
this.emit('warn', `Send tv remote command error: ${error}`)
};
break;
case 2:
Expand All @@ -568,7 +579,7 @@ class XBOXLOCALAPI extends EventEmitter {
this.sendSocketMessage(message, 'mediaCommand');
this.mediaRequestId++;
} catch (error) {
this.emit('warn', `Send system media command error: ${error}`)
this.emit('warn', `Send system media command error: ${error}`)
};
break;
}
Expand Down Expand Up @@ -598,7 +609,7 @@ class XBOXLOCALAPI extends EventEmitter {
this.emit('disconnected', 'Disconnected.');
return true;
} catch (error) {
throw new Error(error);
throw new Error(error);
};
};

Expand All @@ -612,14 +623,18 @@ class XBOXLOCALAPI extends EventEmitter {
const offset = 0;
const length = message.byteLength;

this.socket.send(message, offset, length, 5050, this.host, (error, bytes) => {
if (error) {
throw new Error(error);
}
try {
this.socket.send(message, offset, length, 5050, this.host, (error, bytes) => {
if (error) {
throw new Error(error);
}

const debug = this.debugLog ? this.emit('debug', `Socket send: ${type}, ${bytes}B.`) : false;
return true;
});
const debug = this.debugLog ? this.emit('debug', `Socket send: ${type}, ${bytes}B.`) : false;
return true;
});
} catch (error) {
throw new Error(`Socket send error: ${error}`);
};
};
};
module.exports = XBOXLOCALAPI;
Loading

0 comments on commit 4242d86

Please sign in to comment.