vertual can 전송, vertual can data 수신 및 D-bus 연결,QTdbus로 수신

jalee·2023년 8월 9일
0

CAN 데이터를 사용해야 하는 작업환경에서 CAN device가 있지 않을때 vertual can 환경을 구축해서 작업하면 편리하다.

vertual can 전송 코드

import time
import can
import random

bustype = 'socketcan'
channel = 'vcan0'

def producer():
    """:param id: Spam the bus with messages including the data id."""
    bus = can.Bus(channel=channel, interface=bustype)
    while(1):
        a = random.randrange(0,110)
        msg = can.Message(arbitration_id=0xc0ffee, data=[a, a, a, a, 3, 1, 4, 1], is_extended_id=False)
        bus.send(msg)
        time.sleep(0.1)

producer()

위 코드를 받은 후 pydbus를 사용해서 dbus로 전송하는 코드이다.

import os
import can
from pydbus import SessionBus
from gi.repository import GLib

CAN_ID = "vcan0"

class dbusService:
    '''
    DBus Service Example
    '''
    dbus = """
    <node>
        <interface name='com.example.dbusService'>
            <method name='get_rpm'>
                <arg type='i' name='speed' direction='out'/>
            </method>
            <method name='get_fuel'>
                <arg type='d' name='battery' direction='out'/>
            </method>
        </interface>
    </node>
    """
    
    def __init__(self):
        self.can = can.interface.Bus(channel = CAN_ID, bustype = 'socketcan')
        self.fuel = 0.0
        self.cnt = 0.1

    def get_rpm(self) -> int:
        msg = self.can.recv();
        if msg is None:
            return "No message recieved"
        distance = msg.data[2]
        return distance
        
    def get_fuel(self) -> float:
        if self.fuel >= 0.85:
            self.cnt = -0.1
        elif self.fuel <= 0.15:
            self.cnt = 0.1
        self.fuel += self.cnt
        
        return self.fuel
            

bus = SessionBus()
bus.publish("com.example.dbusService", dbusService())

loop = GLib.MainLoop()
loop.run()

위 코드에서 get_rpm은 받은 CAN data를 dbus로 전송하고, get_fuel은 can으로부터 받지 않은 데이터를 전송한다.

이를 다시 qt를 통해 dbus에 접근하여 클러스터 값을 변화시킨다.

qt dashboard link: https://github.com/leeoodol/DES_Instrument-Cluster/tree/main/dashboard

0개의 댓글