Skip to content

Commit

Permalink
Return to each action == new WS. Hard to get async responses.
Browse files Browse the repository at this point in the history
  • Loading branch information
Toxblh committed Nov 14, 2020
1 parent 21d94f5 commit 30c4009
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 52 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const config = {
debug: true, // Default: false
ip: '192.168.1.2',
mac: '123456789ABC',
name: 'NodeJS-Test', // Default: NodeJS
nameApp: 'NodeJS-Test', // Default: NodeJS
port: 8001, // Default: 8002
token: '12345678',
}
Expand Down
2 changes: 1 addition & 1 deletion example/index-dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const config = {
debug: true, // Default: false
ip: '192.168.1.2',
mac: '123456789ABC',
name: 'NodeJS-Test', // Default: NodeJS
nameApp: 'NodeJS-Test', // Default: NodeJS
saveToken: true
}

Expand Down
2 changes: 1 addition & 1 deletion example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const config = {
debug: true, // Default: false
ip: '192.168.1.2',
mac: '123456789ABC',
name: 'NodeJS-Test', // Default: NodeJS
nameApp: 'NodeJS-Test', // Default: NodeJS
port: 8002, // Default: 8002
token: '12345678',
}
Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/samsung.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe('Tests 8001', () => {
expect(control).toHaveProperty('LOGGER.DEBUG', config.debug)
expect(control).toHaveProperty(
'WS_URL',
'ws://192.168.1.2:8001/api/v2/channels/samsung.remote.control?name=Tm9kZUpTIFJlbW90ZQ== &token=12345678'
'ws://192.168.1.2:8001/api/v2/channels/samsung.remote.control?name=Tm9kZUpTIFJlbW90ZQ==&token=12345678'
)
})
})
Expand Down
67 changes: 19 additions & 48 deletions src/samsung.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ class Samsung {
private SAVE_TOKEN: boolean
private TOKEN_FILE = path.join(__dirname, 'token.txt')
private WS_URL: string
private ws: WebSocket | null = null
private wsTimeout: NodeJS.Timeout | null = null

constructor(config: Configuration) {
if (!config.ip) {
Expand Down Expand Up @@ -59,12 +57,7 @@ class Samsung {
if (this.SAVE_TOKEN) {
this.TOKEN = this._getTokenFromFile() || ''
}

this.WS_URL = `${this.PORT === 8001 ? 'ws' : 'wss'}://${this.IP}:${
this.PORT
}/api/v2/channels/samsung.remote.control?name=${this.NAME_APP}${
this.TOKEN !== '' ? ` &token=${this.TOKEN}` : ''
}`
this.WS_URL = this._getWSUrl()

this.LOGGER.log(
'internal config',
Expand Down Expand Up @@ -101,6 +94,7 @@ class Samsung {
const sToken = String(token)
this.LOGGER.log('got token', sToken, 'getToken')
this.TOKEN = sToken
this.WS_URL = this._getWSUrl()

if (this.SAVE_TOKEN) {
this._saveTokenToFile(sToken)
Expand Down Expand Up @@ -334,34 +328,28 @@ class Samsung {
* If you don't need to keep connection, you can to close immediately
*/
public closeConnection() {
this.wsClose()
// backward compatibility
}

private _send(
command: Command,
done?: (err: null | (Error & { code: string }), res: WSData | null) => void,
eventHandle?: string
) {
if (!this.ws) {
this.ws = new WebSocket(this.WS_URL, { rejectUnauthorized: false })
} else {
this.wsKeepAlive()
}
const ws = new WebSocket(this.WS_URL, { rejectUnauthorized: false })

this.LOGGER.log('command', command, '_send')
this.LOGGER.log('wsUrl', this.WS_URL, '_send')

this.ws.on('open', () => {
ws.on('open', () => {
if (this.PORT === 8001) {
setTimeout(() => this.ws && this.ws.send(JSON.stringify(command)), 1000)
setTimeout(() => ws.send(JSON.stringify(command)), 1000)
} else {
if (this.ws) {
this.ws.send(JSON.stringify(command))
}
ws.send(JSON.stringify(command))
}
})

this.ws.on('message', (message: string) => {
ws.on('message', (message: string) => {
const data: WSData = JSON.parse(message)

this.LOGGER.log('data: ', JSON.stringify(data, null, 2), 'ws.on message')
Expand All @@ -377,18 +365,18 @@ class Samsung {

if (data.event !== 'ms.channel.connect') {
this.LOGGER.log('if not correct event', JSON.stringify(data, null, 2), 'ws.on message')
// this.ws.close()
ws.close()
}

// TODO, additional check on available instead of ws.open
// if(data.event == "ms.channel.connect") { _sendCMD() }
})

this.ws.on('response', (response: WebSocket.Data) => {
ws.on('response', (response: WebSocket.Data) => {
this.LOGGER.log('response', response, 'ws.on response')
})

this.ws.on('error', (err: Error & { code: string }) => {
ws.on('error', (err: Error & { code: string }) => {
let errorMsg = ''
if (err.code === 'EHOSTUNREACH' || err.code === 'ECONNREFUSED') {
errorMsg = 'TV is off or unavalible'
Expand All @@ -399,33 +387,8 @@ class Samsung {
done(err, null)
}
})

this.ws.on('close', () => {
this.wsClearTimeout()
this.ws = null
})
}

private wsKeepAlive() {
this.LOGGER.log('wsKeepAlive', {})
this.wsClearTimeout()
this.wsTimeout = setTimeout(() => this.wsClose(), 60 * 1000)
}

private wsClearTimeout() {
this.LOGGER.log('wsClearTimeout', {})
if (this.wsTimeout) {
clearTimeout(this.wsTimeout)
this.wsTimeout = null
}
}

private wsClose() {
this.LOGGER.log('wsClose', {})
if (this.ws) {
this.ws.close()
}
}

private _sendPromise(command: Command, eventHandle?: string): Promise<WSData | null> {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -568,6 +531,14 @@ class Samsung {
return null
}
}

private _getWSUrl() {
return `${this.PORT === 8001 ? 'ws' : 'wss'}://${this.IP}:${
this.PORT
}/api/v2/channels/samsung.remote.control?name=${this.NAME_APP}${
this.TOKEN !== '' ? `&token=${this.TOKEN}` : ''
}`
}
}

export default Samsung

0 comments on commit 30c4009

Please sign in to comment.