Up 運動NNストアのプログラム 作成: 2026-11-04
更新: 2026-11-16

4足歩行ロボット > 進化型 > 構築> 運動NN > 運動NNストア > プログラム

    ##################################### # Python の ROS2ライブラリ import rclpy # <ユーザ定義のデータ型を使う>用 from rclpy.node import Node # データ型をimport # subscriber のデータ型 from my_robot_msgs.msg import BrainCmd # <チャイルドプロセスで #  NN に入力し,そして出力を受ける>用 import subprocess import json # torch import torch from torch import nn ############### # I2C import smbus # get_clock 用 import time ##################################### # ノード Move,move に設定 class Move(Node):   ###############################   # コントラクタ   # (クラスがもつ属性の定義・初期化)   def __init__(self):     # ノート名 : move     super().__init__('move')     ##################     # subscriber     # subscriber データを保持する変数     # None に初期設定     self.brain = None     # subscriber の設定     create_subscription(       BrainCmd,       '/brain/cmd',       self.callback,       10     )     ##################     # NN に対する<入力する・出力を受ける>を     # child process として実行     # NNプロセス起動     self.nn =       subprocess.Popen(         ['python3', 'nn_move.py'],         stdin=subprocess.PIPE,         stdout=subprocess.PIPE,         text=True,         bufsize=1       )     ##################     # I2C     # MCU の I2C 設定が既にされている     # その内容を書く     # 回路 I2C1 を使用     self.bus = smbus.SMBus(1)     # slave の motor_store_buffer は     #  アドレスが 0x10     self.slave_address = 0x10     # WAITING     self.WAITING = torch.full(       (48,),       1.0,       dtype=torch.float32     )     ##########################    # periodic execution     ##########################     self.timer = self.create_timer(       0.02,       self.move2current     )      ####################################   # サブルーチン   #   callback_brain   #   nn_move   #   move2current   ####################################      ##########################   # callback_brain   #   publisher (brain) の call に,callback する   #   → move_feature が届く   ##########################   def callback_brain(self, msg):     self.brain = msg   ##########################   # nn_move   #   NN に入力し,出力を受ける   #    (プロセス通信ラッパ)   #   motor_command(self) から呼び出される   ############################   def nn_move(self, nn_input):     # 入力を JSON にして送る     input_json = json.dumps(nn_input)     self.nn.stdin.write(input_json + "\n")     self.nn.stdin.flush()     # NN の出力を受け取る     output_json = self.nn.stdout.readline()     nn_output = json.loads(output_json)     return nn_output   ############################   # move2current   #   (1) NN への入力が有る   #   (2) NN 呼び出し → 入力→ 出力   #   (3) モータストアへ I2C 送信   ############################   def move2current(self):     ##################     # (1) 歩容 NN への入力が有る     ##################     # IN庫の入荷棚が全部埋まっていなければスキップ     if None in (       self.brain,     ):       return     # 歩容NN の入力は,stdin へ :     # この形式をつくる     nn_input = {       "brain": self.brain.__dict__     }     ##################     # (2) NN 呼び出し → 入力→ 出力     ##################     nn_output = self.nn_move(nn_input)     ##################     # (3) モータストアへ I2C 送信     ##################     # nn_output == (浮動点誤差を許して WAITING)     #  であれば, 何もしない     if torch.allclose(       nn_output_tensor,       self.WAITING     ):       return     # モータストアへ I2C 送信     # NNの出力は,モータ12個の電圧差分     # bytearray になっていて,そのまま送信できる     i2c_data = nn_output     # motor_store_buffer に書き込む     self.bus.write_i2c_block_data(       self.slave_address,       0x00,       i2c_data     )   ############################   # cleanup   ############################   def destroy_node(self):     if self.nn.poll() is None:       self.nn.terminate()     super().destroy_node() ##################################### ##################################### ################## #  main ################## def main(args=None):   rclpy.init(args=args)   # オブジェクト化   node = Move()   try:     rclpy.spin(node)   finally:     node.destroy_node()     rclpy.shutdown() ################## # プログラムの起動 ################## if __name__ == '__main__':   main()