├── requirements.txt ├── setup.py ├── LICENSE ├── example ├── app.py └── templates │ └── index.html ├── .gitignore ├── README.md └── flask_serial └── __init__.py /requirements.txt: -------------------------------------------------------------------------------- 1 | Click==7.0 2 | Flask==1.0.2 3 | itsdangerous==1.1.0 4 | Jinja2==2.10 5 | MarkupSafe==1.1.0 6 | pyserial==3.4 7 | Werkzeug==0.14.1 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """flask-serial Setup.""" 2 | from setuptools import setup 3 | from flask_serial import __version__ 4 | 5 | setup( 6 | name='flask-serial', 7 | version=__version__, 8 | url='https://github.com/RedFalsh/flask-serial.git', 9 | license='MIT', 10 | author='Redfalsh', 11 | author_email='13693421942@163.com', 12 | description='Flask extension for the Serial', 13 | long_description="https://github.com/RedFalsh/flask-serial/blob/master/README.md", 14 | long_description_content_type='text/markdown', 15 | packages=['flask_serial'], 16 | platforms='any', 17 | install_requires=[ 18 | 'Flask', 19 | 'typing', 20 | 'pyserial' 21 | ], 22 | classifiers=[ 23 | 'Development Status :: 5 - Production/Stable', 24 | 'Environment :: Web Environment', 25 | 'Intended Audience :: Developers', 26 | 'License :: OSI Approved :: MIT License', 27 | 'Programming Language :: Python', 28 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 29 | 'Topic :: Software Development :: Libraries :: Python Modules' 30 | ] 31 | ) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 RedFalsh 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /example/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from flask_serial import Serial 3 | from flask_socketio import SocketIO 4 | from flask_bootstrap import Bootstrap 5 | 6 | import json 7 | 8 | import eventlet 9 | eventlet.monkey_patch() 10 | 11 | app = Flask(__name__) 12 | app.config['SERIAL_TIMEOUT'] = 0.1 13 | app.config['SERIAL_PORT'] = 'COM1' 14 | app.config['SERIAL_BAUDRATE'] = 115200 15 | app.config['SERIAL_BYTESIZE'] = 8 16 | app.config['SERIAL_PARITY'] = 'N' 17 | app.config['SERIAL_STOPBITS'] = 1 18 | 19 | ser = Serial(app) 20 | socketio = SocketIO(app) 21 | bootstrap = Bootstrap(app) 22 | 23 | @app.route('/') 24 | def index(): 25 | return render_template('index.html') 26 | 27 | @socketio.on('send') 28 | def handle_send(json_str): 29 | data = json.loads(json_str) 30 | ser.on_send(data['message']) 31 | print("send to serial: %s"%data['message']) 32 | 33 | @ser.on_message() 34 | def handle_message(msg): 35 | print("receive a message:", msg) 36 | socketio.emit("serial_message", data={"message":str(msg)}) 37 | 38 | @ser.on_log() 39 | def handle_logging(level, info): 40 | print(level, info) 41 | 42 | if __name__ == '__main__': 43 | # Warning!!! 44 | # this must use `debug=False` 45 | # if you use `debug=True`,it will open serial twice, it will open serial failed!!! 46 | socketio.run(app, debug=False) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .idea/ 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | .pytest_cache/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | db.sqlite3 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # SageMath parsed files 83 | *.sage.py 84 | 85 | # Environments 86 | .env 87 | .venv 88 | env/ 89 | venv/ 90 | ENV/ 91 | env.bak/ 92 | venv.bak/ 93 | 94 | # Spyder project settings 95 | .spyderproject 96 | .spyproject 97 | 98 | # Rope project settings 99 | .ropeproject 100 | 101 | # mkdocs documentation 102 | /site 103 | 104 | # mypy 105 | .mypy_cache/ 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # flask-serial 2 | receive and send data of serial in Flask 3 | 4 | xx 5 | # install 6 | 7 | - download: 8 | 9 | `git clone https://github.com/RedFalsh/flask-serial.git` 10 | 11 | - install: 12 | 13 | `python setup.py install` 14 | 15 | # pip install 16 | 17 | `pip install flask-serial` 18 | 19 | # Usage 20 | 21 | ```python 22 | 23 | from flask import Flask 24 | from flask_serial import Serial 25 | 26 | app = Flask(__name__) 27 | app.config['SERIAL_TIMEOUT'] = 0.2 28 | app.config['SERIAL_PORT'] = 'COM2' 29 | app.config['SERIAL_BAUDRATE'] = 115200 30 | app.config['SERIAL_BYTESIZE'] = 8 31 | app.config['SERIAL_PARITY'] = 'N' 32 | app.config['SERIAL_STOPBITS'] = 1 33 | 34 | 35 | ser =Serial(app) 36 | 37 | @app.route('/') 38 | def use_serial(): 39 | return 'use flask serial!' 40 | 41 | @ser.on_message() 42 | def handle_message(msg): 43 | print("receive a message:", msg) 44 | # send a msg of str 45 | ser.on_send("send a str message!!!") 46 | # send a msg of bytes 47 | ser.on_send(b'send a bytes message!!!') 48 | 49 | @ser.on_log() 50 | def handle_logging(level, info): 51 | print(level, info) 52 | 53 | if __name__ == '__main__': 54 | app.run() 55 | 56 | ``` 57 | 58 | # Use With Socketio 59 | 60 | ```python 61 | 62 | from flask import Flask, render_template 63 | from flask_serial import Serial 64 | from flask_socketio import SocketIO 65 | from flask_bootstrap import Bootstrap 66 | 67 | import json 68 | 69 | import eventlet 70 | eventlet.monkey_patch() 71 | 72 | app = Flask(__name__) 73 | app.config['SERIAL_TIMEOUT'] = 0.1 74 | app.config['SERIAL_PORT'] = 'COM1' 75 | app.config['SERIAL_BAUDRATE'] = 115200 76 | app.config['SERIAL_BYTESIZE'] = 8 77 | app.config['SERIAL_PARITY'] = 'N' 78 | app.config['SERIAL_STOPBITS'] = 1 79 | 80 | ser = Serial(app) 81 | socketio = SocketIO(app) 82 | bootstrap = Bootstrap(app) 83 | 84 | @app.route('/') 85 | def index(): 86 | return render_template('index.html') 87 | 88 | @socketio.on('send') 89 | def handle_send(json_str): 90 | data = json.loads(json_str) 91 | ser.on_send(data['message']) 92 | print("send to serial: %s"%data['message']) 93 | 94 | @ser.on_message() 95 | def handle_message(msg): 96 | print("receive a message:", msg) 97 | socketio.emit("serial_message", data={"message":str(msg)}) 98 | 99 | @ser.on_log() 100 | def handle_logging(level, info): 101 | print(level, info) 102 | 103 | if __name__ == '__main__': 104 | # Warning!!! 105 | # this must use `debug=False` 106 | # if you use `debug=True`,it will open serial twice, it will open serial failed!!! 107 | socketio.run(app, debug=False) 108 | 109 | 110 | ``` 111 | 112 | -------------------------------------------------------------------------------- /example/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "bootstrap/base.html" %} 2 | {% block title %}Flask-Serial example{% endblock %} 3 | 4 | {% block styles %} 5 | {{ super() }} 6 | {% endblock %} 7 | 8 | {% block scripts %} 9 | {{ super() }} 10 | 11 | 12 | 30 | {% endblock %} 31 | 32 | {% block content %} 33 |
34 |
35 |
36 |

