I created such a mini program
from flask import Flask, request, jsonify
import serial
app = Flask(__name__)
ser = serial.Serial('COM3', 9600, timeout=1)
@app.route('/send', methods=['POST'])
def send():
data = request.get_json().get('data', '')
if data:
write_to_port(ser, data)
response = read_full_response(ser)
return jsonify({"message": response}), 200
else:
return jsonify({"error": "No data provided"}), 400
@app.route('/read', methods=['GET'])
def read():
reading = read_from_port(ser)
return jsonify({"message": reading}), 200
def read_from_port(ser):
reading = ser.readline().decode('utf-8').strip()
print('Read:', reading)
return reading
def write_to_port(ser, data):
ser.write(data.encode())
print(f"Written: {data}")
def read_full_response(ser):
response = b""
while True:
if ser.in_waiting:
chunk = ser.read(ser.in_waiting)
response += chunk
if b"x00" in chunk:
break
return response.decode('utf-8').strip()
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
On one computer it works fine, on the other I get an error
Traceback (most recent call last):
File "C:terminalmain.py", line 8, in <module>
ser = serial.Serial('COM3', 9600, timeout=1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersAdminAppDataLocalProgramsPythonPython312Libsite-packagesserialserialwin32.py", line 33, in __init__
super(Serial, self).__init__(*args, **kwargs)
File "C:UsersAdminAppDataLocalProgramsPythonPython312Libsite-packagesserialserialutil.py", line 244, in __init__
self.open()
File "C:UsersAdminAppDataLocalProgramsPythonPython312Libsite-packagesserialserialwin32.py", line 64, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM3': PermissionError(13, 'Access is denied.', None, 5)
As far as I could check, there are no other programs.
I turned off and on this device in the Manager – does not help.
I run the cmd command as an administrator. Maybe someone else has ideas?