~cypheon/kicad2spice

3130700f234596f399c2c9a03511ea340c68a3d4 — Johann Rudloff 4 years ago ab8dc55
Export Spice netlist according to defined primitives, guarantee unique naming for components in netlist.
2 files changed, 24 insertions(+), 7 deletions(-)

M lib/export_pspice.ml
M lib/schematic.ml
M lib/export_pspice.ml => lib/export_pspice.ml +23 -7
@@ 7,15 7,14 @@ let comp_ignored comp =
  comp.Comp.ref.[0] = '#'
  || Fields.get comp.Comp.fields Fields.Keys.spice_netlist_enabled "Y" <> "Y"

let write_comp outch pin_cache comp =
let write_comp outch pin_cache comp name =
  let pin_nets = map (fun pin ->
    Hashtbl.find pin_cache (comp.Comp.ref, pin.Pin.number)
    ) comp.Comp.part.CompDef.pins in
  output_string outch comp.Comp.ref;
  output_string outch name;
  output_string outch (" " ^ (String.concat " " pin_nets));
  output_string outch (" " ^ (comp.Comp.value));
  output_string outch "\n";
  ignore pin_cache
  output_string outch "\n"

let make_cache kf vf xs =
  let tbl = Hashtbl.create (Enum.count xs) in


@@ 26,6 25,22 @@ let make_cache kf vf xs =

let id x = x

let comp_name comp =
  let comp_type_from_name = String.sub comp.Comp.ref 0 1 in
  let comp_type = Fields.get comp.Comp.fields Fields.Keys.spice_primitive comp_type_from_name in
  if comp_type_from_name = comp_type then comp.Comp.ref
  else comp_type ^ comp.Comp.ref

let make_unique used name =
  if not (Hashtbl.mem used name) then (Hashtbl.add used name 1; name)
  else begin
    let rec helper n =
      let full_name = name ^ "_" ^ (string_of_int n) in
      if not (Hashtbl.mem used full_name) then (Hashtbl.add used full_name 1; full_name)
      else helper (n+1)
    in helper 2
  end

let write_netlist outch schematic netlist =
  let net_names = make_cache id ( fun net_name ->
    Netlist.driver_net_name netlist net_name


@@ 37,11 52,12 @@ let write_netlist outch schematic netlist =
      | _ -> failwith "invalid netlist"
  ) subgraph.Subgraph.items
  ) netlist.Netlist.nets;
  ignore schematic; ignore netlist;
  output_string outch ".title KiCad schematic (by eeschema2netlist)\n";
  let used_comp_names = Hashtbl.create 512 in
  iter ( function
    | Item.Comp comp -> if not (comp_ignored comp)
    then write_comp outch pin_cache comp
    | Item.Comp comp when not (comp_ignored comp) ->
        let comp_export_name = make_unique used_comp_names (comp_name comp) in
        write_comp outch pin_cache comp comp_export_name
    | _ -> ()
  ) schematic.items;
  output_string outch ".end\n";

M lib/schematic.ml => lib/schematic.ml +1 -0
@@ 5,6 5,7 @@ module Fields = struct

  module Keys = struct
    let spice_netlist_enabled = "Spice_Netlist_Enabled"
    let spice_primitive = "Spice_Primitive"
  end

  let pp pval fmt m = let open Format in