# -*- coding: utf-8 -*-

import FreeCAD as App
from FreeCAD import Placement, Rotation, Vector
import matplotlib
from io import StringIO

D=FreeCAD.newDocument("Luftspule")

D_Draht = 1.55          # Drahtdurchmesser
Add_Z = 0.1             # Höhe über der Platine
Abstand = 0.2           # Windungsabstand
D_Spule = 33.5          # Spulendurchmesser
Windungen = 17.0        # Windungszahl
Vertikal = True         # vertikal wenn True

len = Windungen * (D_Draht + Abstand)

vec0=Vector(0,0,0)      # Nullvektor
vecx=Vector(1,0,0)      # Drehachse x
vecy=Vector(0,1,0)      # Drehachse y
vecz=Vector(0,0,1)      # Drehachse z

# Farben
# Farbe_Spule = matplotlib.colors.to_rgb('chocolate')
Farbe_Spule = 0x8e402a00 # Farbe von Kupfer (laut Internet)

Steigung = D_Draht+Abstand # Steigung

# Helix generieren
helix = D.addObject("Part::Helix", "Helix")
helix.Pitch = Steigung
helix.Height = Steigung*Windungen
helix.Radius = D_Spule/2
helix.ViewObject.Visibility = False

# Sketch generieren, wird entlang der Helix gesweeped
sketch = D.addObject('Sketcher::SketchObject', 'Drahtquerschnitt')
sketch.Placement = Placement(vec0, Rotation(0.707107, 0, 0, 0.707107))
sketch.MapMode = "Deactivated"
sketch.addGeometry(Part.Circle(Vector(D_Spule/2,0,0),vecz,D_Draht/2),False)
sketch.ViewObject.Visibility = False

# Sweep ausführen
sweep = D.addObject('Part::Sweep','Spule')
sweep.Sections=[sketch, ]
sweep.Spine=(helix,['Edge1',])
sweep.Solid=True
sweep.Frenet=False
sweep.ViewObject.ShapeColor=Farbe_Spule

output = StringIO()
print("Spule-D", D_Spule, "mm-W", Windungen, "-L", len, "mm", file=output, sep='', end='')
sweep.Label=output.getvalue()

# Platzieren
if Vertikal:
   sweep.Placement=Placement(Vector(0,0,D_Draht/2+Add_Z), Rotation(vec0,0), vec0).multiply(sweep.Placement)
else:
   sweep.Placement=Placement(Vector(-D_Spule/2,0,0), Rotation(vec0,0), vec0).multiply(sweep.Placement)
   sweep.Placement=Placement(vec0, Rotation(vecy,90), vec0).multiply(sweep.Placement)
   sweep.Placement=Placement(Vector(0,0,D_Draht/2+Add_Z), Rotation(vec0,0), vec0).multiply(sweep.Placement)

D.recompute()

view = FreeCADGui.ActiveDocument.ActiveView
view.fitAll()



