# ABA POS SDK for Node.js

An official Node.js Addons for ABA POS SDK developed by ABA Bank (Advanced Bank of Asia Ltd.). This package allows you to connect with the ABA POS terminal from these supported platforms: Windows (x64, arm64), macOS (x64, arm64), and Linux (x64, arm64).

## Driver Installation
The driver might already come with Windows Update if you use Windows 10 or 11. To verify if you have
the driver installed, you need to:

* Connect ABA POS to your POS system via a USB cable.
* On Windows, open Device Manager > Ports (COM & LPT). Check the listed devices:
  * Prolific USB-to-Serial Comm Port
  * Prolific PL2303GT USB Serial COM Port
  * Prolific PL2303GC USB Serial COM Port
  * USB Serial Device (COMXX)
  * Or something similar.
If you cannot find the USB device after you plug in the ABA POS USB cable, you can get the latest official
USB driver from:
    * WizarPOS Q2, Q2P: https://www.prolific.com.tw/en/portfolio-item/pl2303gs/
    * WizarPOS Q2Pro: https://smartpossdk.gitbook.io/cloudpossdk/faq/usb-serial-port/install-terminal-usb-drivers

* On macOS, you need to install the official driver from AppStore here:
https://apps.apple.com/us/app/pl2303-serial/id1624835354

* On Linux, please contact our ABA Terminal Integration Team via any channel (Telegram, Email, etc)

## Additional Software Installation
On Windows, you'll need to install Microsoft Visual C++ Redistributable (VC_redist.x64.exe or VC_redist.arm64.exe) if you could not load the aba-pos-sdk-node. Link: https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist

## Import Module
You need to import AbaPosSdk and AbaPosSdkError from this module: 'aba-pos-sdk-node'.

```agsl
const { AbaPosSdk, AbaPosSdkError } = require('aba-pos-sdk-node');
```

* Define a function to handle an error
```agsl
function onSdkError(error) {
    if (error instanceof AbaPosSdkError) {
        // You can handle the specific error code and message.
        const errorCode = error.errorCode;
        const errorMessage = error.errorMessage;

        // Or just get the formatted error message.
        const formattedMessage = error.toString();

        console.error(formattedMessage);
    } else {
        console.error('Something went wrong:', error);
    }
}
```

## Using USB Serial Port:
You need to connect ABA POS terminal to your POS system (PC, ECR, Kiosk, etc) and follow the code sample below.

Note: It's not recommended to replace the USB cable that comes with the POS terminal. Please report any issues with the
cable to ABA Bank.

```agsl
try {
    // A new key will be provided by ABA Bank to use with the production POS terminal.
    const key ='001116A775D266AE67DF1F6CA9C7F071';
    await AbaPosSdk.initUsbConnection(key);

    const invoiceId = new Date().toISOString()
    const data = `{"CMD":"SALE","TYPE":"ALL","QRTYPE":"ALL","AMT":"0.01","CURRCODE":"USD","TIMESTAMP":"${AbaPosSdk.generateTimestamp()}","ECRREF":"${invoiceId}"}`;

    // The timeout in milliseconds. You can increase the timeout if it's too fast.
    const timeoutMs = 60000;

    console.log("Send data to ABA POS. Waiting for response...");
    const response = await AbaPosSdk.sendDataByUsb(data, timeoutMs);
    
    if (response) {
        console.log('Response received:', response);
    } else {
        // Response can be empty if it's timeout, or you have called AbaPosSdk.cancelWaitingPosTerminal()
        console.log('No response!');
    }
} catch (error) {
    onSdkError(error);
}
```

## Using Wi-Fi (IP Address):

To use Wi-Fi (IP Address) connectivity, your POS system (PC, ECR, Kiosk, etc) and the ABA POS terminal must be
connected to the same Wi-Fi router/hotspot.

* On macOS, during the development, you also need to sign your app. Otherwise, your app will be blocked by the Firewall, and it cannot send or receive the response. \
```sudo codesign --force --deep --sign - MyApp.app```

```
// Here is an example if you are developing an app using Electron framework.
sudo codesign --force --deep --sign - node_modules/electron/dist/Electron.app
```

