Jason
Hi My name is Jason
Jason
自動化生產?資訊化?
數據分析?機器學習?深度學習?人工智慧?
>>> import serial
>>> # Open named port at “19200,8,N,1”, 1s timeout:
>>> with serial.Serial('/dev/ttyS1', 19200, timeout=1) as ser:
... x = ser.read() # read one byte
... s = ser.read(10) # read up to ten bytes (timeout)
... line = ser.readline() # read a '\n' terminated line
>>> # Open port at “38400,8,E,1”, non blocking HW handshaking:
>>> ser = serial.Serial('COM3', 38400, timeout=0,
... parity=serial.PARITY_EVEN, rtscts=1)
>>> s = ser.read(100) # read up to one hundred bytes
... # or as much is in the buffer
Vision
Gateway
Django
Serial Port
TCP/IP
By Chetan Giridhar, PyCon India 2014
Producer
Queue
Consumer
def consumer():
with serial.Serial(com, port, timeout=0) as ser:
buffer = ''
while True:
buffer += ser.readline().decode()
if '\r' in buffer:
buf = buffer.split('\r')
last_received, buffer = buffer.split('\r')[-2:]
yield last_received
async def async_producer(session, q):
start = time.time()
while len(q):
data = q.popleft()
status, result = await async_post(session, url_seq, url_films, data)
if status != 201:
q.append(data)
if time.time() - start >= 1:
break
q = deque()
com = 'COM5'
port = 9600
last_received = ''
async def async_main():
global q
async with aiohttp.ClientSession() as session:
for data in consumer():
q.append(data)
d = q.popleft()
status, result = await async_post(session, url_seq, url_films, data=d) # post data
if status != 201:
q.append(d)
if len(q) >= 2:
await async_producer(session, q)
loop = asyncio.get_event_loop()
loop.run_until_complete(async_main())
loop.close()
async def async_main():
global q # --> 錯誤 (1)
async with aiohttp.ClientSession() as session:
for data in consumer(): # --> 錯誤 (2)
q.append(data)
d = q.popleft()
status, result = await async_post(session, url_seq, url_films, data=d) # post data
if status != 201:
q.append(d)
if len(q) >= 2:
await async_producer(session, q)
loop = asyncio.get_event_loop()
loop.run_until_complete(async_main())
loop.close()
快快樂樂的讓 serial port 非同步
一頁,簡潔有力啊!我喜歡
可能會讓人直接放棄的一頁官方教學
import threading
import serial
import queue
port = '/dev/cu.usbmodem1411'
baud = 9600
ser = serial.Serial(port, baud, timeout=0)
def produce(ser, queue):
while True:
buffers = ''
while True:
buffers += ser.readline().decode()
if '\r' in buffers:
last_received, buffers = buffers.split('\r')[-2:]
data = last_received.strip()
print(f"prodcue: {id(data)}")
queue.put(data)
def consume(queue):
while True:
data = queue.get()
print(f"consume: {id(data)}")
queue.task_done()
q = queue.Queue()
workers = [
threading.Thread(target=produce, args=(ser, q, )),
threading.Thread(target=consume, args=(q,))
]
for w in workers:
w.start()
q.join()
class Reader(asyncio.Protocol):
def __init__(self, queue):
"""Store the queue here."""
super().__init__()
self.transport = None
self.buf = None
self.queue = queue
def connection_made(self, transport):
"""Store the serial transport and prepare to receive data."""
self.transport = transport
self.buf = bytes()
print('port opend', transport)
def data_received(self, data):
"""Store characters until a newline is received."""
self.buf += data
if b'\r' in self.buf:
lines = self.buf.split(b'\r')
recv, self.buf = lines[-2:] # whatever was left over
data = recv.strip()
asyncio.ensure_future(self.queue.put(data))
self.buf.strip()
print(f'producing: {id(data)}')
def connection_lost(self, exc):
print('Reader closed')
Asyncio
• transport
• protocols
import serial_asyncio
async def produce(queue, **kwargs):
"""get serial data use recv() define format with non-blocking
"""
reader, writer = await serial_asyncio.open_serial_connection(url=url, **kwargs)
buffers = recv(reader)
async for buf in buffers:
# TODO: can handle data format here
print(f"produce id: {id(buf)}")
async def recv(r):
"""
Handle stream data with different StreamReader:
'read', 'readexactly', 'readuntil', or 'readline'
"""
while True:
msg = await r.readuntil(b'\r')
yield msg.rstrip().decode('utf-8')
Asyncio
StreamReader
# 'read', 'readexactly', 'readuntil', or 'readline'
msg = await r.readuntil(b'\r')
async def consume(queue):
"""Get serail data with async"""
while True:
data = await queue.get()
print(f'consuming: {id(data)}')
"""handle data from here"""
await asyncio.sleep(random.random())
queue.task_done()
loop = asyncio.get_event_loop()
queue = asyncio.Queue(loop=loop)
produce = partial(Reader, queue)
producer_coro = serial_asyncio.create_serial_connection(
loop, produce, com, baudrate
)
consumer_coro = consume(queue)
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
loop.close()
>>> buf = buf.rstrip().decode('utf-8')
>>> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 0: invalid
continuation byte
loop.stop()
Task was destroyed but it is pending!
task: <Task pending coro=<consume() running at xxxxx.py:207>
wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x03144F30>()]>>
2018-09-04 08:24:31 INFO [xxxxx:216] Event loop is closed
Exception ignored in: <coroutine object consume at 0x03255660>
RuntimeError: coroutine ignored GeneratorExit
decode error
這是啥 à?'À'?可以吃嗎?
or
裝置?win 的 big5
try:
buf = buf.rstrip().decode('utf-8')
except Exception as e:
wlog(buf)
buf = buf.rstrip().decode('utf-8', 'ignore')
import pytz
# 要查詢資料庫的時間記得要加上時區
tp = pytz.timezone('Asia/Taipei')
dt = datetime.datetime.strptime(start, '%Y-%m-%d %H:%M').astimezone(tp)
前端 js 可以設定幾秒後動態去更新資料(Demo 手按的 XD)
如果要漂亮一點就是多加一些統計量,也是動態的
資料科學家
我是超全端(樣樣都卡關)
By Jason