最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Getting data from serial port of a digital scale with Javascript or PHP? - Stack Overflow

programmeradmin2浏览0评论

I don't know if it's actually possible but I need to get the weight from a digital scale for trucks either with JavaScript or PHP.

Currently the scale is connected to a PC that is extremely slow and runs Windows XP along with a custom software developed by the pany that made the scale to keep a registry of the different vehicles that get weighed each day.

Unfortunately the PC can't be upgraded since I would lose all the drivers and the software doesn't work on a newer version of Windows.

I was thinking that if I can municate with the serial device and get the data, either through Javascript or PHP, and get the weight same as the custom software does, then I could make a small webpage with PHP and a MYSQL backend that does the same thing that the custom software does but with all the functionality that I'm actually missing and upgrade the PC.

I bought a serial to USB adapter and connected the device to my Windows 10 laptop and it appears that it's transmitting data correctly as you can see in this picture

I've searched for ways to municate with a serial device with Javascript and I think that with NodeJS you can do it but I don't know if I can implement that to a webpage. Also I haven't written anything in C or C++ or C# so I don't know how I would do it from any of those languages (a lot of the answers I saw were to do it using one of those).

I also saw that there is a chrome app called chrome.serial but I haven't found any working examples that would indicate me on how to proceed.

Any help would be greatly appreciated!!! :)

I don't know if it's actually possible but I need to get the weight from a digital scale for trucks either with JavaScript or PHP.

Currently the scale is connected to a PC that is extremely slow and runs Windows XP along with a custom software developed by the pany that made the scale to keep a registry of the different vehicles that get weighed each day.

Unfortunately the PC can't be upgraded since I would lose all the drivers and the software doesn't work on a newer version of Windows.

I was thinking that if I can municate with the serial device and get the data, either through Javascript or PHP, and get the weight same as the custom software does, then I could make a small webpage with PHP and a MYSQL backend that does the same thing that the custom software does but with all the functionality that I'm actually missing and upgrade the PC.

I bought a serial to USB adapter and connected the device to my Windows 10 laptop and it appears that it's transmitting data correctly as you can see in this picture

I've searched for ways to municate with a serial device with Javascript and I think that with NodeJS you can do it but I don't know if I can implement that to a webpage. Also I haven't written anything in C or C++ or C# so I don't know how I would do it from any of those languages (a lot of the answers I saw were to do it using one of those).

I also saw that there is a chrome app called chrome.serial but I haven't found any working examples that would indicate me on how to proceed.

Any help would be greatly appreciated!!! :)

Share Improve this question asked Jan 25, 2020 at 16:39 Marcos Silva LepeMarcos Silva Lepe 511 silver badge5 bronze badges 2
  • Can you try to use PHP Serial library? – Anggara Commented Jan 25, 2020 at 16:44
  • I'll take a look at it right now. Thanks!!! – Marcos Silva Lepe Commented Jan 25, 2020 at 17:05
Add a ment  | 

4 Answers 4

Reset to default 1

One way is to set up an Node.js Environment and then try out serial.io

https://serialport.io/

I have fiund this, maybe this is the way to go.

For Real-Time applications, Node.js is the way to go along with socket.io, for real-time updates on your website

I have just done this using PHP and Powershell. Let powershell read serial port and dump the data to a file in your xampp. Then PHP can be used to read the file and serve as REST call handler. You can make Ajax call to localhost to get data.

Setup xampp on your machine Open Poweshell in Administrator mode and execute the below mand. This will set the powershell restriction free. Otherwise ps1 script cannot be run on the run.

    Set-ExecutionPolicy Unrestricted

Create a directory in xampp/htdocs/weight. I called it weight and you can call anything you want. Create .ps1 script in the folder with following code

Start-Process PowerShell -Verb RunAs
$COM = [System.IO.Ports.SerialPort]::getportnames()
function read- {
    $port= new-Object System.IO.Ports.SerialPort $COM,9600,None,8,one
    $port.Open()
    do {
        $line = $port.ReadLine() | Out-File -FilePath C:\xampp\htdocs\weight\weight.txt
        Write-Host $line # Do stuff here
    }
    while ($port.IsOpen)
}
read-

Add a PHP file. I called it weightUtil.php. Add the following code into it.