Flask-Serial Example

37 |
38 |
39 |
40 |
41 |
42 |
43 |

Send Serial Message

44 |
45 |
46 |
47 |
48 |
49 |
50 | 51 |
52 | 53 |
54 |
55 |
56 |
57 | 58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |

Receive Serial Messages

70 |
71 |
72 |
73 |
74 |
75 |
76 | 77 |
78 | 79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | {% endblock %} 90 | -------------------------------------------------------------------------------- /flask_serial/__init__.py: -------------------------------------------------------------------------------- 1 | """flask-serial Package. 2 | :author: Redfalsh <13693421942@163.com> 3 | :license: MIT, see license file or https://opensource.org/licenses/MIT 4 | :created on 2019-01-10 10:59:22 5 | :last modified by: Redfalsh 6 | :last modified time: 2019-01-10 11:00:00 7 | :describe: 8 | flask-serial package is used in flask website, it can receive or send serial's data, 9 | you can use it to send or receive some serial's data to show website with flask-socketio 10 | """ 11 | __version__ = "1.1.0" 12 | 13 | import serial 14 | import time 15 | import threading 16 | import collections 17 | 18 | SERIAL_LOG_INFO = 0x01 19 | SERIAL_LOG_NOTICE = 0x02 20 | SERIAL_LOG_WARNING = 0x04 21 | SERIAL_LOG_ERR = 0x05 22 | SERIAL_LOG_DEBUG = 0x6 23 | 24 | class Ser: 25 | """serial class,use thire library: pyserial""" 26 | def __init__(self): 27 | # default serial args 28 | self.serial = serial.Serial() 29 | self.serial.timeout = 0.1 30 | self.serial.port = "COM1" 31 | self.serial.baudrate = 9600 32 | self.serial.bytesize = 8 33 | self.serial.parity = "N" 34 | self.serial.stopbits = 1 35 | self.max_recv_buf_len = 255 36 | 37 | self._out_packet = collections.deque() 38 | # serial receive threading 39 | self._thread = None 40 | self._thread_terminate = False 41 | self.serial_alive = False 42 | 43 | self._on_message = None 44 | self._on_send = None 45 | self._on_log = None 46 | self._logger = None 47 | # callback mutex RLock 48 | self._callback_mutex = threading.RLock() 49 | self._open_mutex = threading.Lock() 50 | 51 | def loop_start(self): 52 | self._thread = threading.Thread(target=self.loop_forever) 53 | self._thread.setDaemon(True) 54 | self._thread.start() 55 | 56 | def loop_forever(self): 57 | run = True 58 | while run: 59 | if self.serial_alive: 60 | break 61 | else: 62 | with self._open_mutex: 63 | self._open_serial() 64 | time.sleep(1) 65 | while self.serial_alive: 66 | time.sleep(0.1) 67 | while run: 68 | try: 69 | b = self.serial.read(self.max_recv_buf_len) 70 | if not b: 71 | break 72 | self._handle_on_message(b) 73 | self._easy_log(SERIAL_LOG_INFO, "serial receive message:%s", b) 74 | except Exception as e: 75 | pass 76 | 77 | def _open_serial(self): 78 | """try to open the serial""" 79 | if self.serial.port and self.serial.baudrate: 80 | try: 81 | if self.serial.isOpen(): 82 | self._close_serial() 83 | self.serial.open() 84 | except serial.SerialException as e: 85 | # print("[ERR] open serial error!!! %s" % e) 86 | # self._easy_log(SERIAL_LOG_ERR, "open serial error!!! %s", e) 87 | raise 88 | else: 89 | self.serial_alive = True 90 | self._thread = threading.Thread(target=self._recv) 91 | self._thread.setDaemon(True) 92 | self._thread.start() 93 | # print("[INFO] open serial success: %s / %s"%(self.serial.port, self.serial.baudrate)) 94 | self._easy_log(SERIAL_LOG_INFO, "open serial success: %s / %s",self.serial.port, self.serial.baudrate) 95 | else: 96 | print("[ERR] port is not setting!!!") 97 | self._easy_log(SERIAL_LOG_ERR, "port is not setting!!!") 98 | 99 | def _close_serial(self): 100 | try: 101 | self.serial.close() 102 | self.serial_alive = False 103 | self._thread_terminate = False 104 | except: 105 | pass 106 | 107 | def _recv(self): 108 | """serial recv thread""" 109 | while self.serial_alive: 110 | time.sleep(0.1) 111 | while self.serial_alive: 112 | try: 113 | b = self.serial.read(self.max_recv_buf_len) 114 | if not b: 115 | break 116 | # s = str(binascii.b2a_hex(b).decode('utf-8')).upper() 117 | self._handle_on_message(b) 118 | self._easy_log(SERIAL_LOG_INFO, "serial receive message:%s", b) 119 | except Exception as e: 120 | pass 121 | # self.serial_alive = False 122 | # self._easy_log(SERIAL_LOG_ERR, "serial err:%s", e) 123 | 124 | @property 125 | def on_message(self): 126 | """ If implemented, called when the serial has receive message. 127 | Defined to allow receive. 128 | 129 | """ 130 | return self._on_message 131 | 132 | @on_message.setter 133 | def on_message(self, func): 134 | with self._callback_mutex: 135 | self._on_message = func 136 | 137 | def _handle_on_message(self, message): 138 | """serial receive message handle""" 139 | self.on_message(message) 140 | 141 | def on_send(self, msg): 142 | """send msg, 143 | msg: type of bytes or str""" 144 | with self._callback_mutex: 145 | if msg: 146 | if isinstance(msg, bytes): 147 | self.serial.write(msg) 148 | if isinstance(msg, str): 149 | self.serial.write(msg.encode('utf-8')) 150 | self._easy_log(SERIAL_LOG_INFO, "serial send message: %s", msg) 151 | 152 | @property 153 | def on_log(self): 154 | """If implemented, called when the serial has log information. 155 | Defined to allow debugging.""" 156 | return self._on_log 157 | 158 | @on_log.setter 159 | def on_log(self, func): 160 | """ Define the logging callback implementation. 161 | 162 | Expected signature is: 163 | log_callback(level, buf) 164 | 165 | level: gives the severity of the message and will be one of 166 | SERIAL_LOG_INFO, SERIAL_LOG_NOTICE, SERIAL_LOG_WARNING, 167 | SERIAL_LOG_ERR, and SERIAL_LOG_DEBUG. 168 | buf: the message itself 169 | """ 170 | self._on_log = func 171 | 172 | def _easy_log(self, level, fmt, *args): 173 | if self.on_log is not None: 174 | buf = fmt % args 175 | try: 176 | if level == SERIAL_LOG_DEBUG: 177 | level = "[DEBUG]" 178 | if level == SERIAL_LOG_ERR: 179 | level = "[ERR]" 180 | if level == SERIAL_LOG_INFO: 181 | level = "[INFO]" 182 | if level == SERIAL_LOG_NOTICE: 183 | level = "[NOTICE]" 184 | if level == SERIAL_LOG_WARNING: 185 | level = "[WARNING]" 186 | self.on_log(level, buf) 187 | except Exception: 188 | pass 189 | 190 | class Serial: 191 | def __init__(self, app): 192 | self.ser = Ser() 193 | if app is not None: 194 | self.init_app(app) 195 | 196 | def init_app(self, app): 197 | self.ser.serial.timeout = app.config.get("SERIAL_TIMEOUT") 198 | self.ser.serial.port = app.config.get("SERIAL_PORT") 199 | self.ser.serial.baudrate = app.config.get("SERIAL_BAUDRATE") 200 | self.ser.serial.bytesize = app.config.get("SERIAL_BYTESIZE") 201 | self.ser.serial.parity = app.config.get("SERIAL_PARITY") 202 | self.ser.serial.stopbits = app.config.get("SERIAL_STOPBITS") 203 | 204 | # try open serial 205 | self.ser.loop_start() 206 | 207 | def on_message(self): 208 | """serial receive message use decorator 209 | use: 210 | @serial.on_message() 211 | def handle_message(msg): 212 | print("serial receive message:", msg) 213 | """ 214 | def decorator(handler): 215 | # type: (Callable) -> Callable 216 | self.ser.on_message = handler 217 | return handler 218 | return decorator 219 | 220 | def on_send(self, msg): 221 | """serial send message 222 | use: 223 | serial.on_send("send a message to serial") 224 | """ 225 | self.ser.on_send(msg) 226 | 227 | def on_log(self): 228 | """logging 229 | use: 230 | serial.on_log() 231 | def handle_logging(level, info) 232 | print(info) 233 | """ 234 | def decorator(handler): 235 | # type: (Callable) -> Callable 236 | self.ser.on_log = handler 237 | return handler 238 | return decorator 239 | 240 | --------------------------------------------------------------------------------