Skip to content

Commit

Permalink
Quick type fixes reformatting
Browse files Browse the repository at this point in the history
  • Loading branch information
joaoantoniocardoso committed Jun 27, 2023
1 parent 72973b2 commit 767cb05
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 32 deletions.
62 changes: 32 additions & 30 deletions can.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/bin/python

from typing import Optional, List
from operator import mod
from unicodedata import normalize
import json
Expand All @@ -15,7 +16,8 @@


class Can:
def convert_string(string: str) -> str:
@classmethod
def convert_string(cls, string: str) -> str:
if not isinstance(string, str):
raise TypeError("`string` needs to be an integer type!")

Expand All @@ -28,13 +30,15 @@ def convert_string(string: str) -> str:

return string

def validate_byte(byte: int) -> bool:
@classmethod
def validate_byte(cls, byte: int) -> bool:
if (byte < 0) | (byte > 8):
print("Byte number MUST be between 0 and 7 to be described.")
return False
return True

def validate_bit(bit: int) -> bool:
@classmethod
def validate_bit(cls, bit: int) -> bool:
if (bit < 0) | (bit > 8):
print("Bit number MUST be between 0 and 7 to be described.")
return False
Expand All @@ -52,7 +56,7 @@ def __init__(self, msg: str, id: int,frequency: int, description: str):
raise TypeError("`description` must be a string type!")
self.description = description

self.bytes = [None] * 8
self.bytes: List[Optional[dict]] = [None] * 8

self.frequency = frequency

Expand All @@ -74,14 +78,16 @@ def get(self) -> dict:
def __str__(self) -> str:
return json.dumps(self.get(), indent=4)

def validate_byte(self, byte: int):
def validate_byte(self, byte: int) -> bool:
if not isinstance(byte, int):
raise TypeError("`byte` needs to be an integer type!")

if (byte < 0) or (byte > 7):
raise ValueError(
"`byte` number MUST be between 0 and 7 to be described.")

return True

def validate_bit(self, bit: int) -> bool:
if not isinstance(bit, int):
raise TypeError("`bit` needs to be an integer type!")
Expand All @@ -90,35 +96,41 @@ def validate_bit(self, bit: int) -> bool:
raise ValueError(
"`bit` number MUST be between 0 and 7 to be described.")

def validate_byte_name(self, name: str):
return True

def validate_byte_name(self, name: str) -> bool:
if not isinstance(name, str):
raise TypeError("byte field `name` must be a string type!")

for byte in filter(None, self.bytes):
if byte.get('name') == Can.convert_string(name):
raise ValueError("byte field `name` must be unique!")

def validate_bit_name(self, byte: int, name: str):
return True

def validate_bit_name(self, byte: int, name: str) -> bool:
if not isinstance(name, str):
raise TypeError("bit field `name` must be a string type!")

if self.bytes[byte] is not None:
for bit in filter(None, self.bytes[byte].get('bits')):
if bit == Can.convert_string(name):
raise ValueError("bit field `name` must be unique!")

def get_length(self):

return True

def get_length(self) -> int:
return len(list(filter(lambda x: x is not None, self.bytes)))

def get_frame_length(self):
def get_frame_length(self) -> int:
return 44 + 8 * self.get_length()

def describe_byte(self,
name: str,
byte: int,
description: str,
btype: str,
units: str = None):
units: Optional[str] = None):
self.validate_byte_name(name)
self.validate_byte(byte)

Expand Down Expand Up @@ -192,7 +204,7 @@ def get_total_load(self, bitrate):
for topic in self.topics:
load += topic.get_load(bitrate)
return load

def __str__(self) -> str:
return json.dumps(self.get(), indent=4)

Expand Down Expand Up @@ -253,7 +265,7 @@ def export_c_library(self, filename: str = "can_ids.h"):

def export_csv(self, filename: str):
import pandas as pd

modules = []
signature = []
ids = []
Expand Down Expand Up @@ -284,12 +296,8 @@ def export_csv(self, filename: str):
"frame_length": frame_length,
"description": description,
})

df.to_csv(filename)




df.to_csv(filename)

def get_can_load_by_topic(self):
load = {}
Expand All @@ -299,7 +307,6 @@ def get_can_load_by_topic(self):
load[topic["id"]] = []
load[topic["id"]].append(self.get_topic_load(topic))
return load


def get_can_load(self):
load = 0
Expand All @@ -311,14 +318,15 @@ def get_can_load(self):
def get_topic_load(self, topic: dict):
frame_length = topic["frame_length"]
frame_period = (1/self.bitrate) * frame_length
return frame_period * topic["frequency"] * 100
# load = period for 1 msg * frequency * 100%
return frame_period * topic["frequency"] * 100
# load = period for 1 msg * frequency * 100%
# Reference:
# https://support.vector.com/kb?id=kb_article_view&sysparm_article=KB0012332&sys_kb_id=99354e281b2614148e9a535c2e4bcb6d&spa=1

def plot_load(self):
import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows= 2, ncols=2,figsize=(9, 6))
plt.figtext(.5, .9, "Can Load ", fontsize=15, ha='center')

Expand All @@ -332,11 +340,11 @@ def plot_load(self):

id = list(ids.keys())
id.sort()

load = []
for i in id:
load.append(ids[i])

axes[0][0].bar(range(0, len(id)), load, align='center', color='royalblue')
axes[0][0].set_xticks(range(0, len(id)))
axes[0][0].set_xticklabels(list(id), fontsize = 9, rotation = 90)
Expand Down Expand Up @@ -376,12 +384,8 @@ def plot_load(self):
axes[1][1].pie(load, labels=modules,
textprops={'size': 'smaller'}, radius=1.5, labeldistance=1.1,startangle=-45)



plt.show()




if __name__ == '__main__':
t1 = Can.topic("motor", 9, 100, "Motor controller parameters")
Expand All @@ -403,7 +407,7 @@ def plot_load(self):

# print(m1)

c1 = Can("0.0.0", 500e3)
c1 = Can("0.0.0", 500_000)
c1.add_module(m1)
# print(c1)
c1.export_json("sample.json")
Expand All @@ -416,5 +420,3 @@ def plot_load(self):
# print(c2)

# c2.export_ids_h("sample.h")


4 changes: 2 additions & 2 deletions can_ids_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
raise FileNotFoundError(
f"File {SEMVER_FILENAME} not found. It should contain the version in semver standard.")

can = Can(version=f"{version}", bitrate=500e3)
can = Can(version=f"{version}", bitrate=500_000)

################################################################################
### MODULE: GENERIC
Expand Down Expand Up @@ -157,7 +157,7 @@
topic_mppts = can.topic(
msg="mppts",
id=200,
frequency = 4,
frequency = 4,
description="Mppts controller parameters",
)
topic_mppts.describe_byte(
Expand Down

0 comments on commit 767cb05

Please sign in to comment.