Displaying serial data of python in the web - python

I have the following program of python which displays serial data in the command prompt.
#!python
import time
import cgi
from serial import Serial
import subprocess
ser = Serial('COM4', 115200, timeout=1)
print("connected to: " + ser.portstr)
while True:
# Read a line and convert it from b'xxx\r\n' to xxx
line = ser.readline().decode('utf-8')[:-2]
if line: # If it isn't a blank line
print(line)
if line == '520':
subprocess.call(["xte", "key Up"])
elif line == '620':
subprocess.call(["xte", "key Down"])
elif line == '110':
break
ser.close()
This program is running perfect. The data is being constantly displayed in the console. Basically it is displaying the distance from a ping sensor I want to display the data in the web page http://localhost/distance.html. How will I do it? Displaying only the last data will be fine. Thanks for all the suggestions

Write the data to a file. Serve that file with a webserver like for example Apache.

Related

"write_timeout" not working in Serial() in pyserial

I am trying to make a program which constantly reads data being sent from device using serial port to computer. In addition to this whenever I enter something it is sent to device.(My main aim is to make a serial terminal emulator).
I wrote following program but it waits for any input and does not constantly read data and display on screen sent by device as thought:
ser1 = serial.Serial(com_name_to_use, auto_baud, timeout=0, write_timeout=0)
while True:
try:
# Writing Section
inp_str1 = input() # + "\n"
str1 = inp_str1.encode(encoding="ascii")
ser1.write(str1)
time.sleep(0.03)
# Reading Section
bf = ser1.readline()
print(str(bf, encoding="utf-8"), end="")
except Exception as err1:
pass
Kindly, tell how to fix it.

python: proc.comunicate hangs

I'm trying to start another script in python and then give an answer to input, this is the main script:
import subprocess
import sys
import platform
cmdline = ['py', 'ciao.py']
cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in cmd.stdout:
if line == b'Loading...\r\n':
print("sending data...")
cmd.communicate(b"test\n")[0]
print("done")
print(line)
print(line)
And this is ciao.py:
import os
import re
import time
print("Loading...")
ciao = input("> ")
print(ciao)
os.system("mkdir okfunziona")
print("Done")
while 1:
time.sleep(10)
The main script manages to send "test" but then hangs and does not print "done" to the console.
The problem is both on windows and on linux.
---------------------------------------------------------------EDIT--------------------------------------------------------------
Ok i have tested Ashish Nitin Patil's example but i see b'Loading...\r\n' output, and I do not see the other outputs of the secondary script, like ">" or "Done", it seems that the "cmd.stdout.readline ()" works only the first time because the script does not end.
See this answer (and others on that question) for inspiration. For your case, you should not be using communicate, instead use stdin.write and stdout.readline.
Your main script might look like below -
while True:
line = cmd.stdout.readline()
print(line)
if line.strip() == b'Loading...':
print("sending data...")
cmd.stdin.write(b"test\n")
cmd.stdin.close()
print("done")
elif line.strip() == b'Done':
break
The outputs -
b'Loading...\n'
sending data...
5
done
b'> test\n'
b'Done\n'

Serial data reading from Raspberry Pi

I am trying to capture my temperature sensor reading from Arduino Uno, turn on AC if temperature is high or off and then send temperature to Raspberry Pi and write to a log file.
My Python code in Raspberry Pi to capture event and log to a file.
import time
import datetime
import serial
now = datetime.datetime.now()
month=time.strftime("%Y_%m")
#f= open(month+".txt","w+")
f=open("temperature.log","w+")
ser = serial.Serial('/dev/ttyACM0', 9600) # enable the serial port
print 'before while'
while 1: # execute the loop forever
val=ser.readline()
# read the serial data sent by the UNO
f.write(now.strftime("%Y-%m-%d %H:%M"))
# print the serial data sent by UNO
f.write(' -> ')
f.write(val)
f.close()
I can get the temperature value (sometimes it's a mess 16707), but most importantly it does not write to the log file.
Where am I missing? Do I have to include another library in the Python code?
You are closing the log file at the end of each loop. It should run once, but after the file is closed, it won't write again until you open it. Just put f.close() after the while loop. Or as a better practice:
ser = serial.Serial('/dev/ttyACM0', 9600)
with open("temperature.log", "w+") as f:
print 'before while'
while 1:
val = ser.readline()
f.write(now.strftime("%Y-%m-%d %H:%M"))
f.write(' -> ')
f.write(val)
This will close the file automatically once the code inside the with statement is finished.

throwing exception SerialException: device reports readiness to read but returned no data

My raspberry pi is connected to microcontroller over serial pin. I am trying to read the data from the serial port. The script reads the data for few seconds. However, it terminates throwing following exception
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
I have used following python code
#!/usr/bin/python
import serial
import time
serialport = serial.Serial("/dev/ttyAMA0", 115200, timeout=.5)
while 1:
response = serialport.readlines(None)
print response
time.sleep(.05)
serialport.close()
Here is the code you should be using if you are seriously trying to just transfer and print a file:
for line in serialport.readlines().split('\n'):
print line
------------------------------------------------------------
I believe you are having problems because you are using readlines(None) instead of readline() Readline() reads it a line at a time, and will wait for each one. If reading a whole file it will be slower than readlines. But readlines() expects a whole file all at once. It is obviously not waiting for your serial transfer speed.
--------------------------------------------------
My data-logging loop receives a line every two minutes and writes it to a file. It could easily just print each line like you show in the OP.
readine() waits for each line. I have tested it to wait up to 30 minutes between lines with no problems by altering the program on the Nano.
import datetime
import serial
ser = serial.Serial("/dev/ttyUSB0",9600) --/dev/ACM0 is fine
while True :
linein = ser.readline()
date = str(datetime.datetime.now().date())
date = date[:10]
time = str(datetime.datetime.now().time())
time = time[:8]
outline = date + tab + time + tab + linein
f = open("/home/pi/python/today.dat","a")
f.write(outline)
f.close()
Maybe changing to this approach would be better for you.

How to print telnet response line by line?

Is it possible to print the telnet response line by line, when a command executed over telnet keeps on responding over console ?
Example: I have executed a command (to collect logs), It keeps on displaying logs on console window. Can we read the response line by line & print it , without missing any single line ?
Below snippet writes the log, but only after certain specified time. If I stop the service/script (CTRL-C) in between, that doesn't write anything.
import sys
import telnetlib
import time
orig_stdout = sys.stdout
f = open('outpuy.txt', 'w')
sys.stdout = f
try:
tn = telnetlib.Telnet(IP)
tn.read_until(b"pattern1")
tn.write(username.encode('ascii') + b"\n")
tn.read_until(b"pattern2")
tn.write(command1.encode('ascii') + b"\n")
z = tn.read_until(b'abcd\b\n',600)
array = z.splitlines( )
except:
sys.exit("Telnet Failed to ", IP)
for i in array:
i=i.strip()
print(i)
sys.stdout = orig_stdout
f.close()
You can use tn.read_until("\n") in a loop in order to read one line durint execution of your telnet command
while True:
line = tn.read_until(b"\n") # Read one line
print(line)
if b'abcd' in line: # last line, no more read
break
You can use the ready_very_eager, read_eager, read_lazy, and ready_very_lazy functions specified in the documentation to read your stream byte-by-byte. You can then handle the "until" logic on your own code and at the same time write the read lines to the console.

Categories

Resources