Created
July 4, 2020 20:36
-
-
Save schott12521/5d7712fae1162842c0d5d016423b342a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
// ############# | |
// Reads data from tag and tries to call Sonos API with spotify URI from tag | |
// ############# | |
import { NFC, CONNECT_MODE_DIRECT } from '../src/index'; | |
import pretty from './pretty-logger'; | |
const request = require('request'); | |
const nfc = new NFC(); // const nfc = new NFC(pretty); // optionally you can pass logger to see internal debug logs | |
nfc.on('reader', async reader => { | |
// enable when you want to auto-process ISO 14443-4 tags (standard=TAG_ISO_14443_4) | |
reader.aid = 'F222222222'; | |
// Disable beeper :) | |
try { | |
await reader.connect(CONNECT_MODE_DIRECT); | |
await reader.setBuzzerOutput(false); | |
await reader.disconnect(); | |
} catch (err) { | |
pretty.info(`initial sequence error`, reader, err); | |
} | |
reader.on('card', async card => { | |
// example reading 36 bytes assuming containing 16bit integer | |
try { | |
// reader.read(blockNumber, length, blockSize = 4, packetSize = 16) | |
// - blockNumber - memory block number where to start reading | |
// - length - how many bytes to read | |
// - blockSize - 4 for MIFARE Ultralight, 16 for MIFARE Classic | |
// ! Caution! length must be divisible by blockSize (we have to read the whole block(s)) | |
// Read 36 bytes from the album tag, which is the exact length in bytes of: | |
// spotify:album:2dfTV7CktUEBkZCHiB7VQB | |
const data = await reader.read(4, 36); | |
pretty.info(`data read`, reader, data); | |
const payload = bufferToString(data); | |
sendRequestToSonos(payload); | |
pretty.info(`data converted`, reader, payload); | |
} catch (err) { | |
pretty.error(`error when reading data`, reader, err); | |
} | |
}); | |
reader.on('error', err => { | |
pretty.error(`an error occurred`, reader, err); | |
}); | |
reader.on('end', () => { | |
pretty.info(`device removed`, reader); | |
}); | |
}); | |
nfc.on('error', err => { | |
pretty.error(`an error occurred`, err); | |
}); | |
function bufferToString(buffer) { | |
return buffer.toString('utf8'); | |
} | |
function sendRequestToSonos(musicRequestParameters) { | |
let sonosRoomName = "Living%20Room"; | |
request('http://localhost:5005/' + sonosRoomName + '/spotify/now/' + musicRequestParameters, { json: true }, (err, res, body) => { | |
if (err) { | |
pretty.error("Error while sending request to sonos", err); | |
} | |
pretty.info("Response received from sonos API", body); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment