formatted with autopep8

This commit is contained in:
Gabe R 2020-06-28 20:10:19 -05:00
parent 8326ddd462
commit 05fa4783ed
No known key found for this signature in database
GPG Key ID: F96D83D8D7ED67D0

View File

@ -9,12 +9,13 @@ import sys
from typing import Any, List
import yaml
if __name__== '__main__':
if __name__ == '__main__':
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from wireviz import wv_colors
from wireviz.wv_helper import nested, int2tuple, awg_equiv, flatten2d, tuplelist2tsv
class Harness:
def __init__(self):
@ -74,7 +75,7 @@ class Harness:
dot.node(k, shape='none',
style='filled',
margin='0',
orientation = '0' if n.ports_left else '180',
orientation='0' if n.ports_left else '180',
label='''<
<TABLE BORDER="1" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2"><TR>
@ -94,7 +95,7 @@ class Harness:
n.subtype,
'{}-pin'.format(n.pincount) if n.show_pincount else '']
# p = pinout
p = [[],[],[]]
p = [[], [], []]
for pinnumber, pinname in zip(n.pinnumbers, n.pinout):
if n.hide_disconnected_pins and not n.visible_pins.get(pinnumber, False):
continue
@ -108,7 +109,7 @@ class Harness:
dot.node(k, label=nested(l))
if len(n.loops) > 0:
dot.attr('edge',color='#000000:#ffffff:#000000')
dot.attr('edge', color='#000000:#ffffff:#000000')
if n.ports_left:
loop_side = 'l'
loop_dir = 'w'
@ -124,7 +125,8 @@ class Harness:
for k, c in self.cables.items():
# a = attributes
a = ['{}x'.format(len(c.colors)) if c.show_wirecount else '',
'{} {}{}'.format(c.gauge, c.gauge_unit, ' ({} AWG)'.format(awg_equiv(c.gauge)) if c.gauge_unit == 'mm\u00B2' and c.show_equiv else '') if c.gauge else '', # TODO: show equiv
'{} {}{}'.format(c.gauge, c.gauge_unit, ' ({} AWG)'.format(awg_equiv(c.gauge)) if c.gauge_unit ==
'mm\u00B2' and c.show_equiv else '') if c.gauge else '', # TODO: show equiv
'+ S' if c.shield else '',
'{} m'.format(c.length) if c.length > 0 else '']
a = list(filter(None, a))
@ -144,7 +146,7 @@ class Harness:
html = html + '<tr><td><table border="0" cellspacing="0" cellborder="0">' # conductor table
for i, x in enumerate(c.colors,1):
for i, x in enumerate(c.colors, 1):
p = []
p.append('<!-- {}_in -->'.format(i))
p.append(wv_colors.translate_color(x, self.color_mode))
@ -154,7 +156,8 @@ class Harness:
html = html + '<td>{}</td>'.format(bla)
html = html + '</tr>'
bgcolor = wv_colors.translate_color(x, 'hex')
html = html + '<tr><td colspan="{colspan}" cellpadding="0" height="6" bgcolor="{bgcolor}" border="2" sides="tb" port="{port}"></td></tr>'.format(colspan=len(p), bgcolor=bgcolor if bgcolor != '' else '#ffffff', port='w{}'.format(i))
html = html + '<tr><td colspan="{colspan}" cellpadding="0" height="6" bgcolor="{bgcolor}" border="2" sides="tb" port="{port}"></td></tr>'.format(
colspan=len(p), bgcolor=bgcolor if bgcolor != '' else '#ffffff', port='w{}'.format(i))
if c.shield:
p = ['<!-- s_in -->', 'Shield', '<!-- s_out -->']
@ -163,7 +166,8 @@ class Harness:
for bla in p:
html = html + '<td>{}</td>'.format(bla)
html = html + '</tr>'
html = html + '<tr><td colspan="{colspan}" cellpadding="0" height="6" border="2" sides="b" port="{port}"></td></tr>'.format(colspan=len(p), bgcolor=wv_colors.translate_color(x, 'hex'), port='ws')
html = html + '<tr><td colspan="{colspan}" cellpadding="0" height="6" border="2" sides="b" port="{port}"></td></tr>'.format(
colspan=len(p), bgcolor=wv_colors.translate_color(x, 'hex'), port='ws')
html = html + '<tr><td>&nbsp;</td></tr>' # spacer at the end
@ -179,30 +183,36 @@ class Harness:
# connections
for x in c.connections:
if isinstance(x.via_port, int): # check if it's an actual wire and not a shield
search_color = c.colors[x.via_port-1]
search_color = c.colors[x.via_port - 1]
if search_color in wv_colors.color_hex:
dot.attr('edge',color='#000000:{wire_color}:#000000'.format(wire_color=wv_colors.color_hex[search_color]))
dot.attr('edge', color='#000000:{wire_color}:#000000'.format(
wire_color=wv_colors.color_hex[search_color]))
else: # color name not found
dot.attr('edge',color='#000000:#ffffff:#000000')
dot.attr('edge', color='#000000:#ffffff:#000000')
else: # it's a shield connection
dot.attr('edge',color='#000000')
dot.attr('edge', color='#000000')
if x.from_port is not None: # connect to left
from_ferrule = self.connectors[x.from_name].category == 'ferrule'
code_left_1 = '{from_name}{from_port}:e'.format(from_name=x.from_name, from_port=':p{}r'.format(x.from_port) if not from_ferrule else '')
code_left_2 = '{via_name}:w{via_wire}:w'.format(via_name=c.name, via_wire=x.via_port, via_subport='i' if c.show_pinout else '')
code_left_1 = '{from_name}{from_port}:e'.format(
from_name=x.from_name, from_port=':p{}r'.format(x.from_port) if not from_ferrule else '')
code_left_2 = '{via_name}:w{via_wire}:w'.format(
via_name=c.name, via_wire=x.via_port, via_subport='i' if c.show_pinout else '')
dot.edge(code_left_1, code_left_2)
from_string = '{}:{}'.format(x.from_name, x.from_port) if not from_ferrule else ''
html = html.replace('<!-- {}_in -->'.format(x.via_port), from_string)
if x.to_port is not None: # connect to right
to_ferrule = self.connectors[x.to_name].category == 'ferrule'
code_right_1 = '{via_name}:w{via_wire}:e'.format(via_name=c.name, via_wire=x.via_port, via_subport='o' if c.show_pinout else '')
code_right_2 = '{to_name}{to_port}:w'.format(to_name=x.to_name, to_port=':p{}l'.format(x.to_port) if not to_ferrule else '')
code_right_1 = '{via_name}:w{via_wire}:e'.format(
via_name=c.name, via_wire=x.via_port, via_subport='o' if c.show_pinout else '')
code_right_2 = '{to_name}{to_port}:w'.format(
to_name=x.to_name, to_port=':p{}l'.format(x.to_port) if not to_ferrule else '')
dot.edge(code_right_1, code_right_2)
to_string = '{}:{}'.format(x.to_name, x.to_port) if not to_ferrule else ''
html = html.replace('<!-- {}_out -->'.format(x.via_port), to_string)
dot.node(c.name, label='<{html}>'.format(html=html), shape='box', style='filled,dashed' if c.category=='bundle' else '', margin='0', fillcolor='white')
dot.node(c.name, label='<{html}>'.format(html=html), shape='box',
style='filled,dashed' if c.category == 'bundle' else '', margin='0', fillcolor='white')
return dot
@ -215,14 +225,14 @@ class Harness:
d.save(filename='{}.gv'.format(filename), directory=directory)
# bom output
bom_list = self.bom_list()
with open('{}.bom.tsv'.format(filename),'w') as file:
with open('{}.bom.tsv'.format(filename), 'w') as file:
file.write(tuplelist2tsv(bom_list))
# HTML output
with open('{}.html'.format(filename),'w') as file:
with open('{}.html'.format(filename), 'w') as file:
file.write('<html><body style="font-family:Arial">')
file.write('<h1>Diagram</h1>')
with open('{}.svg'.format(filename),'r') as svg:
with open('{}.svg'.format(filename), 'r') as svg:
for l in svg:
file.write(l)
@ -236,7 +246,8 @@ class Harness:
for row in listy[1:]:
file.write('<tr>')
for i, item in enumerate(row):
file.write('<td {align} style="border:1px solid #000000; padding: 4px">{content}</td>'.format(content=item, align='align="right"' if listy[0][i] == 'Qty' else ''))
file.write('<td {align} style="border:1px solid #000000; padding: 4px">{content}</td>'.format(
content=item, align='align="right"' if listy[0][i] == 'Qty' else ''))
file.write('</tr>')
file.write('</table>')
@ -253,26 +264,31 @@ class Harness:
shared = next(iter(items.values()))
designators = list(items.keys())
designators.sort()
name = 'Connector{type}{subtype}{pincount}{color}'.format(type = ', {}'.format(shared.type) if shared.type else '',
subtype = ', {}'.format(shared.subtype) if shared.subtype else '',
pincount = ', {} pins'.format(shared.pincount) if shared.category != 'ferrule' else '',
color = ', {}'.format(shared.color) if shared.color else '')
item = {'item': name, 'qty': len(designators), 'unit': '', 'designators': designators if shared.category != 'ferrule' else ''}
name = 'Connector{type}{subtype}{pincount}{color}'.format(type=', {}'.format(shared.type) if shared.type else '',
subtype=', {}'.format(
shared.subtype) if shared.subtype else '',
pincount=', {} pins'.format(
shared.pincount) if shared.category != 'ferrule' else '',
color=', {}'.format(shared.color) if shared.color else '')
item = {'item': name, 'qty': len(designators), 'unit': '',
'designators': designators if shared.category != 'ferrule' else ''}
bom_connectors.append(item)
bom_connectors = sorted(bom_connectors, key=lambda k: k['item']) # https://stackoverflow.com/a/73050
bom.extend(bom_connectors)
# cables
types = Counter([(v.category, v.gauge, v.gauge_unit, v.wirecount, v.shield) for v in self.cables.values()])
for type in types:
items = {k: v for k, v in self.cables.items() if (v.category, v.gauge, v.gauge_unit, v.wirecount, v.shield) == type}
items = {k: v for k, v in self.cables.items() if (
v.category, v.gauge, v.gauge_unit, v.wirecount, v.shield) == type}
shared = next(iter(items.values()))
if shared.category != 'bundle':
designators = list(items.keys())
designators.sort()
total_length = sum(i.length for i in items.values())
name = 'Cable, {wirecount}{gauge}{shield}'.format(wirecount = shared.wirecount,
gauge = ' x {} {}'.format(shared.gauge, shared.gauge_unit) if shared.gauge else ' wires',
shield = ' shielded' if shared.shield else '')
name = 'Cable, {wirecount}{gauge}{shield}'.format(wirecount=shared.wirecount,
gauge=' x {} {}'.format(
shared.gauge, shared.gauge_unit) if shared.gauge else ' wires',
shield=' shielded' if shared.shield else '')
item = {'item': name, 'qty': round(total_length, 3), 'unit': 'm', 'designators': designators}
bom_cables.append(item)
# bundles (ignores wirecount)
@ -287,7 +303,8 @@ class Harness:
for bundle in items.values():
# add each wire from each bundle to the wirelist
for color in bundle.colors:
wirelist.append({'gauge': shared.gauge, 'gauge_unit': shared.gauge_unit, 'length': shared.length, 'color': color, 'designator': bundle.name})
wirelist.append({'gauge': shared.gauge, 'gauge_unit': shared.gauge_unit,
'length': shared.length, 'color': color, 'designator': bundle.name})
# join similar wires from all the bundles to a single BOM item
types = Counter([(v['gauge'], v['gauge_unit'], v['color']) for v in wirelist])
for type in types:
@ -319,6 +336,7 @@ class Harness:
bom_list.append(item_list)
return bom_list
@dataclass
class Connector:
name: str
@ -356,7 +374,7 @@ class Connector:
# create default lists for pinnumbers (sequential) and pinouts (blank) if not specified
if not self.pinnumbers:
self.pinnumbers = list(range(1,self.pincount + 1))
self.pinnumbers = list(range(1, self.pincount + 1))
if not self.pinout:
self.pinout = [''] * self.pincount
@ -369,13 +387,14 @@ class Connector:
def activate_pin(self, pin):
self.visible_pins[pin] = True
@dataclass
class Cable:
name: str
category : str = None
category: str = None
type: str = None
gauge: float = None
gauge_unit : str = None
gauge_unit: str = None
show_equiv: bool = False
length: float = 0
wirecount: int = None
@ -395,7 +414,7 @@ class Cable:
except:
raise Exception('Gauge must be a number, or number and unit separated by a space')
self.gauge = g
self.gauge_unit = u.replace('mm2','mm\u00B2')
self.gauge_unit = u.replace('mm2', 'mm\u00B2')
elif self.gauge is not None: # gauge specified, assume mm2
if self.gauge_unit is None:
self.gauge_unit = 'mm\u00B2'
@ -438,6 +457,7 @@ class Cable:
# self.connections.append((from_name, from_pin[i], via_pin[i], to_name, to_pin[i]))
self.connections.append(Connection(from_name, from_pin[i], via_pin[i], to_name, to_pin[i]))
@dataclass
class Connection:
from_name: Any
@ -446,6 +466,7 @@ class Connection:
to_name: Any
to_port: Any
def parse(yaml_input, file_out=None, generate_bom=False):
yaml_data = yaml.safe_load(yaml_input)
@ -457,16 +478,16 @@ def parse(yaml_input, file_out=None, generate_bom=False):
# if str is of the format '#-#', it is treated as a range (inclusive) and expanded
output = []
if not isinstance(yaml_data, list):
yaml_data = [yaml_data,]
yaml_data = [yaml_data, ]
for e in yaml_data:
e = str(e)
if '-' in e: # list of pins
a, b = tuple(map(int, e.split('-')))
if a < b:
for x in range(a,b+1):
for x in range(a, b + 1):
output.append(x)
elif a > b:
for x in range(a,b-1,-1):
for x in range(a, b - 1, -1):
output.append(x)
elif a == b:
output.append(a)
@ -487,7 +508,7 @@ def parse(yaml_input, file_out=None, generate_bom=False):
h = Harness()
# add items
sections = ['connectors','cables','ferrules','connections']
sections = ['connectors', 'cables', 'ferrules', 'connections']
types = [dict, dict, dict, list]
for sec, ty in zip(sections, types):
if sec in yaml_data and type(yaml_data[sec]) == ty:
@ -521,8 +542,8 @@ def parse(yaml_input, file_out=None, generate_bom=False):
via_name = list(con[1].keys())[0]
to_name = list(con[2].keys())[0]
if not check_designators([from_name,via_name,to_name],('connectors','cables','connectors')):
print([from_name,via_name,to_name])
if not check_designators([from_name, via_name, to_name], ('connectors', 'cables', 'connectors')):
print([from_name, via_name, to_name])
raise Exception('Bad connection definition (3)')
from_pins = expand(con[0][from_name])
@ -555,13 +576,12 @@ def parse(yaml_input, file_out=None, generate_bom=False):
from_name = list(con[0].keys())[0]
to_name = list(con[1].keys())[0]
con_cbl = check_designators([from_name, to_name],('connectors','cables'))
cbl_con = check_designators([from_name, to_name],('cables','connectors'))
con_con = check_designators([from_name, to_name],('connectors','connectors'))
con_cbl = check_designators([from_name, to_name], ('connectors', 'cables'))
cbl_con = check_designators([from_name, to_name], ('cables', 'connectors'))
con_con = check_designators([from_name, to_name], ('connectors', 'connectors'))
fer_cbl = check_designators([from_name, to_name],('ferrules','cables'))
cbl_fer = check_designators([from_name, to_name],('cables','ferrules'))
fer_cbl = check_designators([from_name, to_name], ('ferrules', 'cables'))
cbl_fer = check_designators([from_name, to_name], ('cables', 'ferrules'))
if not con_cbl and not cbl_con and not con_con and not fer_cbl and not cbl_fer:
raise Exception('Wrong designators')
@ -610,11 +630,11 @@ def parse(yaml_input, file_out=None, generate_bom=False):
else:
h.connect(None, None, cable_name, cable_pin, ferrule_id, 1)
else:
raise Exception('Wrong number of connection parameters')
h.output(filename=file_out, format=('png','svg'), gen_bom=generate_bom, view=False)
h.output(filename=file_out, format=('png', 'svg'), gen_bom=generate_bom, view=False)
def parse_file(yaml_file, file_out=None, generate_bom=False):
with open(yaml_file, 'r') as file:
@ -645,6 +665,7 @@ def parse_cmdline():
return args
def main():
args = parse_cmdline()
@ -674,5 +695,6 @@ def main():
parse(yaml_input, file_out=file_out, generate_bom=args.generate_bom)
if __name__ == '__main__':
main()