<?php
header("Access-Control-Allow-Origin: *");
    $data = '';
    $myFileName = "weight.txt";
    $myfile = fopen($myFileName, "r") or die("Unable to open file!");
    if(filesize($myFileName) > 0){
        $data = fread($myfile,filesize($myFileName));
    } 
    echo $data;

    fclose($myfile);
?>

You are now set and ready. Run the tomcat server from Xampp control panel and you are ready to receive weight with POST request. You can make post call to http://localhost/weight/weightUtil.php

If you find any issues with rights to access file in C drive, simply add everyone with full access to xampp. Things will then run smooth.

Well... I couldn't get it done with PHP after trying a script and trying to get it to work in Linux because in Windows the script can only write and not read the data from the device.

I went with Node and serial.io following the advice from Ifaruki (thanks for that!!) and with the following script I was able to correctly read the data from the scale

var SerialPort = require('serialport');
var io = require('socket.io').listen(3000);

var serialPort = new SerialPort("COM4", {
    baudRate: 9600,
    parser: new SerialPort.parsers.Readline("\n"),
    dataBits: 7,
    parity: 'none',
    stopBits: 1,
    flowControl: false
});

io.sockets.on('connection', function(socket){
    socket.on('message', function(msg){
        console.log(msg);
    });

    socket.on('disconnected', function(){
        console.log('disconnected');
    });
});

var clearData = "";
var readData = "";

serialPort.on('open',function(){
    console.log('open');
    serialPort.on('data', function(data){
        const buf2 = Buffer.from(data)
        let wArray = buf2.toString('utf8');
        //this part just removes characters I don't need from the data
        let wSlice = wArray.slice(3, wArray.length);
        let rawWeight = wSlice.slice(0, -3);
        let fWeight = rawWeight.trim();
        let weight = parseInt(fWeight);
        console.log(weight);
    });
});

setTimeout(function(){
    serialPort.close(function(){
        console.log("Port Closed!");
    });
}, 3000);

I'm not really familiarized with Node.

What I need to do now is to run this function inside a browser so I can spit out the data from the device in a webpage... Please if anyone could point me in the right direction....

The best way to do it much more friendly and a better performance you need to do it using Node.js, and if are not familiar with it then move toward php or Asp. As you use asp or php it will work but didnt give you much more performance or you will get a little bit time to get the output. I have created it using asp you can take a same reference for other languages also.Below sharing you a code for better understand:

**Backend Code:**

' Web method to fetch weight data from weightbridge
    <WebMethod()>
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
    Public Shared Function fetchWeightFromBackend() As String
        Dim weight As String = String.Empty
        Try
            Using weightBridgePort As New SerialPort()
                weightBridgePort.PortName = "COM4" ' Specify the correct COM port for your weightbridge
                weightBridgePort.BaudRate = 9600 ' Specify the baud rate (typically 9600 for weightbridges)
                weightBridgePort.Parity = Parity.None
                weightBridgePort.DataBits = 8
                weightBridgePort.StopBits = StopBits.One
                weightBridgePort.Handshake = Handshake.None
                weightBridgePort.Encoding = System.Text.Encoding.Default
                weightBridgePort.ReadTimeout = 5000 ' Set read timeout in milliseconds
                weightBridgePort.Open()

                ' Send mand to weightbridge to request weight
                weightBridgePort.WriteLine("W")

                ' Read response from weightbridge
                weight = weightBridgePort.ReadLine().Trim()
            End Using
        Catch ex As Exception
            ' Handle exception if reading fails
            Console.WriteLine("Error reading weight: " & ex.Message)
        End Try

        Return weight
    End Function

**Frontend code to Call the Webmethod:**

    // Fetch weight from the backend when clicking the button
                $("#btnFetchWeight").on("click", function (event) {
                event.preventDefault()
                    $.ajax({
                        type: "POST",
                        url: "Dashboard.aspx/fetchWeightFromBackend",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            var weight = response.d;
    
                         weight = weight.replace('=+', '');
    
                            $("#weight").val(weight); // Update the weight input field with fetched weight
                        },
                        error: function (xhr, status, error) {
                            console.error("Error fetching weight:", status, error);
                        }
                    });
                }); 
发布评论

评论列表(0)

  1. 暂无评论