minibraun minibraun - 1 year ago 81
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

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():
ser.write((cmd +'\r\n').encode())
out = ''
while ser.inWaiting() > 0:
out += (

ser.write((cmd +'\r\n').encode())
out = ''
while ser.inWaiting() > 0:
out += (

if out != '':


new=[x.strip() for x in my_string.split(',')]

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

print (json.dumps(D))

My php middle man:rs232.php

$result=json_decode(exec($python.''), true);
$y=array("x1" => $x1);
echo json_encode($y);

And my javascript code:page.php

$(function() {
var repeat= function(){
type: "GET",
url: "config/rs232.php",
success: function(data) {
var rs232data=JSON.parse(data);

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

Answer Source

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
    # Keeping some delay here, replace this with pyserial code
    number = number + 1
    f = open("serial_data.txt", 'w')

Now in your PHP script,

    $data = file_get_contents('serial_data.txt');
    echo $data;