-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathkicad_api.go
More file actions
533 lines (459 loc) · 14.4 KB
/
kicad_api.go
File metadata and controls
533 lines (459 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"regexp"
"sort"
"strings"
"github.com/samber/lo"
)
// KiCad HTTP Library API data structures
// KiCadCategory represents a category in the KiCad HTTP API
type KiCadCategory struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
// KiCadPartSummary represents a part summary in the parts list
type KiCadPartSummary struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
}
// KiCadPartDetail represents a detailed part in the KiCad HTTP API
type KiCadPartDetail struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
SymbolIDStr string `json:"symbolIdStr,omitempty"`
ExcludeFromBOM string `json:"exclude_from_bom,omitempty"`
Fields map[string]KiCadPartField `json:"fields,omitempty"`
}
// KiCadPartField represents a field in a KiCad part
type KiCadPartField struct {
Value string `json:"value"`
Visible string `json:"visible,omitempty"`
}
// KiCadRootResponse represents the root API response
type KiCadRootResponse struct {
Categories string `json:"categories"`
Parts string `json:"parts"`
}
// KiCadServer represents the KiCad HTTP API server
type KiCadServer struct {
pmDir string
csvCollection *CSVFileCollection
token string
}
// NewKiCadServer creates a new KiCad HTTP API server
func NewKiCadServer(pmDir, token string) (*KiCadServer, error) {
server := &KiCadServer{
pmDir: pmDir,
token: token,
}
// Load CSV collection data
if err := server.loadCSVCollection(); err != nil {
return nil, fmt.Errorf("failed to load CSV collection: %w", err)
}
return server, nil
}
// loadCSVCollection loads the CSV collection from the configured directory
func (s *KiCadServer) loadCSVCollection() error {
if s.pmDir == "" {
return fmt.Errorf("partmaster directory not configured")
}
collection, err := loadAllCSVFiles(s.pmDir)
if err != nil {
return fmt.Errorf("failed to load CSV files from %s: %w", s.pmDir, err)
}
s.csvCollection = collection
return nil
}
// authenticate checks if the request has a valid token
func (s *KiCadServer) authenticate(r *http.Request) bool {
if s.token == "" {
return true // No authentication required if no token set
}
auth := r.Header.Get("Authorization")
expectedAuth := "Token " + s.token
return auth == expectedAuth
}
// getCategories extracts unique categories from the CSV collection
func (s *KiCadServer) getCategories() []KiCadCategory {
categoryMap := make(map[string]bool)
// Extract categories from CSV files - use IPNs from each file
for _, file := range s.csvCollection.Files {
// Extract from IPNs if they exist
if ipnIdx := s.findColumnIndex(file, "IPN"); ipnIdx >= 0 {
for _, row := range file.Rows {
if len(row) > ipnIdx && row[ipnIdx] != "" {
category := s.extractCategory(row[ipnIdx])
if category != "" {
categoryMap[category] = true
}
}
}
}
}
// Convert to sorted slice
categoryNames := lo.Keys(categoryMap)
sort.Strings(categoryNames)
categories := make([]KiCadCategory, len(categoryNames))
for i, name := range categoryNames {
categories[i] = KiCadCategory{
ID: name,
Name: s.getCategoryDisplayName(name),
Description: s.getCategoryDescription(name),
}
}
return categories
}
// findColumnIndex finds the index of a column by name in a CSV file
func (s *KiCadServer) findColumnIndex(file *CSVFile, columnName string) int {
for i, header := range file.Headers {
if header == columnName {
return i
}
}
return -1
}
// extractCategory extracts the CCC component from an IPN
func (s *KiCadServer) extractCategory(ipnStr string) string {
// IPN format: CCC-NNNN-VVVV (also supports CCC-NNN-VVVV for legacy)
re := regexp.MustCompile(`^([A-Z][A-Z][A-Z])-(\d{3,4})-(\d{4})$`)
matches := re.FindStringSubmatch(ipnStr)
if len(matches) >= 2 {
return matches[1]
}
return ""
}
// getCategoryDisplayName returns a human-readable name for a category
func (s *KiCadServer) getCategoryDisplayName(category string) string {
displayNames := map[string]string{
"ANA": "Analog ICs",
"ART": "Artwork",
"CAP": "Capacitors",
"CON": "Connectors",
"CPD": "Compound Components",
"DIO": "Diodes",
"ICS": "Integrated Circuits",
"IND": "Inductors",
"MCU": "Microcontrollers",
"MPU": "Microprocessors",
"OPT": "Optical Components",
"OSC": "Oscillators",
"PWR": "Power Components",
"REG": "Regulators",
"RES": "Resistors",
"RFM": "RF Modules",
"SWI": "Switches",
"XTR": "Transceivers",
"LED": "LEDs",
"SCR": "Screws",
"MCH": "Mechanical",
"PCA": "PCB Assemblies",
"PCB": "Printed Circuit Boards",
"ASY": "Assemblies",
"DOC": "Documentation",
"DFW": "Firmware",
"DSW": "Software",
"DCL": "Declarations",
"FIX": "Fixtures",
"CNT": "Connectors",
"IC": "Integrated Circuits",
"XTL": "Crystals",
"FER": "Ferrites",
"FUS": "Fuses",
"SW": "Switches",
"REL": "Relays",
"TRF": "Transformers",
"SNS": "Sensors",
"DSP": "Displays",
"SPK": "Speakers",
"MIC": "Microphones",
"ANT": "Antennas",
"CBL": "Cables",
}
if displayName, exists := displayNames[category]; exists {
return displayName
}
return category
}
// getCategoryDescription returns a description for a category
func (s *KiCadServer) getCategoryDescription(category string) string {
descriptions := map[string]string{
"ANA": "Analog integrated circuits",
"ART": "Artwork and graphics components",
"CAP": "Capacitor components",
"CON": "Connector components",
"CPD": "Compound and complex components",
"DIO": "Diode components",
"ICS": "Integrated circuit components",
"IND": "Inductor components",
"MCU": "Microcontroller components",
"MPU": "Microprocessor components",
"OPT": "Optical components",
"OSC": "Oscillator components",
"PWR": "Power supply and management components",
"REG": "Voltage regulator components",
"RES": "Resistor components",
"RFM": "RF module components",
"SWI": "Switch components",
"XTR": "Transceiver components",
"LED": "Light emitting diode components",
"SCR": "Screw and fastener components",
"MCH": "Mechanical components",
"PCA": "Printed circuit board assemblies",
"PCB": "Printed circuit boards",
"ASY": "Assembly components",
"DOC": "Documentation components",
"DFW": "Firmware components",
"DSW": "Software components",
"DCL": "Declaration components",
"FIX": "Fixture components",
"CNT": "Connector components",
"IC": "Integrated circuit components",
"XTL": "Crystal components",
"FER": "Ferrite components",
"FUS": "Fuse components",
"SW": "Switch components",
"REL": "Relay components",
"TRF": "Transformer components",
"SNS": "Sensor components",
"DSP": "Display components",
"SPK": "Speaker components",
"MIC": "Microphone components",
"ANT": "Antenna components",
"CBL": "Cable components",
}
if description, exists := descriptions[category]; exists {
return description
}
return fmt.Sprintf("%s components", category)
}
// getPartsByCategory returns parts filtered by category
func (s *KiCadServer) getPartsByCategory(categoryID string) []KiCadPartSummary {
var parts []KiCadPartSummary
for _, file := range s.csvCollection.Files {
// Check if this file belongs to the category
fileName := strings.TrimSuffix(strings.ToUpper(file.Name), ".CSV")
fileCategory := ""
// Try to get category from filename
if len(fileName) == 3 {
fileCategory = fileName
}
// Check parts within this file
ipnIdx := s.findColumnIndex(file, "IPN")
descIdx := s.findColumnIndex(file, "Description")
for _, row := range file.Rows {
if len(row) == 0 {
continue
}
// Determine part category
partCategory := fileCategory
if ipnIdx >= 0 && len(row) > ipnIdx && row[ipnIdx] != "" {
partCategory = s.extractCategory(row[ipnIdx])
}
// Include if category matches
if partCategory == categoryID {
partID := ""
partName := ""
partDesc := ""
// Get part ID (prefer IPN, fallback to row index)
if ipnIdx >= 0 && len(row) > ipnIdx && row[ipnIdx] != "" {
partID = row[ipnIdx]
} else {
partID = fmt.Sprintf("%s-unknown-%d", categoryID, len(parts))
}
// Get description
if descIdx >= 0 && len(row) > descIdx {
partName = row[descIdx]
partDesc = row[descIdx]
}
parts = append(parts, KiCadPartSummary{
ID: partID,
Name: partName,
Description: partDesc,
})
}
}
}
return parts
}
// getPartDetail returns detailed information for a specific part
func (s *KiCadServer) getPartDetail(partID string) *KiCadPartDetail {
for _, file := range s.csvCollection.Files {
ipnIdx := s.findColumnIndex(file, "IPN")
for _, row := range file.Rows {
if len(row) == 0 {
continue
}
// Check if this is the right part
rowPartID := ""
if ipnIdx >= 0 && len(row) > ipnIdx {
rowPartID = row[ipnIdx]
}
if rowPartID == partID {
fields := make(map[string]KiCadPartField)
partName := ""
symbolID := ""
category := s.extractCategory(partID)
// Add all fields from the CSV dynamically
for i, header := range file.Headers {
if i < len(row) && row[i] != "" && header != "" {
// Set name from Description field
if header == "Description" {
partName = row[i]
}
// Set symbol from Symbol field
if header == "Symbol" {
symbolID = row[i]
} else {
// Add field to fields map (exclude Symbol as it goes in symbolIdStr)
fields[header] = KiCadPartField{Value: row[i]}
}
}
}
// Error if no Symbol field found
if symbolID == "" {
log.Printf("ERROR: Part %s has no Symbol field defined", partID)
}
// Format ID as category/part-id (e.g., "rfm/RFM-0000-0001")
formattedID := partID
if category != "" {
formattedID = strings.ToLower(category) + "/" + partID
}
return &KiCadPartDetail{
ID: formattedID,
Name: partName,
SymbolIDStr: symbolID,
ExcludeFromBOM: "false", // Default to include in BOM
Fields: fields,
}
}
}
}
return nil
}
// getSymbolIDFromCategory generates a symbol ID based on category
func (s *KiCadServer) getSymbolIDFromCategory(category string) string {
// Map categories to common KiCad symbol library symbols
symbolMap := map[string]string{
"CAP": "Device:C",
"RES": "Device:R",
"DIO": "Device:D",
"LED": "Device:LED",
"IC": "Device:IC",
"OSC": "Device:Oscillator",
"XTL": "Device:Crystal",
"IND": "Device:L",
"FER": "Device:Ferrite_Bead",
"FUS": "Device:Fuse",
"SW": "Switch:SW_Push",
"REL": "Relay:Relay_SPDT",
"TRF": "Device:Transformer",
"SNS": "Sensor:Sensor",
"CNT": "Connector:Conn_01x02",
"ANT": "Device:Antenna",
"ANA": "Device:IC", // Analog IC
"SCR": "Mechanical:MountingHole",
"MCH": "Mechanical:MountingHole",
}
if symbol, exists := symbolMap[category]; exists {
return symbol
}
// Default symbol
return "Device:Device"
}
// HTTP Handlers
// rootHandler handles the root API endpoint
func (s *KiCadServer) rootHandler(w http.ResponseWriter, r *http.Request) {
if !s.authenticate(r) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Extract base URL from request
baseURL := fmt.Sprintf("%s://%s%s", getScheme(r), r.Host, strings.TrimSuffix(r.URL.Path, "/"))
response := KiCadRootResponse{
Categories: baseURL + "/categories.json",
Parts: baseURL + "/parts",
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(response)
}
// categoriesHandler handles the categories endpoint
func (s *KiCadServer) categoriesHandler(w http.ResponseWriter, r *http.Request) {
if !s.authenticate(r) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
categories := s.getCategories()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(categories)
}
// partsByCategoryHandler handles the parts by category endpoint
func (s *KiCadServer) partsByCategoryHandler(w http.ResponseWriter, r *http.Request) {
if !s.authenticate(r) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Extract category ID from URL path
path := strings.TrimPrefix(r.URL.Path, "/v1/parts/category/")
categoryID := strings.TrimSuffix(path, ".json")
parts := s.getPartsByCategory(categoryID)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(parts)
}
// partDetailHandler handles the part detail endpoint
func (s *KiCadServer) partDetailHandler(w http.ResponseWriter, r *http.Request) {
if !s.authenticate(r) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Extract part ID from URL path
path := strings.TrimPrefix(r.URL.Path, "/v1/parts/")
partID := strings.TrimSuffix(path, ".json")
part := s.getPartDetail(partID)
if part == nil {
http.Error(w, "Part not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(part)
}
// getScheme determines the URL scheme (http or https)
func getScheme(r *http.Request) string {
if r.TLS != nil {
return "https"
}
if r.Header.Get("X-Forwarded-Proto") == "https" {
return "https"
}
return "http"
}
// StartKiCadServer starts the KiCad HTTP API server
func StartKiCadServer(pmDir, token string, port int) error {
server, err := NewKiCadServer(pmDir, token)
if err != nil {
return fmt.Errorf("failed to create KiCad server: %w", err)
}
// Set up routes
http.HandleFunc("/v1/", server.rootHandler)
http.HandleFunc("/v1/categories.json", server.categoriesHandler)
http.HandleFunc("/v1/parts/category/", server.partsByCategoryHandler)
http.HandleFunc("/v1/parts/", server.partDetailHandler)
// Add a health check endpoint
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
addr := fmt.Sprintf(":%d", port)
log.Printf("Starting KiCad HTTP Library API server on %s", addr)
log.Printf("API endpoints:")
log.Printf(" Root: http://localhost%s/v1/", addr)
log.Printf(" Categories: http://localhost%s/v1/categories.json", addr)
log.Printf(" Parts by category: http://localhost%s/v1/parts/category/{category_id}.json", addr)
log.Printf(" Part detail: http://localhost%s/v1/parts/{part_id}.json", addr)
return http.ListenAndServe(addr, nil)
}