1

I have been trying to get the credit card data from Desko Keyboard which I eventually succeeded but the problem is I'm getting card data in a different pattern every time I swipe

Below is my JS code

var fs = require('Serialport');
function listenDevice() {
  this.port = fs('COM8');
  let dataComplete = '';
  let count = 0;
  this.port.on('open', () => {
    console.log('sp: ' + this.port.path + ' port open event');
    this.port.set({ dtr: true, rts: true }, function (err) {
      if (err) {
        console.log('Set Error: ', err.message);
        this.isServiceError = true;
        this.serviceErrorText = err;
      }
    });
  });

  this.port.on('data', (data) => {
    console.log('sp: Data: ', data.toString('utf-8'));
  });
}

This is the Pattern of the card data I'm getting:

sp: Data: CBZZZZZZZZZZZZZZZZ^XXXXXXXX sp: Data: XXXX X ^18082261485500005000000 !ZZZZZZZZZZZZZZZZ sp: Data: =1808226000005

sp: Data: CBZZZZZZZZZZZZZZZZ^XXXXXXXX sp: Data: XXXX X ^18082261485 sp: Data: 500005000000 !ZZZZZZZZZZZZZZZZ=1808226000005

sp: Data: CBZZZZZZZZZZZZZZZZ^XXXXXXXX sp: Data: XXXX X ^18082261485500005000000 !ZZZZZZZZZZZZZZZZ=1808226000005

Here X denotes the Card Holder Name Z denotes the Card Number

As you can sp: Data:log has been called twice or thrice but the card data is similar. I want to concat this card data no matter how the data is coming. Any idea.

And I'm using serial port to read the data

  • Like this? `dataComplete += data.toString('utf-8')` – adiga Jan 25 '19 at 06:29
  • I can do that but when I can actually get this coz the on data function calls two or three times – Vinodh Kumar C Jan 25 '19 at 07:10
  • So per card this function is triggered 9 times? – adiga Jan 25 '19 at 07:27
  • No No... keeping the reference of above logs. Below "This is the Pattern of the card I'm getting:" The first two lines are on first swipe, the second two lines are on swiping same card on second time and so on. To answer your question, on first time it triggered two times (you can see sp: Data: printed twice there) – Vinodh Kumar C Jan 25 '19 at 07:49

1 Answers1

1

You can't assume you'll have all the data in a single data event. You need to buffer data, and using the information you know about the protocol, determine when you have enough.

Since you're only expecting a small amount of data, it's acceptable to have a running buffer of data concatenated together.

You'll want to do something like this:

let buffer;
this.port.on('data', (data) => {
  buffer = Buffer.concat([buffer, data]);
  if (/* your code to determine if you have enough data */) {
    const packet = buffer.slice(0, /* expected length */);
    buffer = buffer.slice(/* expected length*/);
    console.log(packet.toString());
  }
});
Brad
  • 159,648
  • 54
  • 349
  • 530