API¶
KiABOM utilises API requests to retrieve part data from suppliers, and saves the parsed data in the cache for the specified duration. The KiCad netlist reader module is used to read the schematic, and the MPN field value is used for the requests using the supplier APIs. The data from both preferred and alternative suppliers is the combined into a single object which is then used to generate the BOM.
Summary¶
Functions
|
Get the footprint name from the Lib:Name string in the footprint symbol field. |
|
Generate a BOM row as a list of strings. |
|
Get a string as a table data cell HTML element. |
|
Get the HTML table containing the BOM data |
|
Output some general info afte the HTML BOM table. |
|
Override csv.writer's writerow() to support encoding conversion (initial encoding is utf8) |
|
Write the rows for the CSV BOM |
|
Write the general info to the CSV |
|
Write to the corresponding file the collated data. |
|
Return the selected equivalence function to be used in grouping |
|
Open the file to be used for outputing the BOM data. |
Print the title splash. |
|
|
Get the specified columns for use during BOM generation. |
|
Calls get_columns() to get the groups for BOM generation |
|
Check if there is a valid internet connection. |
|
Download the datasheets from the 'Datasheets' symbol field |
|
Check the input arguments are valid. |
Automatically set the output format based on the output file extension |
|
Read the config file placed in the same directory as the main script file. |
|
|
Main function executed when __name__ is "__main__". |
Classes
|
Class containing KiCad netlist data |
|
Information for each part parsed from the API which is then cached. |
|
Derived information from parts info. |
|
Base SupplierAPI class to be used by all supported supplier APIs |
|
Class for Mouser API. |
|
Class for DigiKey API. |
|
Class containing parts data from the API |
|
Class used for currency conversion |
|
Class containing the file data required to create the BOM. |
Definitions¶
Definitions for the above summary tables.
Functions¶
- kiabom.get_footprint_name(text: str) str¶
Get the footprint name from the Lib:Name string in the footprint symbol field.
- Parameters:
text – Footprint field string.
- Returns:
Footprint name or blank.
- kiabom.get_bom_row(pos: int, group: list[comp], columns: list[str], bom_data: BomData) list[str]¶
Generate a BOM row as a list of strings.
- Parameters:
pos – Index position
group – List of comp() objects from the KiCad netlist reader indicating the component group
columns – Columns list to use
bom_data – BomData object
- Returns:
List of strings indicating the BOM row of the component group
- kiabom.html_get_td_string(string: str) str¶
Get a string as a table data cell HTML element.
- Parameters:
string – Text to be placed between the <td> and </td>.
- Returns:
String encloded by <td> and </td>.
- kiabom.html_get_table(html_text: str, columns: list[str], grouped: list[list[comp]], bom_data: BomData) str¶
Get the HTML table containing the BOM data
- Parameters:
html_text – Text containing HTML template
columns – Columns list
grouped – A list containing lists of grouped parts
bom_data – BomData object
- Returns:
HTML string
- kiabom.html_output_general_info(html: str, net: netlist, board_quantity: int) str¶
Output some general info afte the HTML BOM table.
- Parameters:
html – HTML string.
net – Netlist object opened using kicad_netlist_reader.
board_quantity – Board quantity.
- Returns:
HTML string.
- kiabom.csv_writerow(acsvwriter, columns: list[str])¶
Override csv.writer’s writerow() to support encoding conversion (initial encoding is utf8)
- Parameters:
acsvwriter (csv.writer object) – A csv.writer object used to write the columns list.
columns – A list of string values to write as a row.
- kiabom.csv_write_bom(out, columns: list[str], grouped: list[list[comp]], bom_data: BomData)¶
Write the rows for the CSV BOM
- Parameters:
out (csv.writer object) – A csv.writer object created with csv.writer().
columns – Columns list
grouped – A list containing lists of grouped parts
bom_data – BomData object
- kiabom.csv_output_general_info(out, net: netlist, board_quantity: int)¶
Write the general info to the CSV
- Parameters:
out (csv.writer object) – A csv.writer object created with csv.writer().
net – The netlist object created by opening the XML with kicad_netlist_reader.
board_quantity – Board quantity.
- kiabom.write_to_file(f: TextIOWrapper, output_format: str, headers_flag: bool, info_flag: bool, sum_flag: bool, board_quantity: int, columns: list[str], net_obj: KiCadNetlist, bom_data: BomData)¶
Write to the corresponding file the collated data.
- Parameters:
f – File object
output_format – Selected output format.
headers_flag – Flag to output headers to the BOM table.
info_flag – Flag to output extra info to the end of the file.
sum_flag – Flag to output the total price sum after the BOM table.
board_quantity – Specify board quantity.
columns – Columns to be used when outputting BOM.
net_obj – A Net object.
bom_data – A BomData object.
- kiabom.get_equ(group_fields_list: list[str])¶
Return the selected equivalence function to be used in grouping
- Parameters:
group_fields_list – List of group fields to group by
- Returns:
Equivalence (__equ__) function.
- Return type:
Function returning True or False.
- kiabom.open_output_file(output_file: str) TextIOWrapper¶
Open the file to be used for outputing the BOM data.
- Parameters:
output_file – Output file name.
- Returns:
A file object.
- kiabom.print_title_screen()¶
Print the title splash.
- kiabom.get_columns(columns: str, preset: str, preset_dict: dict) list[str]¶
Get the specified columns for use during BOM generation.
- Parameters:
columns – Comma separated string of the columns names.
preset – Specified column list preset.
preset_dict – Preset dictionary to get columns from
- Returns:
A column string list.
- kiabom.get_group_by(group_by: str, preset: str, preset_dict: dict) list[str]¶
Calls get_columns() to get the groups for BOM generation
- kiabom.has_internet(test_address: str = '8.8.8.8', timeout: int = 2) bool¶
Check if there is a valid internet connection.
- Parameters:
test_address – Address used to test for internet connection.
timeout – Time to wait until a valid internet connection is established.
- Returns:
True or False on whether there is an internet connection.
- kiabom.download_datasheets(grouped: list[list[comp]], downloads_folder: str | Path = 'datasheets', timeout: int = 2)¶
Download the datasheets from the ‘Datasheets’ symbol field
- Parameters:
grouped – A list containing lists of grouped parts
downloads_folder – Downloads folder name
timeout – Time in seconds where the internet connection will time out.
- kiabom.check_args(args: Namespace)¶
Check the input arguments are valid.
- Parameters:
args – Input arguments.
- kiabom.set_format_from_output_file_extension(output_file: str) str¶
Automatically set the output format based on the output file extension
- Parameters:
output_file – Output file name.
- Returns:
Output file format.
- kiabom.read_config() dict¶
Read the config file placed in the same directory as the main script file. If no config was found, use the hardcoded options instead.
- Returns:
Dictionary of YAML file
- kiabom.main(argv: list[str])¶
Main function executed when __name__ is “__main__”.
- Parameters:
argv – Argument vector containing command line options.
Classes¶
- class kiabom.KiCadNetlist(input_xml: str | Path, excludeBOM: bool, excludeBoard: bool, DNP: bool)¶
Class containing KiCad netlist data
- Parameters:
net – Netlist reader object.
components – List of components from the schematic.
grouped – A list containing lists of grouped parts
refdes_groups – List of reference designator groups
- get_refdes_from_net()¶
Get reference designators from KiCAD netlist reader
- remove_ignore_mpn_parts(ignore_mpns: list[str])¶
Remove the parts with the MPN values found in the ignore_mpns list
- Parameters:
ignore_mpns – List containing MPN values to ignore
- class kiabom.PartsInfo(datasheet: str = '', description: str = '', manufacturer: str = '', mpn: str = '', order_code: str = '', stock: str = '', supplier: str = '', product_page: str = '', price_tiers: dict = <factory>, currency_code: str = '')¶
Information for each part parsed from the API which is then cached. Class members are based only on API result. Full parts info is split into two classes to minimise cache.
- class kiabom.BomPartsInfo(datasheet: str = '', description: str = '', manufacturer: str = '', mpn: str = '', order_code: str = '', stock: str = '', supplier: str = '', product_page: str = '', price_tiers: dict = <factory>, currency_code: str = '', price: float = 0, quantity: int = 0)¶
Derived information from parts info. Done to minimise cache.
- class kiabom.SupplierAPI(cache_ttl: int, time: int = 1782300176)¶
Base SupplierAPI class to be used by all supported supplier APIs
- Parameters:
name – Supplier name
api_status – Supplier API status. Should be “success” or any error string
comp_count – Number of components found
cache_comp_count – Number of components found in cache
cache_path – Supplier cache path
cache_ttl – Cache time-to-live
time – Time used for cache_ttl comparison
req_counter – Requests counter
last_sleep – Store the last sleep time since epoch
rate_limi – Number of requests per minute allowed by the API
- api_init(config: dict) str¶
Supplier API initialisation function. All derived classes must return a “success” string on success
- Parameters:
config – Config dict
- Raises:
NotImplementedError –
- Returns:
“success” on success and other error strings on failure
- cache_mpn_normalise(mpn: str) str¶
Normalize the MPN string to a string that can be used as a file name.
- Parameters:
mpn – MPN value
- Returns:
normalized MPN value
- cache_part(mpn: str, part_info: PartsInfo)¶
Store the specified part in the cache
- Parameters:
mpn – MPN value
data – KiABOM dict of specified part
- cache_query(mpn: str) PartsInfo | None¶
Query the cache for the requested MPN
- Parameters:
mpn – requested MPN
- Returns:
KiABOM dictionary or None if not found in cache
- check_rate_limit()¶
Check if the requests have reached the per minute rate limit and sleep the script if they have
- get_part(mpn: str, ignore_mpns: list[str] | None) PartsInfo¶
Get the specified part MPN for KiABOM. Calls the search and parser functions. Also handles the required caching for each part and checking if the rate limit has been reached.
- Parameters:
mpn – MPN value
ignore_mpns – List of ignore MPN strings
- Returns:
Parsed API response in a PartsInfo() object
- parse(parts: list[dict]) list[PartsInfo]¶
Parse the API result into the dictionary KiABOM uses for BOM generation. Look at the other parse functions for examples.
- Parameters:
parts – List of API results
- Raises:
NotImplementedError –
- Returns:
List of parsed API results
- print_stats()¶
Print some stats to see how many parts from cache were used
- search(mpn: str) list[dict]¶
Search the MPN with the Supplier API. Also outputs any errors from the request.
- Parameters:
mpn – MPN value
- Raises:
NotImplementedError –
- Returns:
List of API results
- class kiabom.MouserAPI(config: dict, cache_ttl: int)¶
Class for Mouser API.
- Parameters:
cache_path – Cache path
name – Name of supplier
currency_code – Currency code for/from parts search
api_status – API status string
rate_limi – Number of requests per minute allowed by the supplier’s API
- api_init(config: dict) str¶
Supplier API initialisation function. All derived classes must return a “success” string on success
- Parameters:
config – Config dict
- Raises:
NotImplementedError –
- Returns:
“success” on success and other error strings on failure
- get_currency_code(price_tiers_list: list[dict]) str¶
MouserAPI-specific function to get the currency code
- Parameters:
price_tiers_list – Price tiers from API response
- Returns:
Dict of the price tiers
- get_price_tiers(price_tiers_list: list[dict]) dict¶
MouserAPI-specific function to get the price tiers
- Parameters:
price_tiers_list – Price tiers from API response
- Returns:
Dict of the price tiers
- parse(parts: list[dict]) list[PartsInfo]¶
Parse the API result into the dictionary KiABOM uses for BOM generation. Look at the other parse functions for examples.
- Parameters:
parts – List of API results
- Raises:
NotImplementedError –
- Returns:
List of parsed API results
- search(mpn: str) list¶
Search the MPN with the Supplier API. Also outputs any errors from the request.
- Parameters:
mpn – MPN value
- Raises:
NotImplementedError –
- Returns:
List of API results
- class kiabom.DigiKeyAPI(config: dict, cache_ttl: int)¶
Class for DigiKey API.
- Parameters:
cache_path – Cache path
name – Name of supplier
currency_code – Currency code for/from parts search
api_status – API status string
rate_limi – Number of requests per minute allowed by the supplier’s API
- api_init(config: dict) str¶
Supplier API initialisation function. All derived classes must return a “success” string on success
- Parameters:
config – Config dict
- Raises:
NotImplementedError –
- Returns:
“success” on success and other error strings on failure
- get_order_code(product_variations: list[dict]) str¶
DigiKeyAPI-specific function to get the order code.
- Parameters:
product_variations – Product variations entry from API response
- Returns:
Order code
- get_order_code_price_tiers(order_code: str, product_variations: list[dict]) dict¶
DigiKeyAPI-specific function to get the price tiers
- Parameters:
order_code – Order code
product_variations – Product variations entry from API response
- Returns:
Dict of the price tiers
- parse(parts: list[dict]) list[PartsInfo]¶
Parse the API result into the dictionary KiABOM uses for BOM generation. Look at the other parse functions for examples.
- Parameters:
parts – List of API results
- Raises:
NotImplementedError –
- Returns:
List of parsed API results
- search(mpn: str, site: str = 'uk', language: str = 'en', currency: str = 'usd') list[dict]¶
Search the MPN with the Supplier API. Also outputs any errors from the request.
- Parameters:
mpn – MPN value
- Raises:
NotImplementedError –
- Returns:
List of API results
- class kiabom.PartsSearch(supplier: str, grouped: list[list[comp]], ignore_mpns: list, config: dict, cache_ttl: int)¶
Class containing parts data from the API
- Parameters:
parts_list – List of dictionaries of the parsed API results for each part
supplier – SupplierAPI object
- search_parts(grouped: list[list[comp]], ignore_mpns: list) list[PartsInfo]¶
Search the parts from the KiCad netlist groups and print status messages
- Parameters:
grouped – KiCad netlist reader grouped parts
ignore_mpns – List of MPN values to ignore
- Returns:
List of dictionaries of the parsed API results
- class kiabom.CurrencyConverter(currency_code: str, use_cache: bool = True)¶
Class used for currency conversion
- Parameters:
requested_currency – Currency specified
currency_rates – Currency rates in use
- convert(from_currency: str, price: float, to_currency: str) float¶
Convert a price from one currency to the other
- Parameters:
from_currency – Currency code to convert from
price – Price to convert
to_currency – Currency code to convert to
- Returns:
Converted currency to 7 decimal places
- class kiabom.BomData(pref_obj: PartsSearch, alt_obj: PartsSearch, refdes_groups: list[list[str]], board_quantity: int, currency_conv: CurrencyConverter | None)¶
Class containing the file data required to create the BOM. Has data from both preferred and alternative suppliers. Part quantity is resolved based on requested board quantity and group component count. Using the quantity, the price is retrieved based on the price tiers in the response. This price is then converted to the requested currency.
- Parameters:
pref – Preferred supplier object
alt – Alternative supplier object
currency_conv – CurrencyConverter object
filled_res – Preferred API response with gaps filled from alternative response
total_price_sum – Total price sum of all parts