kiconnect/freecad/kiconnect/api.py

115 lines
3.3 KiB
Python

import FreeCAD as App
import FreeCADGui as Gui
from kipy import KiCad
from kipy.proto.common.types import DocumentType
from . import settings
from . import board as Board
from .bases import BaseObject, BaseViewProvider
class APIObject(BaseObject):
TYPE = 'KiConnect::API'
def __init__(self, feature):
self.boards = {}
self.kicad = KiCad()
super(APIObject, self).__init__(feature)
feature.addProperty('App::PropertyFile', 'Socket', 'KiConnect', 'Path to the KiCAD Socket File').Socket = '/tmp/kicad/api.lock'
feature.addProperty('App::PropertyBool', 'Connected', 'KiConnect', 'Is socket connected')
feature.addProperty('App::PropertyInteger', 'DocumentCount', 'KiConnect', 'Count of open Documnets')
self.onDocumentRestored(feature)
self.ping_connection(feature)
self.kicad_board = self.kicad.get_board()
self.polygons = Board.extract_polygons(self.kicad_board)
for polygon in self.polygons:
board, polygon_id = Board.makeBoard(self.feature.getParent(), self.kicad_board, polygon)
self.boards[polygon_id] = board
def onDocumentRestored(self, feature):
super(APIObject, self).onDocumentRestored(feature)
self.kicad = KiCad()
self.ping_connection(feature)
if self.is_connected:
self.kicad_board = self.kicad.get_board()
self.polygons = Board.extract_polygons(self.kicad_board)
parent = feature.getParent()
if not parent: return
'''
# XXX This gets all of the KiConnect::Board features but then does nothing with them
# future multi-board support?
boards = [ board for board in parent.Group if hasattr(board, 'Type') and board.Type == 'KiConnect::Board' ]
'''
@property
def is_connected(self):
'''
Returns connection status
'''
return self.feature.Connected
def get_polygon(self, polygon_id):
for p in self.polygons:
if p.id.value == polygon_id:
return p
def ping_connection(self, feature):
'''
Ping the KiCAD API to determine if it's connected
'''
connection_status = 'Disconnected'
document_status = 'No Documents'
try:
self.kicad.ping()
feature.Connected = True
connection_status = 'Connected'
except Exception as e:
feature.Connected = False
connection_status = 'Disconnected'
if feature.Connected:
try:
docs = self.kicad.get_open_documents(DocumentType.DOCTYPE_PCB)
document_status = f'{len(docs)} Documents'
feature.DocumentCount = len(docs)
except Exception as e:
print(e)
feature.DocumentCount = 0
feature.Label2 = f'{connection_status} ({document_status})'
return feature.Connected
class APIViewProvider(BaseViewProvider):
ICON = 'kicad/icon_footprint_browser.svg'
TYPE = 'KiConnect::API'
def __init__(self, viewprovider):
super(APIViewProvider, self).__init__(viewprovider)
def makeAPI(parent):
feature = App.ActiveDocument.addObject('App::FeaturePython', 'API')
parent.addObject(feature)
APIObject(feature)
APIViewProvider(feature.ViewObject)
return feature