-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse_taluts.py
2151 lines (1948 loc) · 120 KB
/
parse_taluts.py
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import datetime
from typedef_bom import BoM_typeDef #класс BoM
from typedef_components import Components_typeDef #класс базы данных компонентов
from typedef_titleBlock import TitleBlock_typeDef #класс основной надписи
script_dirName = os.path.dirname(__file__) #адрес папки со скриптом
script_baseName = os.path.splitext(os.path.basename(__file__))[0] #базовое имя модуля
script_date = datetime.datetime(2024, 6, 8)
designer_name = "Alexander Taluts" #имя разработчика
# ----------------------------------------------------------- Generic functions -------------------------------------------------
#Find tuple items in string (true if any present)
def string_find_any(string, stringTuple, start = 0, end = -1, caseSensitive = False):
if end < 0: end = len(string)
if caseSensitive:
for item in stringTuple:
if string.find(item, start, end) >= 0: return True
else:
string = string.casefold()
for item in stringTuple:
if string.find(item.casefold(), start, end) >= 0: return True
return False
#Find tuple items in string (true if all present)
def string_find_all(string, stringTuple, start = 0, end = -1, caseSensitive = False):
if end < 0: end = len(string)
if caseSensitive:
for item in stringTuple:
if string.find(item, start, end) < 0: return False
else:
string = string.casefold()
for item in stringTuple:
if string.find(item.casefold(), start, end) < 0: return False
return True
#Compare string from strings in a tuple (true if any is equal)
def string_equal(string, stringTuple, caseSensitive = False):
if string is not None:
if caseSensitive:
for item in stringTuple:
if string == item: return True
else:
for item in stringTuple:
if string.casefold() == item.casefold(): return True
return False
#Check if string starts with tuple items
def string_startswith(string, prefixTuple, start = 0, end = -1, caseSensitive = False):
if string is not None:
if end < 0: end = len(string)
if caseSensitive:
for item in prefixTuple:
if string.startswith(item, start, end): return True
else:
string = string.casefold()
for item in prefixTuple:
if string.startswith(item.casefold(), start, end): return True
return False
#Check if string ends with tuple items
def string_endswith(string, prefixTuple, start = 0, end = -1, caseSensitive = False):
if string is not None:
if end < 0: end = len(string)
if caseSensitive:
for item in prefixTuple:
if string.endswith(item, start, end): return True
else:
string = string.casefold()
for item in prefixTuple:
if string.endswith(item.casefold(), start, end): return True
return False
#Extract enclosed substrings from the string (return source string without substings in element 0 and substrings in subsequent elements)
def string_extract_enclosed(string, enclosure = ['(', ')'], start = 0, end = -1, max_extract = -1, case_sensitive = True):
if len(enclosure[0]) + len(enclosure[1]) < 2: return [string]
if end < 0: end = len(string)
if max_extract < 0: max_extract = len(string)
if case_sensitive:
string_cf = string
enclosure_cf = enclosure
else:
string_cf = string.casefold()
enclosure_cf[0] = enclosure[0].casefold()
enclosure_cf[1] = enclosure[1].casefold()
result = ['']
string_start = 0
enclosure_start = start
while len(result) < max_extract + 1:
enclosure_start = string_cf.find(enclosure_cf[0], enclosure_start, end)
enclosure_end = string_cf.find(enclosure_cf[1], enclosure_start, end)
if enclosure_start >= 0 and enclosure_end >= 0 and enclosure_end > enclosure_start:
result[0] += string[string_start:enclosure_start]
result.append(string[enclosure_start + 1:enclosure_end])
string_start = enclosure_end + 1
enclosure_start = enclosure_end
else:
break
result[0] += string[string_start:]
return result
#========================================================== END Generic functions =================================================
# ----------------------------------------------------------- Designer functions --------------------------------------------------
#Заполнение данных проекта
def parse_project(data, **kwargs):
print(' ' * 12 + 'designer: ' + designer_name + ' (' + script_baseName + ')')
print("INFO >> Defining BoM files", end ="... ", flush = True)
#определяем BoM-файлы и имена конфигураций
bomFilePrefix = 'bom' #в моём случае берём файлы с расширением csv начинающиеся на BoM, а всё что между этим - название конфигурации
bomFileExt = 'csv'
for generatedFile in data.generatedFiles:
if os.path.splitext(generatedFile)[1].casefold() == os.extsep + bomFileExt.casefold():
if os.path.basename(generatedFile)[0:3].casefold() == bomFilePrefix.casefold():
data.BoMs.append(generatedFile)
data.BoMVariantNames.append((os.path.basename(generatedFile)[len(bomFilePrefix):-len(os.extsep + bomFileExt)]).strip())
if len(data.BoMs) > 0:
print('done (' + str(len(data.BoMs)) + ' files)')
else:
print("no BoMs found.")
print("INFO >> Parsing project parameters", end ="... ", flush = True)
#определяем откуда брать основную надпись
schematic = data.SchDocs[0] #в моём случае это самый первый схемный файл проекта
schematic.read(casefold_keys = True) #читаем его сворачивая регистр имён параметров
#с какой-то версии Altium после 17 имена полей стали в CamelCase вместо UPPERCASE
keys = {'RECORD':'RECORD', 'OWNERPARTID':'OWNERPARTID', 'NAME':'NAME', 'TEXT':'TEXT'}
#поэтому сворачиваем регистр для сравнения имён полей
for key in keys:
keys[key] = keys[key].casefold()
#читаем нужные поля основной надписи из соответствующих полей схемного файла
for line in schematic.lines:
#анализируем словарь параметров
if keys['RECORD'] in line and keys['OWNERPARTID'] in line and keys['NAME'] in line and keys['TEXT'] in line:
if line[keys['RECORD']] == '41' and line[keys['OWNERPARTID']] == '-1':
if line[keys['NAME']] == 'TitleBlock_01a_DocumentName': data.titleBlock.tb01a_DocumentName += line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_01a_DocumentName_line1': data.titleBlock.tb01a_DocumentName = line[keys['TEXT']] + data.titleBlock.tb01a_DocumentName
elif line[keys['NAME']] == 'TitleBlock_01a_DocumentName_line2': data.titleBlock.tb01a_DocumentName = data.titleBlock.tb01a_DocumentName + ' ' + line[keys['TEXT']]
#elif line[keys['NAME']] == 'TitleBlock_01b_DocumentType': data.titleBlock.tb01b_DocumentType += line[keys['TEXT']]
#elif line[keys['NAME']] == 'TitleBlock_01b_DocumentType_line1': data.titleBlock.tb01b_DocumentType = line[keys['TEXT']] + data.titleBlock.tb01b_DocumentType
#elif line[keys['NAME']] == 'TitleBlock_01b_DocumentType_line2': data.titleBlock.tb01b_DocumentType =data.titleBlock.tb01b_DocumentType + ' ' + line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_02_DocumentDesignator': data.titleBlock.tb02_DocumentDesignator = line[keys['TEXT']].rsplit(' ', 1)[0]
elif line[keys['NAME']] == 'TitleBlock_04_Letter_left': data.titleBlock.tb04_Letter_left = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_04_Letter_middle': data.titleBlock.tb04_Letter_middle = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_04_Letter_right': data.titleBlock.tb04_Letter_right = line[keys['TEXT']]
#elif line[keys['NAME']] == 'TitleBlock_07_SheetNumber': data.titleBlock.tb07_SheetIndex = line[keys['TEXT']]
#elif line[keys['NAME']] == 'TitleBlock_08_SheetTotal': data.titleBlock.tb08_SheetsTotal = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_09_Organization': data.titleBlock.tb09_Organization = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_10d_ActivityType_Extra': data.titleBlock.tb10d_ActivityType_Extra = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_11a_Name_Designer': data.titleBlock.tb11a_Name_Designer = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_11b_Name_Checker': data.titleBlock.tb11b_Name_Checker = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_11c_Name_TechnicalSupervisor': data.titleBlock.tb11c_Name_TechnicalSupervisor = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_11d_Name_Extra': data.titleBlock.tb11d_Name_Extra = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_11e_Name_NormativeSupervisor': data.titleBlock.tb11e_Name_NormativeSupervisor = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_11f_Name_Approver': data.titleBlock.tb11f_Name_Approver = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_13a_SignatureDate_Designer': data.titleBlock.tb13a_SignatureDate_Designer = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_13b_SignatureDate_Checker': data.titleBlock.tb13b_SignatureDate_Checker = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_13c_SignatureDate_TechnicalSupervisor': data.titleBlock.tb13c_SignatureDate_TechnicalSupervisor = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_13d_SignatureDate_Extra': data.titleBlock.tb13d_SignatureDate_Extra = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_13e_SignatureDate_NormativeSupervisor': data.titleBlock.tb13e_SignatureDate_NormativeSupervisor = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_13f_SignatureDate_Approver': data.titleBlock.tb13f_SignatureDate_Approver = line[keys['TEXT']]
#elif line[keys['NAME']] == 'TitleBlock_19_OriginalInventoryNumber': data.titleBlock.tb19_OriginalInventoryNumber = line[keys['TEXT']]
#elif line[keys['NAME']] == 'TitleBlock_21_ReplacedOriginalInventoryNumber': data.titleBlock.tb21_ReplacedOriginalInventoryNumber = line[keys['TEXT']]
#elif line[keys['NAME']] == 'TitleBlock_22_DuplicateInventoryNumber': data.titleBlock.tb22_DuplicateInventoryNumber = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_24_BaseDocumentDesignator': data.titleBlock.tb24_BaseDocumentDesignator = line[keys['TEXT']]
elif line[keys['NAME']] == 'TitleBlock_25_FirstReferenceDocumentDesignator': data.titleBlock.tb25_FirstReferenceDocumentDesignator = line[keys['TEXT']]
#заполняем свойства проекта
data.designator = data.titleBlock.tb02_DocumentDesignator
if data.designator.endswith('Э3'): data.designator = data.designator[:-2]
data.designator = data.designator.strip()
data.name = data.titleBlock.tb01a_DocumentName
data.author = data.titleBlock.tb11a_Name_Designer
print("done.")
#Создание базы данных компонентов из BoM
def parse_components(components, BoM, **kwargs):
print(' ' * 12 + 'designer: ' + designer_name + ' (' + script_baseName + ')')
stats = [0, 0] #статистика [errors, warnings]
print("INFO >> Parsing BoM data", end ="... ", flush = True)
for i in range(len(BoM.entries)):
component = _parse_component(BoM.entries[i], None, stats)
if isinstance(component, Components_typeDef.ComponentTypes.Generic):
components.entries.append(component)
if component.GENERIC_accessory_child is not None:
for child in component.GENERIC_accessory_child:
components.entries.append(child)
else:
stats[0] += 1
print('\n' + ' ' * 12 + "error: parsing bom entry #" + str(i) + " failed")
if stats[0] + stats[1] == 0:
print('done (' + str(len(components.entries)) + ' components created)')
else:
print('\n' + ' ' * 12 + 'completed with ' + str(stats[0]) + ' errors and ' + str(stats[1]) + ' warnings.')
designer_check(components)
#разбор компонента
def _parse_component(bom_entry, parent = None, stats = [0, 0], **kwargs):
decimalPoint = '.'
#определяем тип элемента
kind = bom_entry['BOM_type']
if string_equal(kind, ("Assembly", "Сборка", "Устройство"), False):
component = Components_typeDef.ComponentTypes.Assembly()
elif string_equal(kind, ("Photocell", "Фотоэлемент", "Photodiode", "Фотодиод", "Phototransistor", "Фототранзистор", "Photoresistor", "Фоторезистор"), False):
component = Components_typeDef.ComponentTypes.Photocell()
elif string_equal(kind, ("Capacitor", "Конденсатор"), False):
component = Components_typeDef.ComponentTypes.Capacitor()
elif string_equal(kind, ("Integrated Circuit", "Микросхема"), False):
component = Components_typeDef.ComponentTypes.IntegratedCircuit()
elif string_equal(kind, ("Fastener", "Крепёж"), False):
component = Components_typeDef.ComponentTypes.Fastener()
elif string_equal(kind, ("Heatsink", "Радиатор"), False):
component = Components_typeDef.ComponentTypes.Heatsink()
elif string_equal(kind, ("Circuit Breaker", "Автоматический выключатель", "Fuse", "Предохранитель"), False):
component = Components_typeDef.ComponentTypes.CircuitBreaker()
elif string_equal(kind, ("Surge protector", "Ограничитель перенапряжения", "TVS", "Супрессор", "GDT", "Разрядник", "Varistor", "Варистор"), False):
component = Components_typeDef.ComponentTypes.SurgeProtector()
elif string_equal(kind, ("Cell", "Элемент гальванический", "Battery", "Батарея", "Battery holder", "Держатель батареи"), False):
component = Components_typeDef.ComponentTypes.Battery()
elif string_equal(kind, ("Display", "Дисплей"), False):
component = Components_typeDef.ComponentTypes.Display()
elif string_equal(kind, ("LED", "Светодиод"), False):
component = Components_typeDef.ComponentTypes.LED()
elif string_equal(kind, ("Jumper", "Перемычка"), False):
component = Components_typeDef.ComponentTypes.Jumper()
elif string_equal(kind, ("Relay", "Реле"), False):
component = Components_typeDef.ComponentTypes.Relay()
elif string_equal(kind, ("Inductor", "Индуктивность", "Choke", "Дроссель"), False):
component = Components_typeDef.ComponentTypes.Inductor()
elif string_equal(kind, ("Resistor", "Резистор", "Thermistor", "Термистор", "Posistor", "Позистор", "Potentiometer", "Потенциометр", "Rheostat", "Реостат"), False):
component = Components_typeDef.ComponentTypes.Resistor()
elif string_equal(kind, ("Switch", "Переключатель", "Выключатель", "Button", "Кнопка"), False):
component = Components_typeDef.ComponentTypes.Switch()
elif string_equal(kind, ("Transformer", "Трансформатор"), False):
component = Components_typeDef.ComponentTypes.Transformer()
elif string_equal(kind, ("Diode", "Диод", "Zener", "Стабилитрон", "Varicap", "Варикап"), False):
component = Components_typeDef.ComponentTypes.Diode()
elif string_equal(kind, ("Thyristor", "Тиристор", "TRIAC", "Symistor", "Симистор", "DIAC", "Dynistor", "Динистор"), False):
component = Components_typeDef.ComponentTypes.Thyristor()
elif string_equal(kind, ("Transistor", "Транзистор"), False):
component = Components_typeDef.ComponentTypes.Transistor()
elif string_equal(kind, ("Optoisolator", "Оптоизолятор", "Optocoupler", "Оптопара", "Phototriac", "Оптосимистор"), False):
component = Components_typeDef.ComponentTypes.Optoisolator()
elif string_equal(kind, ("Connector", "Соединитель", "Разъём"), False):
component = Components_typeDef.ComponentTypes.Connector()
elif string_equal(kind, ("EMI filter", "Фильтр ЭМП"), False):
component = Components_typeDef.ComponentTypes.EMIFilter()
elif string_equal(kind, ("Crystal", "Resonator", "Резонатор", "Oscillator", "Осциллятор"), False):
component = Components_typeDef.ComponentTypes.Oscillator()
else:
component = Components_typeDef.ComponentTypes.Generic()
component.GENERIC_kind = kind
#Fill-in generic attributes
component.GENERIC_accessory_parent = parent #ссылка на родительский компонент
#--- десигнатор
if 'Designator' in bom_entry:
if len(bom_entry['Designator'].strip(' ')) > 0:
component.GENERIC_designator = bom_entry['Designator']
if len(component.GENERIC_designator) > 0:
tmp = component.GENERIC_designator.rsplit('.', 1)
if len(tmp) > 1:
component.GENERIC_designator_channel = tmp[0]
tmp = tmp[1]
else:
component.GENERIC_designator_channel = ''
tmp = tmp[0]
component.GENERIC_designator_prefix = ''
for char in tmp:
if not char.isdigit():
component.GENERIC_designator_prefix += char
else:
break
component.GENERIC_designator_index = int(''.join([s for s in tmp if s.isdigit()]))
#--- номинал
if 'BOM_value' in bom_entry:
if len(bom_entry['BOM_value'].strip(' ')) > 0:
component.GENERIC_value = bom_entry['BOM_value']
#--- количество
if 'Quantity' in bom_entry:
if len(bom_entry['Quantity'].strip(' ')) > 0:
component.GENERIC_quantity = int(bom_entry['Quantity'])
#--- производитель
if 'BOM_manufacturer' in bom_entry:
if len(bom_entry['BOM_manufacturer'].strip(' ')) > 0:
component.GENERIC_manufacturer = bom_entry['BOM_manufacturer']
#--- установка на плату
if 'Fitted' in bom_entry:
if bom_entry['Fitted'] == 'Not Fitted':
component.GENERIC_fitted = False
#--- допустимые замены
if 'BOM_substitute' in bom_entry:
substitutes = bom_entry['BOM_substitute']
if len(substitutes) > 0: #проверяем пустое ли поле
component.GENERIC_substitute = [] #создаём пустой список замен чтобы добавлять в него элементы
substitutes = substitutes.split(';')
for entry in substitutes:
tmp = entry.split('*', 1)
sub_note = None
if len(tmp) > 1: sub_note = tmp[1].strip(' ')
tmp = tmp[0].split('@', 1)
sub_value = tmp[0].strip(' ')
sub_manufacturer = None
if len(tmp) > 1: sub_manufacturer = tmp[1].strip(' ')
component.GENERIC_substitute.append(component.Substitute(sub_value, sub_manufacturer, sub_note))
#--- явное определение
if 'BOM_explicit' in bom_entry:
#есть данные в BoM
if string_equal(bom_entry['BOM_explicit'], ('true', 'истина', '1'), False): component.GENERIC_explicit = True
elif string_equal(bom_entry['BOM_explicit'], ('false', 'ложь', '0'), False): component.GENERIC_explicit = False
else: component.GENERIC_explicit = True #значение по-умолчанию если не смогли распознать значение поля
else:
#нет данных в BoM
#legacy: у резисторов и конденсаторов если не указан производитель то задание неявное
component.GENERIC_explicit = True
if isinstance(component, (component.types.Resistor, component.types.Capacitor, component.types.Jumper)):
if component.GENERIC_manufacturer is None: component.GENERIC_explicit = False
#--- footprint - переводим в package с помощью словаря
if 'Footprint' in bom_entry:
for entry in __dict_package:
for word in __dict_package[entry]:
if word == bom_entry['Footprint']:
component.GENERIC_package = entry
break
if component.GENERIC_package is not None: break
#--- примечание
if 'BOM_note' in bom_entry:
if len(bom_entry['BOM_note'].strip(' ')) > 0:
component.GENERIC_note = bom_entry['BOM_note']
#--- описание
if 'BOM_description' in bom_entry:
if len(bom_entry['BOM_description'].strip(' ')) > 0:
component.GENERIC_description = bom_entry['BOM_description']
#Разбираем параметры из описания
if component.GENERIC_description is None: descriptionParams = ['']
else: descriptionParams = [s.strip() for s in component.GENERIC_description.split(',')]
#Сборка (Устройство)
if type(component) is component.types.Assembly:
pass
#Фотоэлемент
elif type(component) is component.types.Photocell:
pass
#Конденсатор
elif type(component) is component.types.Capacitor:
#legacy: затычка для старого формата где у чипов нет ',' после типа конденсатора (впоследствии надо убрать)
tmp = descriptionParams[0].replace('керам. ', 'керам., ')
tmp = tmp.replace('тантал. ', 'тантал., ')
tmp = tmp.split(', ')
if len(tmp) > 1:
descriptionParams[0] = tmp[0]
descriptionParams.insert(1, tmp[1])
#legacy: затычка для старого формата где ёмкость и допуск в разных параметрах
for j in range(len(descriptionParams)):
if descriptionParams[j].endswith('Ф') and j < len(descriptionParams) - 1:
if descriptionParams[j + 1].endswith('%'):
descriptionParams[j] += ' ±' + descriptionParams.pop(j + 1).replace('±', '')
break
#Parsing params
for j in range(len(descriptionParams)):
#тип конденсатора
if component.CAP_type is None:
if string_equal(descriptionParams[j], ('керамический', 'керам.'), False):
component.CAP_type = component.Type.CERAMIC
elif string_equal(descriptionParams[j], ('танталовый', 'тантал.'), False):
component.CAP_type = component.Type.TANTALUM
elif string_equal(descriptionParams[j], ('плёночный', 'плён.'), False):
component.CAP_type = component.Type.FILM
elif string_equal(descriptionParams[j], ('ионистор', 'суперконд.'), False):
component.CAP_type = component.Type.SUPERCAPACITOR
elif string_find_any(descriptionParams[j], ('алюминиевый', 'алюм.'), False):
if string_find_any(descriptionParams[j], ('электролитический', 'эл-лит'), False):
component.CAP_type = component.Type.ALUM_ELECTROLYTIC
elif string_find_any(descriptionParams[j], ('полимерный', 'полим.'), False):
component.CAP_type = component.Type.ALUM_POLYMER
else:
component.CAP_type = component.Type.UNKNOWN
#завершаем обработку если нашли нужный параметр
if component.CAP_type is not None:
descriptionParams[j] = '' #clear parsed parameter
continue
#тип монтажа и типоразмер
if component.GENERIC_mount is None:
if _parse_param_mountandsize(descriptionParams[j], component):
descriptionParams[j] = '' #clear parsed parameter
continue
#тип диэлектрика (температурный коэффициент)
if component.CAP_dielectric is None:
#керамические
if component.CAP_type == component.Type.CERAMIC:
if string_equal(descriptionParams[j], ('COG', 'C0H', 'C0J', 'C0K', 'CCG', 'CGJ', 'M5U', 'NP0', 'P90', 'U2J', 'U2K', 'UNJ', 'X0U', 'X5R', 'X5S', 'X6S', 'X6T','X7R', 'X7S', 'X7T', 'X7U', 'X8G', 'X8L', 'X8M', 'X8R', 'X9M', 'Y5E', 'Y5P', 'Y5R', 'Y5U', 'Y5V', 'Z5U', 'Z7S', 'ZLM'), True):
component.CAP_dielectric = descriptionParams[j]
#плёночные
elif component.CAP_type == component.Type.FILM:
if string_equal(descriptionParams[j], ('PC', 'PEN', 'PET', 'PPS', 'PP', 'PS'), True):
component.CAP_dielectric = descriptionParams[j]
#завершаем обработку если нашли нужный параметр
if component.CAP_dielectric is not None:
descriptionParams[j] = '' #clear parsed parameter
continue
parsing_result = _parse_param_valueWithTolerance(descriptionParams[j], decimalPoint)
if parsing_result is not None:
#ёмкость
if component.CAP_capacitance is None:
if string_equal(parsing_result[0][1], ('F', 'Ф'), True):
component.CAP_capacitance = parsing_result[0][0]
#допуск
if parsing_result[1] is not None:
component.CAP_tolerance = parsing_result[1]
else:
component.flag = component.FlagType.ERROR
stats[0] += 1
print('\n' + ' ' * 12 + 'error! ' + component.GENERIC_designator + ' - tolerance absent or can not be parsed', end = '', flush = True)
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#напряжение
if component.CAP_voltage is None:
if string_equal(parsing_result[0][1], ('V', 'В'), True):
component.CAP_voltage = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#низкий импеданс
if string_equal(descriptionParams[j], ("low ESR", "низк. имп."), False):
component.CAP_lowImpedance = True
descriptionParams[j] = '' #clear parsed parameter
continue
#сборка
parsing_result = _parse_param_array(descriptionParams[j])
if parsing_result is not None:
component.GENERIC_array = parsing_result
descriptionParams[j] = '' #clear parsed parameter
continue
#Микросхема
elif type(component) is component.types.IntegratedCircuit:
pass
#Крепёж
elif type(component) is component.types.Fastener:
pass
#Радиатор
elif type(component) is component.types.Heatsink:
pass
#Автоматический выключатель (Предохранитель)
elif type(component) is component.types.CircuitBreaker:
#Parsing params
for j in range(len(descriptionParams)):
#тип предохранителя
if component.CBRK_type is None:
if string_equal(descriptionParams[j], ('fuse', 'плавкий'), False):
component.CBRK_type = component.Type.FUSE
elif string_equal(descriptionParams[j], ('PTC resettable', 'самовосстанавливающийся', 'самовосст.'), False):
component.CBRK_type = component.Type.FUSE_PTC_RESETTABLE
elif string_equal(descriptionParams[j], ('thermal', 'термо'), False):
component.CBRK_type = component.Type.FUSE_THERMAL
elif string_equal(descriptionParams[j], ('circuit breaker', 'авт. выкл.'), False):
component.CBRK_type = component.Type.BREAKER
elif string_equal(descriptionParams[j], ('holder', 'держатель'), False):
component.CBRK_type = component.Type.HOLDER
#завершаем обработку если нашли нужный параметр
if component.CBRK_type is not None:
descriptionParams[j] = '' #clear parsed parameter
continue
#тип монтажа и типоразмер
if component.GENERIC_mount is None:
if _parse_param_mountandsize(descriptionParams[j], component):
descriptionParams[j] = '' #clear parsed parameter
continue
parsing_result = _parse_param_valueWithTolerance(descriptionParams[j], decimalPoint)
if parsing_result is not None:
#номинальный ток
if component.CBRK_current_rating is None:
if string_equal(parsing_result[0][1], ('A', 'А')):
component.CBRK_current_rating = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#напряжение
if component.CBRK_voltage is None:
if string_equal(parsing_result[0][1], ('V', 'В'), True):
component.CBRK_voltage = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#точка плавления
if component.CBRK_meltingPoint is None:
if string_equal(parsing_result[0][1], ('A²s', 'А²с', 'A?s', 'А?с'), True): #костыли для неюникода
component.CBRK_meltingPoint = parsing_result[0][0]
#фикс неюникода
component.GENERIC_description = component.GENERIC_description.replace('A?s', 'A²s')
component.GENERIC_description = component.GENERIC_description.replace('А?с', 'А²с')
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#классификация скорости срабатывания
if component.CBRK_speed_grade is None:
if string_equal(descriptionParams[j], ('fast', 'быстрый', 'быстр.'), False):
component.CBRK_speed_grade = component.SpeedGrade.FAST
elif string_equal(descriptionParams[j], ('medium', 'средний', 'средн.'), False):
component.CBRK_speed_grade = component.SpeedGrade.MEDIUM
elif string_equal(descriptionParams[j], ('slow', 'медленный', 'медл.'), False):
component.CBRK_speed_grade = component.SpeedGrade.SLOW
#завершаем обработку если нашли нужный параметр
if component.CBRK_speed_grade is not None:
descriptionParams[j] = '' #clear parsed parameter
continue
#Ограничитель перенапряжения
elif type(component) is component.types.SurgeProtector:
#Определяем тип по разновидности компонента
if string_equal(component.GENERIC_kind, ("TVS", "Супрессор"), False):
component.SPD_type = component.Type.DIODE
elif string_equal(component.GENERIC_kind, ("Varistor", "Варистор"), False):
component.SPD_type = component.Type.VARISTOR
elif string_equal(component.GENERIC_kind, ("GDT", "Разрядник"), False):
component.SPD_type = component.Type.GAS_DISCHARGE_TUBE
#Parsing params
for j in range(len(descriptionParams)):
#тип монтажа и типоразмер
if component.GENERIC_mount is None:
if _parse_param_mountandsize(descriptionParams[j], component):
descriptionParams[j] = '' #clear parsed parameter
continue
#ток гашения выброса
if component.SPD_clamping_current is None:
parsing_result = _parse_param_valueWithToleranceAtConditions(descriptionParams[j], decimalPoint)
if parsing_result is not None:
if string_equal(parsing_result[0][1], ('A', 'А'), True):
component.SPD_clamping_current = parsing_result[0][0]
if component.SPD_testPulse is None and parsing_result[2] is not None:
conditions = parsing_result[2][0].replace(' ', '')
if string_equal(conditions, ('8/20us', '8/20мкс'), False):
component.SPD_testPulse = component.TestPulse.US_8_20
elif string_equal(conditions, ('10/1000us', '10/1000мкс'), False):
component.SPD_testPulse = component.TestPulse.US_10_1000
else:
component.SPD_testPulse = component.TestPulse.UNKNOWN
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#диод
if component.SPD_type == component.Type.DIODE:
#направленность
if component.SPD_bidirectional is None:
if string_equal(descriptionParams[j], ('однонаправленный', 'однонаправ.'), False):
component.SPD_bidirectional = False
elif string_equal(descriptionParams[j], ('двунаправленный', 'двунаправ.'), False):
component.SPD_bidirectional = True
#завершаем обработку если нашли нужный параметр
if component.SPD_bidirectional is not None:
descriptionParams[j] = '' #clear parsed parameter
continue
parsing_result = _parse_param_valueWithToleranceAtConditions(descriptionParams[j], decimalPoint)
if parsing_result is not None:
#максимальное рабочее напряжение
if component.SPD_standoff_voltage is None:
if string_equal(parsing_result[0][1], ('V', 'В'), True):
component.SPD_standoff_voltage = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#мощность
if component.SPD_power is None:
if string_equal(parsing_result[0][1], ('W', 'Вт'), True):
component.SPD_power = parsing_result[0][0]
if component.SPD_testPulse is None and parsing_result[2] is not None:
conditions = parsing_result[2][0].replace(' ', '')
if string_equal(conditions, ('8/20us', '8/20мкс'), False):
component.SPD_testPulse = component.TestPulse.US_8_20
elif string_equal(conditions, ('10/1000us', '10/1000мкс'), False):
component.SPD_testPulse = component.TestPulse.US_10_1000
else:
component.SPD_testPulse = component.TestPulse.UNKNOWN
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#варистор
elif component.SPD_type == component.Type.VARISTOR:
parsing_result = _parse_param_valueWithToleranceAtConditions(descriptionParams[j], decimalPoint)
if parsing_result is not None:
#максимальное рабочее напряжение
if component.SPD_standoff_voltage is None:
if string_equal(parsing_result[0][1], ('V', 'В'), True):
component.SPD_standoff_voltage = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#энергия
if component.SPD_energy is None:
if string_equal(parsing_result[0][1], ('J', 'Дж'), True):
component.SPD_energy = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#газоразрядник
elif component.SPD_type == component.Type.GAS_DISCHARGE_TUBE:
pass
#сборка
parsing_result = _parse_param_array(descriptionParams[j])
if parsing_result is not None:
component.GENERIC_array = parsing_result
descriptionParams[j] = '' #clear parsed parameter
continue
#Батарея
elif type(component) is component.types.Battery:
#Определяем тип по разновидности компонента
if string_equal(component.GENERIC_kind, ("Battery holder", "Держатель батареи"), False):
component.BAT_type = component.Type.HOLDER
elif string_equal(component.GENERIC_kind, ("Cell", "Элемент гальванический"), False):
component.BAT_type = component.Type.CELL
elif string_equal(component.GENERIC_kind, ("Battery", "Батарея"), False):
component.BAT_type = component.Type.BATTERY
#Parsing params
for j in range(len(descriptionParams)):
#тип (ищем признак держателя в описании)
if component.BAT_type != component.Type.HOLDER:
if string_equal(descriptionParams[j], ('holder', 'держатель'), False):
component.BAT_type = component.Type.HOLDER
descriptionParams[j] = '' #clear parsed parameter
continue
#диапазон рабочих температур
if component.GENERIC_temperature_range is None:
parsing_result = _parse_param_temperatureRange(descriptionParams[j], decimalPoint)
if parsing_result is not None:
component.GENERIC_temperature_range = parsing_result
descriptionParams[j] = '' #clear parsed parameter
continue
parsing_result = _parse_param_valueWithToleranceAtConditions(descriptionParams[j], decimalPoint)
if parsing_result is not None:
#номинальное напряжение
if component.BAT_voltage_rated is None:
if string_equal(parsing_result[0][1], ('V', 'В'), True):
component.BAT_voltage_rated = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#ёмкость
if component.BAT_capacity is None:
if string_equal(parsing_result[0][1], ('Ah', 'Ач'), True):
component.BAT_capacity = parsing_result[0][0]
#допуск
#if parsing_result[1] is not None:
# component.BAT_capacity_tolerance = parsing_result[1]
#условия измерения
if parsing_result[2] is not None:
for k in range(len(parsing_result[2])):
condition = _parse_param_value(parsing_result[2][k], decimalPoint)
if condition is not None:
#ток нагрузки
if string_equal(condition[1], ('A', 'А'), True):
component.BAT_capacity_load_current = condition[0]
parsing_result[2][k] = ''
continue
#сопротивление нагрузки
if string_equal(condition[1], ('Ohm', 'Ом'), True):
component.BAT_capacity_load_resistance = condition[0]
parsing_result[2][k] = ''
continue
#напряжение отсечки
if string_equal(condition[1], ('V', 'В'), True):
component.BAT_capacity_voltage = condition[0]
parsing_result[2][k] = ''
continue
#температура
if string_equal(condition[1], ('°C', '℃', 'K', 'К'), True):
component.BAT_capacity_temperature = _parse_param_temperature(condition, decimalPoint)
parsing_result[2][k] = ''
continue
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#Дисплей
elif type(component) is component.types.Display:
#Parsing params
for j in range(len(descriptionParams)):
#тип
if component.DISP_type is None:
if string_equal(descriptionParams[j], ('7-seg', '7-сегм.', '7 segment'), False):
component.DISP_type = component.Type.NUMERIC_7SEG
elif string_equal(descriptionParams[j], ('14-seg', '14-сегм.', '14 segment'), False):
component.DISP_type = component.Type.ALPHANUMERIC_14SEG
elif string_equal(descriptionParams[j], ('16-seg', '16-сегм.', '16 segment'), False):
component.DISP_type = component.Type.ALPHANUMERIC_16SEG
elif string_equal(descriptionParams[j], ('bar graph', 'шкальный'), False):
component.DISP_type = component.Type.BARGRAPH
elif string_equal(descriptionParams[j], ('dot matrix', 'матричный'), False):
component.DISP_type = component.Type.DOTMATRIX
elif string_equal(descriptionParams[j], ('graphic', 'графический'), False):
component.DISP_type = component.Type.GRAPHIC
#завершаем обработку если нашли нужный параметр
if component.DISP_type is not None:
descriptionParams[j] = '' #clear parsed parameter
continue
#структура
if component.DISP_structure is None:
if string_equal(descriptionParams[0], ('LED', 'светодиодный'), False):
component.DISP_structure = component.Structure.LED
elif string_equal(descriptionParams[0], ('OLED', 'орг. светодиодный'), False):
component.DISP_structure = component.Structure.OLED
elif string_equal(descriptionParams[0], ('LCD', 'жидкокрист.'), False):
component.DISP_structure = component.Structure.LCD
elif string_equal(descriptionParams[0], ('VFD', 'вак. люм.'), False):
component.DISP_structure = component.Structure.VFD
#завершаем обработку если нашли нужный параметр
if component.DISP_structure is not None:
descriptionParams[j] = '' #clear parsed parameter
continue
#цвет
if component.DISP_color is None:
parsing_result = _parse_param_color(descriptionParams[j])
if parsing_result is not None:
component.DISP_color = parsing_result
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#сборка
parsing_result = _parse_param_array(descriptionParams[j])
if parsing_result is not None:
component.GENERIC_array = parsing_result
descriptionParams[j] = '' #clear parsed parameter
continue
#Светодиод
elif type(component) is component.types.LED:
#Parsing params
for j in range(len(descriptionParams)):
#тип монтажа и типоразмер
if component.GENERIC_mount is None:
if _parse_param_mountandsize(descriptionParams[j], component):
descriptionParams[j] = '' #clear parsed parameter
continue
#цвет
if component.LED_color is None:
parsing_result = _parse_param_color(descriptionParams[j])
if parsing_result is not None:
component.LED_color = parsing_result
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#индекс цветопередачи
if component.LED_color_renderingIndex is None:
if descriptionParams[j].startswith('CRI'):
parsing_result = _parse_param_value(descriptionParams[j][3:], decimalPoint)
if parsing_result is not None:
component.LED_color_renderingIndex = parsing_result[0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
parsing_result = _parse_param_valueWithToleranceAtConditions(descriptionParams[j], decimalPoint)
if parsing_result is not None:
#длина волны
if (component.LED_color is None) or (component.LED_color <= component.Color.VIOLET):
if (component.LED_wavelength_peak is None) and (component.LED_wavelength_dominant is None):
if string_equal(parsing_result[0][1], ('m', 'м'), True):
if isinstance(parsing_result[0][0], list):
component.LED_wavelength_peak = parsing_result[0][0][0]
component.LED_wavelength_dominant = parsing_result[0][0][1]
else:
component.LED_wavelength_peak = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#цветовая температура
if component.LED_color == component.Color.WHITE:
if component.LED_color_temperature is None:
if string_equal(parsing_result[0][1], ('K', 'К'), True):
component.LED_color_temperature = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#сила света
if component.LED_luminous_intensity is None:
if string_equal(parsing_result[0][1], ('cd', 'кд'), True):
component.LED_luminous_intensity = parsing_result[0][0]
if parsing_result[2] is not None:
conditions = _parse_param_value(parsing_result[2][0], decimalPoint)
if conditions is not None:
if string_equal(conditions[1], ('A', 'А'), True):
component.LED_luminous_intensity_current = conditions[0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#световой поток
if component.LED_luminous_flux is None:
if string_equal(parsing_result[0][1], ('lm', 'лм'), True):
component.LED_luminous_flux = parsing_result[0][0]
if parsing_result[2] is not None:
conditions = _parse_param_value(parsing_result[2][0], decimalPoint)
if conditions is not None:
if string_equal(conditions[1], ('A', 'А'), True):
component.LED_luminous_flux_current = conditions[0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#угол обзора
if component.LED_viewingAngle is None:
if string_equal(parsing_result[0][1], ('°', 'degrees', 'град.'), True):
component.LED_viewingAngle = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#прямой ток
if (component.LED_current_nominal is None) and (component.LED_current_maximum is None):
if string_equal(parsing_result[0][1], ('A', 'А'), True):
if isinstance(parsing_result[0][0], list):
component.LED_current_nominal = parsing_result[0][0][0]
component.LED_current_maximum = parsing_result[0][0][1]
else:
component.LED_current_nominal = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#прямое падение напряжения
if component.LED_voltage_forward is None:
if string_equal(parsing_result[0][1], ('V', 'В'), True):
component.LED_voltage_forward = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#сборка
parsing_result = _parse_param_array(descriptionParams[j])
if parsing_result is not None:
component.GENERIC_array = parsing_result
descriptionParams[j] = '' #clear parsed parameter
continue
#Перемычка
elif type(component) is component.types.Jumper:
#Parsing params
for j in range(len(descriptionParams)):
#тип
if component.JMP_type is None:
if string_equal(descriptionParams[j], ('thermal', 'термо'), False):
component.JMP_type = component.Type.THERMAL
descriptionParams[j] = '' #clear parsed parameter
continue
else:
component.JMP_type = component.Type.ELECTRICAL
#тип монтажа и типоразмер
if component.GENERIC_mount is None:
if _parse_param_mountandsize(descriptionParams[j], component):
descriptionParams[j] = '' #clear parsed parameter
continue
#Реле
elif type(component) is component.types.Relay:
pass
#Индуктивность
elif type(component) is component.types.Inductor:
#Определяем тип
if string_equal(component.GENERIC_kind, ("Inductor", "Индуктивность"), False):
component.IND_type = component.Type.INDUCTOR
elif string_equal(component.GENERIC_kind, ("Choke", "Дроссель"), False):
component.IND_type = component.Type.CHOKE
#legacy: затычка для старого формата где ёмкость и допуск в разных параметрах
for j in range(len(descriptionParams)):
if descriptionParams[j].endswith('Гн') and j < len(descriptionParams) - 1:
if descriptionParams[j + 1].endswith('%'):
descriptionParams[j] += ' ±' + descriptionParams.pop(j + 1).replace('±', '')
break
#Parsing params
for j in range(len(descriptionParams)):
#тип монтажа и типоразмер
if component.GENERIC_mount is None:
if _parse_param_mountandsize(descriptionParams[j], component):
descriptionParams[j] = '' #clear parsed parameter
continue
parsing_result = _parse_param_valueWithTolerance(descriptionParams[j], decimalPoint)
if parsing_result is not None:
#индуктивность
if component.IND_inductance is None:
if string_equal(parsing_result[0][1], ('H', 'Гн'), True):
component.IND_inductance = parsing_result[0][0]
#допуск
if parsing_result[1] is not None:
component.IND_tolerance = parsing_result[1]
else:
component.flag = component.FlagType.ERROR
stats[0] += 1
print('\n' + ' ' * 12 + 'error! ' + component.GENERIC_designator + ' - tolerance absent or can not be parsed', end = '', flush = True)
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#ток
if component.IND_current is None:
if string_equal(parsing_result[0][1], ('A', 'А'), True):
component.IND_current = parsing_result[0][0]
#clear parsed parameter and go to next param
descriptionParams[j] = ''
continue
#Резистор
elif type(component) is component.types.Resistor:
#legacy: затычка для старого формата где сопротивление и допуск в разных параметрах
for j in range(len(descriptionParams)):
if descriptionParams[j].endswith('Ом') and j < len(descriptionParams) - 1:
if descriptionParams[j + 1].endswith('%'):
descriptionParams[j] += ' ±' + descriptionParams.pop(j + 1).replace('±', '')
break
#тип
if string_equal(component.GENERIC_kind, ("Resistor", "Резистор"), False):
component.RES_type = component.Type.FIXED
elif string_equal(component.GENERIC_kind, ("Potentiometer", "Потенциометр", "Rheostat", "Реостат"), False):
component.RES_type = component.Type.VARIABLE
elif string_equal(component.GENERIC_kind, ("Thermistor", "Термистор", "Posistor", "Позистор"), False):
component.RES_type = component.Type.THERMAL
#Parsing params
for j in range(len(descriptionParams)):
#структура
if component.RES_structure is None:
if string_equal(descriptionParams[0], ('тонкоплёночный', 'тонкоплён.'), False):
component.RES_structure = component.Structure.THIN_FILM
elif string_equal(descriptionParams[0], ('толстоплёночный', 'толстоплён.'), False):
component.RES_structure = component.Structure.THICK_FILM
elif string_equal(descriptionParams[0], ('металло-плёночный', 'мет-плён.'), False):
component.RES_structure = component.Structure.METAL_FILM
elif string_equal(descriptionParams[0], ('углеродистый', 'углерод.'), False):
component.RES_structure = component.Structure.CARBON_FILM