読んだ色を前後のライトへ映す
前側センサーの色を通知で受け取り、ライトを変えます。
- 必要な本体
- 1台。
- 線路・準備
- 色スナップを付けたレールへ本体を置きます。走行はコードから開始しません。
- 終了方法
- Enterで購読解除後に切断。コードからの停止操作はありません。
- 保存する場所
matrain-python-async/examples/color_change/1_single_train.py- 実行する場所
matrain-python-asyncフォルダー内。.venvのPythonを使います。
Mac:.venv/bin/python examples/color_change/1_single_train.pyWindows:.venv\Scripts\python.exe examples\color_change\1_single_train.py
通常終了の処理を原例のまま掲載しています。例外やCtrl+Cでの停止が保証されないため、異常時は本体のボタンを短く押して止めます。切断だけを停止とみなさないでください。
コード全文
color_change/1_single_train.py
# Matrain publication modification: licensing/source notice added.
# Executable behavior is unchanged except for the adaptations documented below.
# Source: https://github.com/intelino-code/intelino-trainlib-async-py
# Source commit: 298e1fd4091e069180c30f338b4c285b13accbd0
# This software is made available by Innokind, Inc. DBA Intelino, under the
# terms of the Intelino Public License Agreement, Version 1.0 located at
# https://intelino.com/intelino-public-license. BY INSTALLING, DOWNLOADING,
# ACCESSING, USING OR DISTRIBUTING ANY OF THE SOFTWARE, YOU AGREE TO THE TERMS OF
# SUCH LICENSE AGREEMENT.
"""Color change event example (1): Single train."""
import asyncio
import aioconsole
from intelino.trainlib_async import (
TrainScanner,
Train,
)
from intelino.trainlib_async.messages import (
TrainMsg,
TrainMsgEventFrontColorChanged,
)
async def color_change(train: Train):
"""
Wait for color change events and set headlights/taillights
based on the seen color.
"""
def observer_func(msg: TrainMsg):
if isinstance(msg, TrainMsgEventFrontColorChanged):
print(f"New color: {msg.color}")
color = msg.color.to_rgb_bytes()
asyncio.create_task(train.set_headlight_color(color, color))
# subscribe to the notification stream
subscription = train.notifications.subscribe(observer_func)
# let the train program run until the 'enter' key is pressed
await aioconsole.ainput("Press <Enter> to exit at any time...\n")
# cleanup
subscription.dispose()
async def main():
async with TrainScanner() as train:
# run our train program
await color_change(train)
if __name__ == "__main__":
asyncio.run(main())
冒頭に配布条件と出典のコメントを追加しています。表示している全文と、個別保存・ZIP内のこのファイルは同じです。ライセンス・出典を読む
