Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
trung_ho committed Apr 26, 2023
1 parent a538872 commit e72fc56
Show file tree
Hide file tree
Showing 16 changed files with 1,004 additions and 1 deletion.
20 changes: 20 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Python cache directory
__pycache__/

# Compiled Python bytecode
*.py[cod]

# Log files
*.log

# build ouput
build/

# JetBrains IDE
.idea/

# Generated by MacOS
.DS_Store

# Generated by Windows
Thumbs.db
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Digi-Key Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
100 changes: 100 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# KiCad addon: Push parts to Digi-Key myLists

This addon helps you collect parts in your [KiCad](https://www.kicad.org/) schematic file and push them to Digi-Key [myLists](https://www.digikey.com/en/mylists/).

> With myLists, you can calculate assemblies, find alternates, calculate attrition, and more.
## Installation

- Download the addon from [latest release](https://github.com/Digi-Key/KiCad-Push-to-DigiKey/releases/latest)
- Open KiCad, select KiCad Plugin and Content Manager, click `Install from File...`
- Select the downloaded .zip file in step 1, click `Open`

## Usage

- Open the `PCB Editor` (not Schematic Editor), click the `Push to Digi-Key myLists` icon on the toolbar
- In the dialog that opens, press the `Create DigiKey List` button
- Parts will be pushed to Digi-Key myLists

![Plugin installed](images/plugin-installed.png)
![Plugin in PCB editor](images/plugin-in-PCB-editor.png)
![Parts pushed to Digi-Key myLists](images/parts-pushed-todigikey-mylists.png)

## Frequently Asked Questions

Q: The Part Numbers column does not seem right.

A: The addon tries to guess which column contains part numbers from the schematic file.
If the `Auto` guess is not what you expect, you can choose a column for Part Number manually.


Q: Why do some columns end with an asterisk?

A: Part Number and Quantity columns are required to create a DigiKey myList. They are marked with an asterisk at the end.


Q: I don't find any part numbers after opening the addon.

A: Please make sure the schematic file does have some part numbers. Also try different columns for `Part Number`.
If this persists, it's a bug. Please consider reporting bugs ([guide](https://docs.github.com/en/issues/tracking-your-work-with-issues/creating-an-issue)).
We appreciate your time and effort.


Q: Is Python required to use the addon?

A: Yes. But because Python is usually bundled into KiCad installation files, you probably don't need to install Python separately.


Q: Why do I need to open PCB Editor (instead of Schematic Editor) to get parts in the schematic?

A: For now, only the PCB Editor provides an interface (`pcbnew`) for plugin development.

source:
- https://dev-docs.kicad.org/en/python/
- https://forum.kicad.info/t/writing-and-publishing-a-plugin/38830


Q: Can I add some note to a part number?

A: Yes. The last column - `Note` - is editable. Scroll the addon window all the way to the right to see this column. Double-click a row to edit, press Enter when you finish. `Note` will be sent to Digi-Key myLists as well.


Q: What is `Customer Reference` column for?

A: It's for Digi-Key customer with a reference number. This column is not required, so you can leave it blank.


Q: May I reuse and modify the code?

A: Yes, you can reuse and modify the code under [MIT license](https://github.com/Digi-Key/KiCad-Push-to-DigiKey/blob/master/LICENSE.md).


Q: How to build the addon from the source code?

A: We have a [section](#building-addon-from-source-code) for building the addon from the source code.

## Building addon from source code
To build the addon from source code, a separate installation of Python on your machine is recommended.

1. Install [Python](https://www.python.org/downloads/) if you don't have it yet. Using a [virtual environment](https://docs.python.org/3/library/venv.html) is recommended.
2. Download the source code
3. Make changes (optional)
4. Run `build` command

### Download the source code

1. Go to the source code page on [https://github.com/Digi-Key/KiCad-Push-to-DigiKey](https://github.com/Digi-Key/KiCad-Push-to-DigiKey)
2. Click the `Code` button

You can download the source code via git clone, GitHub CLI, as zip file, and other methods.

### Run `build` command
Go to the root directory of the source code, the directory should contain `pcm` and `src` directories.

```bash
python pcm/build.py
```

A .zip file will be created in `build/` directory. Use this file to install the addon in KiCad Plugin and Content Manager.

Note: Running this command will erase and recreate the `build/` directory.
Binary file added images/parts-pushed-todigikey-mylists.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/plugin-in-PCB-editor.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/plugin-installed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
68 changes: 68 additions & 0 deletions pcm/build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Thanks to gregdavill for this script,
# https://github.com/gregdavill/KiBuzzard/tree/main/pcm

import hashlib
import json
from pathlib import Path
import pathlib
import os
from os import path
import shutil

src_path = path.join(path.dirname(__file__), '..', 'src')

metadata_template = path.join(path.dirname(__file__), 'metadata_template.json')
resources_path = path.join(path.dirname(__file__), 'resources')

build_path = path.join('build')

try:
shutil.rmtree(build_path)
except FileNotFoundError:
pass
os.mkdir(build_path)
os.mkdir(path.join(build_path, 'plugin'))
os.chdir(build_path)

shutil.copytree(src_path, path.join('plugin', 'plugins'))

# clean out any __pycache__ or .pyc files
# (https://stackoverflow.com/a/41386937)
[p.unlink() for p in pathlib.Path('.').rglob('*.py[co]')]
[p.rmdir() for p in pathlib.Path('.').rglob('__pycache__')]


# copy metadata
shutil.copy(metadata_template, path.join('plugin', 'metadata.json'))
# copy icon
shutil.copytree(resources_path, path.join('plugin', 'resources'), ignore=shutil.ignore_patterns('.DS_Store'))

# load up json script
with open(metadata_template) as f:
md = json.load(f)


# zip all files
zip_file = 'PushToDigiKeyMyLists-{0}-pcm.zip'.format(md['versions'][0]['version'])
shutil.make_archive(Path(zip_file).stem, 'zip', 'plugin')


zip_size = path.getsize(zip_file)


uncompressed_size = sum(f.stat().st_size for f in Path(
'plugin').glob('**/*') if f.is_file())

with open(zip_file, 'rb') as f:
zip_sha256 = hashlib.sha256(f.read()).hexdigest()


md['versions'][0].update({
'install_size': uncompressed_size,
'download_size': zip_size,
'download_sha256': zip_sha256,
'download_url': 'https://example.com/{0}/PushForKiCad-{0}-pcm.zip'.format(md['versions'][0]['version'])
})

with open('metadata.json', 'w') as of:
json.dump(md, of, indent=2)
35 changes: 35 additions & 0 deletions pcm/metadata_template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"$schema": "https://go.kicad.org/pcm/schemas/v1",
"name": "Push to Digi-Key myLists",
"description": "Push components in the schematic to Digi-Key myLists for easy and quick part ordering.",
"description_full": "Push components in the schematic to Digi-Key myLists for easy and quick part ordering.",
"identifier": "internal.kicad.pushToDigiKeyMyLists",
"type": "plugin",
"author": {
"name": "Trung Ho",
"contact": {
"github": "https://www.digikey.com",
"web": "https://www.digikey.com",
"twitter": "https://www.digikey.com"
}
},
"maintainer": {
"name": "Trung Ho",
"contact": {
"github": "https://www.digikey.com",
"web": "https://www.digikey.com",
"twitter": "https://www.digikey.com"
}
},
"license": "MIT",
"resources": {
"homepage": "https://www.digikey.com"
},
"versions": [
{
"version": "0.0.6c4",
"status": "testing",
"kicad_version": "6.00"
}
]
}
Binary file added pcm/resources/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions src/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# __init__.py --> plugin.py

from .plugin import DigiKeyMyListsPlugin
plugin = DigiKeyMyListsPlugin()
plugin.register()
63 changes: 63 additions & 0 deletions src/ki_push_thread.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import json
import re
import requests
import time
import wx
from threading import Thread
from .ki_result_event import ResultEvent


class PushThread(Thread):
def __init__(self, wx_object, json_data, list_name):
Thread.__init__(self)
self.wx_object = wx_object
self.json_data = json_data
self.list_name = list_name
self.start()

def run(self):
base_api_url = 'https://www.digikey.com/mylists/api/thirdparty'
json_data = self.json_data
params = {'listName': self.list_name}

self._post_event({'state': 'Initializing...', 'gauge_int': 10})
time.sleep(0.5)

self._post_event({'state': 'Uploading your BOM...', 'gauge_int': 40})

r = None
try:
r = requests.post(base_api_url, json=json_data, params=params, verify=False)
except requests.exceptions.RequestException:
self._post_event({'state': 'ERR_REQUESTS_EXCEPTION', 'api_url': base_api_url})
except:
self._post_event({'state': 'ERR_SENDING_REQUEST', 'api_url': base_api_url})

self._post_event({'state': 'Preparing the webpage...', 'gauge_int': 70})
time.sleep(0.5)

print('\nStatus Code: ', r.status_code)
print('\nr.text data: ', r.text)

returned_short_url = ''
try:
returned_short_url = json.loads(r.text)
short_url_regex = r'^http.+digikey\.com/short/[0-9a-z]{7}'
if not re.match(short_url_regex, returned_short_url):
self._post_event({'state': 'SHORT_URL_NOT_RETURNED', 'r_text': returned_short_url})
return
except json.decoder.JSONDecodeError:
self._post_event({'state': 'SHORT_URL_NOT_RETURNED', 'r_text': returned_short_url})
return

self._post_event({'state': 'Done', 'gauge_int': 100})
time.sleep(0.5)

try:
wx.LaunchDefaultBrowser(returned_short_url)
except:
self._post_event({'state': 'CANNOT_LAUNCH_DEFAULT_BROWSER', 'url': returned_short_url})
self._post_event({'state': 'Finished'}) # keyword: "Finished", to close the wxForm.

def _post_event(self, event_data):
wx.PostEvent(self.wx_object, ResultEvent(event_data))
19 changes: 19 additions & 0 deletions src/ki_result_event.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import wx
# https://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/

EVT_RESULT_ID = wx.NewId()


def EVT_RESULT(win, func):
"""Define Result Event."""
win.Connect(-1, -1, EVT_RESULT_ID, func)


class ResultEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""

def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data
Loading

0 comments on commit e72fc56

Please sign in to comment.