Singleton class manages serial communication

To implement a singleton pattern for serial communication in a Flask application, ensuring that only one instance of the serial communication exists, you can follow this simple example.

First, install the pyserial library for serial communication:

pip install pyserial

Next, create a Flask app and a singleton serial communication class:

from flask import Flask, jsonify, request
import serial
import threading

app = Flask(__name__)

class SerialSingleton:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls, port='COM3', baudrate=9600):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super(SerialSingleton, cls).__new__(cls)
                    cls._instance.serial = serial.Serial(port, baudrate)
        return cls._instance

    def read(self):
        if self.serial.is_open:
            return self.serial.readline().decode('utf-8').strip()
        return None

    def write(self, data):
        if self.serial.is_open:
            self.serial.write(data.encode('utf-8'))

@app.route('/read', methods=['GET'])
def read_serial():
    serial_instance = SerialSingleton()
    data = serial_instance.read()
    return jsonify({'data': data})

@app.route('/write', methods=['POST'])
def write_serial():
    data = request.json.get('data', '')
    serial_instance = SerialSingleton()
    serial_instance.write(data)
    return jsonify({'status': 'success', 'data': data})

if __name__ == '__main__':
    app.run(debug=True)

Explanation:

  1. SerialSingleton Class: This singleton class manages serial communication and uses a thread lock for thread safety. It opens the serial port only when the instance is created for the first time.
  2. read and write Methods: These methods are for reading from and writing to the serial port.
  3. Flask Routes:
  • /read: A GET request to read data from the serial port.
  • /write: A POST request to write data to the serial port. The request body should be in JSON format, e.g., {"data": "your_data"}.

Running the App:

After starting the Flask app, you can communicate with the serial port as follows:

  • To read serial data: GET /read
  • To write serial data: POST /write with a body of {"data": "your_data"}.

Make sure to set the correct serial port and baud rate before running the Flask app.

No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
Previous
Next