```agsl
try {
    // A new key will be provided by ABA Bank to use with the production POS terminal.
    const key = '001116A775D266AE67DF1F6CA9C7F071';
    
    // You can see the IP address on ABA POS App.
    const ipAddress = '192.168.0.1';
    await AbaPosSdk.initIpConnection(ipAddress, key);

    // If you want to change the IP address at runtime, please use:
    // await AbaPosSdk.updateIpAddress(newIpAddress)
    
    const invoiceId = new Date().toISOString()
    const data = `{"CMD":"SALE","TYPE":"ALL","QRTYPE":"ALL","AMT":"0.01","CURRCODE":"USD","TIMESTAMP":"${AbaPosSdk.generateTimestamp()}","ECRREF":"${invoiceId}"}`;
    
    // The timeout in milliseconds. You can increase the timeout if it's too fast.
    const timeoutMs = 60000;

    console.log("Send data to ABA POS. Waiting for response...");
    const response = await AbaPosSdk.sendDataByIp(data, timeoutMs);
    
    if (response) {
        console.log('Response received:', response);
    } else {
        // Response can be empty if it's timeout, or you have called AbaPosSdk.cancelWaitingPosTerminal()
        console.log('No response!');
    }
} catch (error) {
    onSdkError(error);
}
```

## Cancel Waiting for ABA POS Terminal:

Normally, after the request is sent to the ABA POS terminal, the SDK will wait for a response until it times out. You can also stop this waiting and perform another transaction if you want. 

* Note: this command only works for CMD: "SALE", "PRE-AUTH", and "PRE-AUTH COMP"

The example
below works for any connectivity:

```agsl
new Promise(async () => {
  console.log("Cancel waiting POS terminal...");

  // This will stop the SDK from waiting.
  await AbaPosSdk.cancelWaitingPosTerminal();

  const data = `{"CMD":"CANCEL","TIMESTAMP":"${AbaPosSdk.generateTimestamp()}"}`;

  // If you are using USB serial port, please use this method.
  await AbaPosSdk.sendDataByUsb(data, 10000)

  // Or if you are using Wi-Fi (IP Address), please use this method.
  await AbaPosSdk.sendDataByIp(data, 10000)
});
```

## Getting the Logs From the SDK:

You can also get the log from the SDK by following the sample code below:

```agsl
// Set the directory where you want the SDK to keep all the log files.
// Here, it'll generate a directory 'ABA_Logs' inside the current directory.
await AbaPosSdk.setLogDirectoryPath('ABA_Logs');
```

## Releasing resources used by the SDK:

It's recommended to release the resources used by the SDK after you stop using it.

* If you are using a USB serial port:  \
```await AbaPosSdk.releaseUsbConnection();```

* Or if you are using Wi-Fi (IP Address):  \
```await AbaPosSdk.releaseIpConnection();```

```agsl
// Here is an example for the Electron app:
app.on('window-all-closed', async () => {
    if (process.platform !== 'darwin') {

        // Release all the resources used by the SDK. 
        await AbaPosSdk.releaseUsbConnection();
        await AbaPosSdk.releaseIpConnection();

        app.quit();
    }
});
```

## Exception Handling:
If you want to handle the error in specific cases, you can also check these error codes from this class ```AbaQrSdkError``` below:

```agsl
try {
  // Calling any method from AbaPosSdk
} catch (error) {
  if (error instanceof AbaPosSdkError) {
    // You can handle the specific error code and message.
    const errorCode = error.errorCode;
    const errorMessage = error.errorMessage;

    // Or just get the formatted error message.
    const formattedMessage = error.toString();

    console.error(formattedMessage);
  } else {
    console.error('Something went wrong:', error);
  }
}
```

| Error Code  | Description                           |
| :---        |    :----                             |
| 1           | Open serial port error                |
| 2           | Read serial port error                |
| 3           | Write serial port error               |
| 4           | Open socket error                     |
| 5           | Write socket error                    |
| 6           | Read socket error                     |
| 7           | Invalid IP address                    |
| 8           | Invalid hash                          |
| 9           | No device found                       |
| 10          | Unsupported platform                  |
| 1000        | Unknown error                         |
| -10001      | Invalid argument                      |
| -10002      | File operation error                  |
| -10003      | Memory error                          |
| -10004     | Illegal state error                   |

## Other Available Functionalities
To know more about other functionalities offered by ABA POS and more details about the request and response, please see the document ```ABA POS Integration Specification.pdf``` provided by the ABA Team. Please do not hesitate to contact us if you have any questions.

## Changelog
## [1.0.7]
- Added Changelog in README.md and remove CHANGELOG.md from package. NPM doesn't support it.

## [1.0.6]
- Fixed: Missing CHANGELOG.md file.

## [1.0.5]
- Added CHANGELOG.md to see what's new in each release

## [1.0.4]
- Support macOS Arm64 and Windows Arm64
- Breaking changes: _waitForResponse() is private now. You should get response from sendDataByUsb and sendDataByIp directly.
- Remove broken Linux core library. The new core library will be available in the next release.
- Fixed: Never receive response after sending data.

## [1.0.3]
- Bug fixes

## [1.0.2]
- Bug fixes

## [1.0.1]
- Bug fixes

## [1.0.0]
- Initial release