minibraun minibraun - 19 days ago 5
Ajax Question

Send RS232 data from an always running while-loop Python script to HTML via AJAX?

I'm a bit new to AJAX and using serial ports, hope you can guide me.

I have a measuring device that sends data over an RS232 port to a web server.
My website has to display that data in a constantly refreshing manner.

In order to achieve this, I'm using a python script with the Pyserial API.
The measuring device has to be initialized with an "I" command and asked for measurement data with an "M" command.

I am using AJAX to constantly reopen this python script every 250 milliseconds trough a middleman php file that just runs an exec command. And it gets the job done. But I feel that's an incredibly stupid and tasking way to constantly be initializing and closing the connection again and again, and using php as a middle man for python-ajax comunication.

So my question is: Can data be sent from within a while-loop python file that is constantly running to my web page by AJAX or some other means?

My python script:rs232.py

import json
import random
import time
import serial

port = "COM3"
baudrate = 9600
ser = serial.Serial(port, baudrate,bytesize=serial.SEVENBITS,parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=True)

if ser.isOpen():
start=1;
cmd="I"
ser.write((cmd +'\r\n').encode())
out = ''
time.sleep(0.08)
while ser.inWaiting() > 0:
out += (ser.read(1)).decode()

cmd="M"
ser.write((cmd +'\r\n').encode())
out = ''
time.sleep(0.08)
while ser.inWaiting() > 0:
out += (ser.read(1)).decode()

if out != '':
my_string=out

ser.close()

new=[x.strip() for x in my_string.split(',')]
x1=float(new[-1])


D = {'x1':x1, 'start': start}

print (json.dumps(D))


My php middle man:rs232.php

<?php
$python="C:\........\python.exe";
$result=json_decode(exec($python.' rs232.py'), true);
$x1=$result['x1'];
$y=array("x1" => $x1);
echo json_encode($y);
?>


And my javascript code:page.php

$(function() {
var repeat= function(){
$.ajax({
type: "GET",
url: "config/rs232.php",
success: function(data) {
var rs232data=JSON.parse(data);
document.getElementById("militron").innerHTML=rs232data.x1;
}
});
}

setInterval(function(){repeat()}, 250);
});

Answer

Following the second suggestion in my comment, here's what you can do on your server. You could constantly write to a text file after some delay.

import time

number = 0
while(True):
    # Keeping some delay here, replace this with pyserial code
    time.sleep(1)
    number = number + 1
    f = open("serial_data.txt", 'w')
    f.write(str(number))
    f.close()

Now in your PHP script,

<?php
    $data = file_get_contents('serial_data.txt');
    echo $data;
?>