Trip
Trip

Reputation: 13

Send and read serial data from a PHP Desktop app using Node.js or PHP

As written in the title I made a stand alone web app using PHP Desktop, and now i want it to send and read data from a serial port.

I tried first to use this PHP Serial class (https://github.com/rubberneck/php-serial), but i had some problems, particularly on reading data, so i moved to javascript and node.js.

I installed Node.js and, using npm, serialport and ws packages, and I made the serialport work only with the node command on Windows cmd. I tried to follow some examples and extend the code to my PHP Desktop App using also the ws package but nothing seems to work and now I don't know how to go on.

Do you guys have any kind of suggestion? (Particularly on how to go on with the ws package)

What's the best solution to do this?

Thanks in advance.

Here's the code that I used:

PHP code:

<?php

session_start();
include_once 'PhpSerial.php';

if(isset($_POST['serial'])) {


    $serial = new phpSerial;

    $serial->deviceSet("COM3");

    $serial->deviceOpen('w+') ;

    $serial->confBaudRate(115200);

    $serial->sendMessage($_POST['serial'],1);

    $_SESSION['serial_data'] = $serial->readPort();

    $serial->deviceClose(); 

}

else
    header('Location: index.php');

?>

JS code: (without the ws part, that didn't want to work)

var serialport = require('serialport');

var portName = "COM3";

var myPort = new serialport(portName, {
    baudRate: 115200
});

myPort.on('open', showPortOpen);
myPort.on('data', readSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);

function showPortOpen() {
   console.log('port open. Data rate: ' + myPort.baudRate);
}

function readSerialData(data) {
   console.log(data);
}

function showPortClose() {
   console.log('port closed.');
}

function showError(error) {
   console.log('Serial port error: ' + error);
}

Upvotes: 1

Views: 412

Answers (0)

Related Questions