# Copyright (C) 2022 twyleg
import time
import math
import can
import os
from piracer.vehicles import PiRacerStandard
from pydbus import SessionBus
from gi.repository import GLib
CAN_ID = 'can0'
class dbusService:
'''
DBus Service Example
'''
dbus = """
<node>
<interface name='com.example.dbusService'>
<method name='get_fuel'>
<arg type='d' name='voltage' direction='out'/>
</method>
<method name='get_rpm'>
<arg type='i' name='current' direction='out'/>
</method>
</interface>
</node>
"""
def __init__(self):
self.piracer = PiRacerStandard()
self.voltage =0
os.system(f'sudo ifconfig {CAN_ID} down')
os.system(f'sudo ip link set {CAN_ID} up type can bitrate 500000 dbitrate 8000000 restart-ms 1000 berr-reporting on fd on')
self.can = can.interface.Bus(channel = CAN_ID, bustype = 'socketcan')
def get_fuel(self)->float:
self.voltage = self.piracer.get_battery_voltage()
self.voltage = 0.498*math.sin(1.546*self.voltage + 1.001) + 0.48
return self.voltage
def get_rpm(self) -> int:
msg = self.can.recv();
if msg is None:
return "No message recieved"
distance = msg.data[2] + msg.data[3]*256
return distance
bus = SessionBus()
bus.publish("com.example.dbusService", dbusService())
loop = GLib.MainLoop()
loop.run()
아두이노로부터 CAN을 통해 받은 rpm 값은 get_rpm 메서드를 통해 호출이 가능하고, piracer의 배터리 잔량은 piracer 라이브러리를 사용하여 전압값을 받아온 후 위 계산과정을 통해 배터리 잔량 근사값으로 변환한다.
이유는 모르겠지만 get_fuel의 리턴값은 float형 데이터이지만 보낼때는 double형으로 xml에 정의해줘야된다,,, 왜그런지 모르겠다
"type='d' represents a D-Bus type signature for a double-precision floating-point number. In D-Bus type notation, 'd' corresponds to a 64-bit double-precision floating-point value, which is equivalent to a Python float" 라고 chat gpt 가 말해주네요