I have actually a USB Device plug on my computer.
This device allow me to read NFC but when I'm putting my NFC to be red the navigator (Chrome) returned me this error message :
Uncaught (in promise) DOMException: Failed to execute 'claimInterface' on 'USBDevice': The requested interface implements a protected class.
My code is the next one :
var usbd = {};
let device;
let deviceEndpoint = 0x02;
let powerUpDevice = new Uint8Array([0x62,0x00, 0x00, 0x00, 0x00,0x00,0x00,0x01,0x00, 0x00]).buffer;
let getCardUID = new Uint8Array([0xff,0xca,0x00,0x00,0x04]).buffer;
(function() {
'use strict';
usbd.authorize = function(){
navigator.usb.requestDevice({ filters: [{ vendorId: 0x072f }] })
.then(selectedDevice => {
device = selectedDevice;
console.log(device.configuration.interfaces[0].interfaceNumber);
console.log(device.manufacturerName);
console.log(device.productName);
console.log(device);
return device.open()
.then(() => {
if (device.configuration === null) {
return device.selectConfiguration(1);
}
});
})
.then(() => device.claimInterface(0))
.then(() => device.transferOut(deviceEndpoint, powerUpDevice)
.then(transferResult => {
console.log(transferResult);
}, error => {
console.log(error);
device.close();
})
.catch(error => {
console.log(error);
})
);
};
usbd.getDevice = function(){
return navigator.usb.getDevices().then(devices => {
return devices.map(device => new usbd.device(device));
});
};
usbd.device = function(device) {
this.device_ = device;
};
usbd.getTagUID = function(){
device = this.getDevice();
device
.then(device => {
device[0].device_.open()
.then(() => device[0].device_.claimInterface(0))
.then(() => device[0].device_.transferOut(deviceEndpoint, getCardUID)
.then(transferResult => {
console.log(transferResult);
}, error => {
console.log(error);
device[0].device_.close();
})
.catch(error => {
console.log(error);
})
)
.then(() => device[0].device_.claimInterface(0))
.then(() => device[0].device_.transferIn(deviceEndpoint, 16)
.then(USBInTransferResult => {
if (USBInTransferResult.data) {
console.log(USBInTransferResult.data.getUint32(0));
}
}, error => {
console.log(error);
device[0].device_.close();
})
.catch(error => {
console.log(error);
})
);
});
};
$('#connect').click(function(){
usbd.authorize();
});
$('#readCard').click(function(){
usbd.getTagUID();
});
})();
How can I do to read my NFC on my website ?
Related
I am trying to make a video call on my project and I am using simple-peer to connect 2 peers. I can see all of console.log on Node.js but can get console.log(4) on React. I am not fully understood to WebRTC yet so please understand my broken codes...
This is my code with React.
const myVideo = useRef();
const userVideo = useRef();
const connectionRef = useRef();
const roomName = "123";
const [stream, setStream] = useState();
let creator = false;
useEffect(() => {
const socket = io("url");
socket.emit("joinRoom", roomName);
socket.on("created", () => {
creator = true;
navigator.mediaDevices
.getUserMedia({ video: true, audio: true })
.then((stream) => {
setStream(stream);
myVideo.current.srcObject = stream;
});
});
socket.on("joined", () => {
navigator.mediaDevices
.getUserMedia({ video: true, audio: true })
.then((stream) => {
setStream(stream);
userVideo.current.srcObject = stream;
});
socket.emit("ready", roomName);
});
socket.on("ready", () => {
if (creator) {
const peer = new Peer({ initiator: true, trickle: false, stream });
peer.on("signal", (signal) => {
socket.emit("sendingSignal", {
signal,
roomName,
});
});
peer.on("stream", (stream) => {
userVideo.current.srcObject = stream;
});
socket.on("receivingSignal", (signal) => {
peer.signal(signal);
});
connectionRef.current = peer;
}
});
socket.on("offer", (incomingSignal) => {
console.log(incomingSignal);
if (!creator) {
const peer = new Peer({ initiator: false, trickle: false, stream });
console.log(peer);
console.log(1);
peer.on("signal", (signal) => {
socket.emit("returningSignal", { signal, roomName });
console.log(2);
});
console.log(3);
peer.on("stream", (stream) => {
userVideo.current.srcObject = stream;
console.log(4);
});
console.log(5);
peer.signal(incomingSignal);
console.log(6);
connectionRef.current = peer;
}
});
}, []);
And this is my code with Node.js.
io.on(“connection”, (socket) => {
console.log(1)
socket.on(‘joinRoom’, (roomName)=>{
let rooms = io.sockets.adapter.rooms;
let room = rooms.get(roomName);
console.log(2)
if (room == undefined) {
console.log(2.1)
socket.join(roomName);
socket.emit(“created”);
console.log(2.2)
} else if (room?.size == 1) {
console.log(2.3)
socket.join(roomName);
socket.emit(“joined”);
console.log(2.4)
} else {
socket.emit(“full”);
console.log(2.5)
}
});
socket.on(“ready”, function (roomName) {
socket.broadcast.to(roomName).emit(“ready”);
});
socket.on(‘sendingSignal’,({signal, roomName})=>{
console.log(3)
console.log({signal,roomName})
io.to(roomName).emit(“offer”,signal)
console.log(3.5)
})
socket.on(“returningSignal”, ({ signal, roomName }) => {
console.log({signal, roomName})
console.log(4)
io.to(roomName).emit(“receivingSignal”, signal)
console.log(4.5)
});
})
In backend program, i use new Promise(resolve, reject). When it success post data to database, it will output empty. How make it output "success! article_id: 1"?
const createArticle = (insertValues) =>
{
return new Promise((resolve, reject) =>
{
connectionPool.getConnection((connectionError, connection) =>
{
if(connectionError)
{
reject(connectionError);
}
else
{
connection.query('Insert into Article set?', insertValues, (error, result) =>
{
if(error)
{
console.error('sql error: ', error);
reject(error);
}
else if (result.affectedRows === 1)
{
console.log(result.insertId);
resolve(`success! article_id: ${result.insertId}`);
}
connection.release();
});
}
});
});
};
i use the program to call createArticle.
const articlePost = (req, res) =>
{
const insertValues = req.body;
articleModule.createArticle(insertValues).then((result) =>{
res.sent(result);
}).catch((err) => { return res.send(err); });
};
My specs are behaving weirdly in that when I run the tests alone, they pass. However, when I run the test suite all together, the failure tests still continue to use the success axios mock instead of using the correct failing http axios mock. This results in my tests failing. Am I missing something for isolating the 2 mocks from each other in the different portions of code?
jobactions.js
export const loadUnassignedJobs = (job_type) => {
if (!['unscheduled', 'overdue'].includes(job_type)) {
throw 'Job Type must be "unscheduled" or "overdue".';
}
return (dispatch) => {
dispatch({type: JobActionTypes.LOAD_UNASSIGNED_JOBS_STARTED, job_type });
return axios.get(defaults.baseapi_uri + 'jobs/' + job_type)
.then(function (response) {
dispatch(updateUnassignedJobs(response.data.jobs));
// handle success
})
.catch(function (error) {
// handle error
dispatch({ type: JobActionTypes.LOAD_UNASSIGNED_JOBS_FAILURE, error });
})
.then(function () {
// always executed
});
}
};
export const updateUnassignedJobs = (unassigned_jobs) => {
let unassigned_job_ids = [];
let jobs = {};
for (let job of unassigned_jobs) {
unassigned_job_ids.push(job.id);
jobs[job.id]=job;
}
return({
type: JobActionTypes.LOAD_UNASSIGNED_JOBS_SUCCESS,
jobs,
unassigned_job_ids,
});
};
spec.js
import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import * as jobActions from "../../../app/javascript/actions/JobActions"
import { findAction } from '../support/redux_store'
import * as JobActionTypes from '../../../app/javascript/constants/JobActionTypes'
import fixtures_jobs_unscheduled_success from '../fixtures/jobs_unscheduled_success'
import moxios from "moxios";
export const mockStore = configureMockStore([thunk]);
let store;
describe ('loadUnassignedJobs', () => {
context('when bad parameters are passed', async () => {
it('will raise an error', () => {
const store = mockStore();
expect(() => {
store.dispatch(jobActions.loadUnassignedJobs('wrong_type'));
}).to.throw('Job Type must be "unscheduled" or "overdue".');
});
});
context('when unscheduled is passed', () => {
beforeEach(() => {
moxios.install();
console.log("before each called");
console.log(moxios.requests);
store = mockStore();
store.clearActions();
});
afterEach(() => {
console.log("after each called");
console.log(moxios.requests);
moxios.uninstall();
});
context('on success', () => {
beforeEach(() => {
moxios.wait(() => {
let request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: fixtures_jobs_unscheduled_success
});
});
})
it('dispatches LOAD_UNASSIGNED_JOBS_STARTED', () => {
store.dispatch(jobActions.loadUnassignedJobs('unscheduled')).then(() => {
expect(findAction(store, JobActionTypes.LOAD_UNASSIGNED_JOBS_STARTED)).to.be.eql({
type: JobActionTypes.LOAD_UNASSIGNED_JOBS_STARTED,
job_type: 'unscheduled'
});
});
});
it('dispatches updateUnassignedJobs()', () => {
store.dispatch(jobActions.loadUnassignedJobs('unscheduled')).then(() => {
expect(findAction(store,JobActionTypes.LOAD_UNASSIGNED_JOBS_SUCCESS)).to.be.eql(jobActions.updateUnassignedJobs(fixtures_jobs_unscheduled_success.jobs))
});
});
});
context('on error', () => {
beforeEach(() => {
//console.log("before each on error called");
//console.log(moxios.requests);
moxios.wait(() => {
console.log('after waiting for moxios..')
console.log(moxios.requests);
let request = moxios.requests.mostRecent();
request.respondWith({
status: 500,
response: { error: 'internal server error' }
});
});
})
it('dispatches LOAD_UNASSIGNED_JOBS_FAILURE', (done) => {
console.log(moxios.requests);
store.dispatch(jobActions.loadUnassignedJobs('unscheduled')).then(() => {
console.log(moxios.requests);
console.log(store.getActions());
expect(findAction(store, JobActionTypes.LOAD_UNASSIGNED_JOBS_FAILURE)).to.include({
type: JobActionTypes.LOAD_UNASSIGNED_JOBS_FAILURE
});
expect(findAction(store, JobActionTypes.LOAD_UNASSIGNED_JOBS_FAILURE).error).to.include({
message: 'Request failed with status code 500'
});
done();
});
});
it('does not dispatch LOAD_UNASSIGNED_JOBS_SUCCESS', (done) => {
store.dispatch(jobActions.loadUnassignedJobs('unscheduled')).then(() => {
expect(findAction(store, JobActionTypes.LOAD_UNASSIGNED_JOBS_SUCCESS)).to.be.undefined;
done();
});
});
})
});
});
describe('updateUnassignedJobs', () => {
it('assigns jobs to hash and creates an unassigned_job_ids array', () => {
expect(jobActions.updateUnassignedJobs([ { id: 1, step_status: 'all_complete' }, { id: 2, step_status: 'not_started' } ])).to.be.eql(
{
type: JobActionTypes.LOAD_UNASSIGNED_JOBS_SUCCESS,
jobs: { 1: { id: 1, step_status: 'all_complete' }, 2: { id: 2, step_status: 'not_started' } },
unassigned_job_ids: [ 1,2 ]
}
)
});
});
Found the issue!
The it() blocks for the success case were not using the done callback causing the afterEach() moxios.uninstall() to be called prematurely and not resetting the requests after the call was complete. Fixing this, and now all the tests pass.
I created two observables from a database:
const roomData$ = estab
.query()
.where('estab.type', 'like', 'rooms')
.then((rooms) => {
rooms.forEach((room) => {
observer.next(room.data);
});
});
}).map(data => ({
roomsData: [
...data.rooms,
],
}));
const hotelData$ = Observable.create((observer) => {
estab
.query()
.where('estab.type', 'like', 'hotels')
.then((hotels) => {
hotels.forEach((hotel) => {
observer.next(hotel.data);
});
});
}).map(data => ({
hotelsData: [
...data.hotels,
],
}));
const hotelContentData$ = Observable.concat(roomData$, hotelData$);
hotelContentData$.subscribe((data) => {
fs.appendFile('data.json', (err) => {
if (err) throw err;
console.log('file has been appended!);
}
})
In the data.json file I found only the data received from the roomData$ observable. I change the order in Observable.concat(hotelData$, roomData$) and now I get the data of hotel observable. Why only one Observable is executed? How can I execute both of them and get data from hotelData$ and roomData$?
Observable.concat will take emissions from a stream until that stream completes, and then move to the next stream. Since you're creating your own observable sequences, be sure to complete each one.
const roomData$ = Observable.create( observer => {
estab
.query()
.where('estab.type', 'like', 'rooms')
.then((rooms) => {
rooms.forEach((room) => {
observer.next(room.data);
});
observer.complete(); // adding this will complete your stream.
});
}).map(data => ({
roomsData: [
...data.rooms,
],
}));
const hotelData$ = Observable.create((observer) => {
estab
.query()
.where('estab.type', 'like', 'hotels')
.then((hotels) => {
hotels.forEach((hotel) => {
observer.next(hotel.data);
});
observer.complete(); // adding this will complete your stream.
});
}).map(data => ({
hotelsData: [
...data.hotels,
],
}));
const hotelContentData$ = Observable.concat(roomData$, hotelData$);
hotelContentData$.subscribe((data) => {
fs.appendFile('data.json', (err) => {
if (err) throw err;
console.log('file has been appended!);
});
});
I have a method which returns a promise like:
checkLogin(credentials) {
return new Promise((resolve, reject) => {
this.http.post(url, credentials)
.map(res => res.json())
.subscribe(
data => {
resolve(data);
},
err => {
reject(err);
}
);
});
}
I call this method inside another:
login(credentials) {
this.checkLogin(credentials)
.then(function(result) {
console.log("ok: ",result);
this.doAlert("ok");
})
.catch(function(err) {
console.log("error: ",err.message);
this.doAlert(err.message)
});
}
Here is where the error happens, it is said "TypeError: this.doAlert is not a function":
But the doAlert is in the same file than the others, and it works fine from other places (not promises calls)
doAlert(text) {
let alert = Alert.create({
title: 'Alert;,
subTitle: text,
buttons: ['Ok']
});
this.nav.present(alert);
}
Is it not possible to do this?
Use fat-arrow functions instead
login(credentials) {
this.checkLogin(credentials)
.then((result) => {
console.log("ok: ",result);
this.doAlert("ok");
})
.catch((err) => {
console.log("error: ",err.message);
this.doAlert(err.message)
});
}
to keep the scope
See also
- https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
- https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript
- What's the meaning of "=>" in TypeScript? (Fat Arrow)
Use arrow functions
login(credentials) {
this.checkLogin(credentials)
.then((result) => {
console.log("ok: ",result);
this.doAlert("ok");
})
.catch((err) => {
console.log("error: ",err.message);
this.doAlert(err.message)
});