1.0.0 • Published 4 months ago

commander-udp-pos v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
4 months ago

commander-udp-pos

Easy Commander POS with UDP

Install

npm install commander-udp-pos
npx cap sync

Quick intro

This plugin was developed for Android App with CapacitorJS. The plugin's main feature is to create a UDP connection to send data 1:1 from device to device on a local network, useful in cases where one device needs to receive information from another device within a local network.

šŸ“‹ļø Requirements

  • capacitor/android 7.x.x
  • capacitor/core 7.x.x

šŸ’»ļø Quick example

The best way to add the plugin to CapacitorJS app (ex: Angular) is creating a service, the following example is a suggestion of application and logic.

import { Injectable, NgZone } from '@angular/core';
import { PluginListenerHandle } from '@capacitor/core';
import { CommanderUdpPos as CUP, listenToMessages } from 'commander-udp-pos';

@Injectable({
  providedIn: 'root'
})
export class UdpServerService {
  private udpPort: number = 41234;
  listening!: PluginListenerHandle;

  constructor(private zone: NgZone) { }

  async initializeUdp(): Promise<void> {
    try {
      await CUP.listen({ port: this.udpPort });
      console.log(`Server UDP port listening: ${this.udpPort}`);

        // Listening local network messages from other device
      this.listening = listenToMessages((data) => {
        this.zone.run(async ()=>{
          const msg = await this.decompressText(data.message);
          const order = JSON.parse(msg);
          order.ip = data.senderAddress.replaceAll('/','');
          console.log(order);
          /* 
          * Here you can add logic, ex: new shared service for sending 
          * a menssage to other app section.
          */
        });
      });

    } catch (error) {
      console.error('Error starting UDP server:', error);
    }
  }

  private async sendMessage(message: string, address: string, port: number): Promise<void> {
    try {
      await CUP.sendMessage({
        message: message,
        address: address,
        port: port,
      });
    } catch (error) {
      console.error('Error sending UDP message:', error);
    }
  }

  // Adjust payload parameters or interface according to your application
  async sendOrder(payload: {ip: string; order: number; msg: string;}): Promise<void> {
      const message = await this.compressText(JSON.stringify({order: payload.order, msg: payload.msg}));
      const targetAddress = payload.ip;
      const targetPort = 41234;
      await this.sendMessage(message, targetAddress, targetPort);
  }

  async closeServer(): Promise<void> {
    try {
      this.listening.remove();
      await CUP.closeServer();
      console.log('Server UDP is closed: OK.');
    } catch (error) {
      console.error('Error closing UDP server:', error);
    }
  }

  private async compressText(text: string): Promise<string> {
    // Your method for compress text

    return text_compressed;
  }

  private async decompressText(compressedText: string): Promise<string> {
    // Your method for decompress text

    return text_uncompressed;
  }

}

The next step is to use the service in any component, that's all.

//...
import { UdpServerService } from '../services/udpServer.service';

// Example of interface
export interface Order {
  ip: string; 
  order: number; 
  msg: string;
}

//...
export class CommanderComponent implements OnInit, AfterViewInit, OnDestroy {
constructor(private cupService: UdpServerService, private sharedData: SharedDataService){}

  async ngAfterViewInit() {
    await this.cupService.initializeUdp();
  }

  async ngOnDestroy() {
    await this.cupService.closeServer();
  }

  ngOnInit(): void {
    /*
    * Here it could be have the shared service suscribed that process the upd message received in 
    * listener <listenToMessages> for logic into the angular-capacitor app.
    */ 
  }

  sendMessage(){
    this.cupService.sendOrder(this.payload);
  }
}

šŸ—’ļø Notes

The plugin can be used for various issues, such as activating devices within the same network (IoT) or exchanging metadata, and it is very important to use a compression or encryption method for the message to avoid sending and receiving problems.

The maximum DatagramPacket buffer is 8 KB (8192 bytes), consider this compressing large messages or sending them partially.

API

sendMessage(...)

sendMessage(options: { message: string; port: number; address: string; }) => Promise<void>
ParamType
options{ message: string; port: number; address: string; }

listen(...)

listen(options: { port: number; }) => Promise<void>
ParamType
options{ port: number; }

closeServer()

closeServer() => Promise<void>

šŸ“Œ Showcase Example

A real example of an application using this plugin:

šŸ”— See the app

Contact, Reports or Bugs

Thanks for checking out the project. You can take a peek about my work by visiting my website.

šŸŒ Website: Visit

NivarDev

1.0.0

4 months ago