forked from Bouni/kicad-jlcpcb-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
partdetails.py
245 lines (221 loc) · 9.26 KB
/
partdetails.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
"""Contains the part details modal dialog."""
import io
import logging
import webbrowser
import requests # pylint: disable=import-error
import wx # pylint: disable=import-error
from .helpers import HighResWxSize, loadBitmapScaled
class PartDetailsDialog(wx.Dialog):
"""The part details dialog class."""
def __init__(self, parent, part):
wx.Dialog.__init__(
self,
parent,
id=wx.ID_ANY,
title="JLCPCB Part Details",
pos=wx.DefaultPosition,
size=HighResWxSize(parent.window, wx.Size(1000, 800)),
style=wx.DEFAULT_DIALOG_STYLE | wx.STAY_ON_TOP,
)
self.logger = logging.getLogger(__name__)
self.parent = parent
self.part = part
self.pdfurl = None
self.picture = None
# ---------------------------------------------------------------------
# ---------------------------- Hotkeys --------------------------------
# ---------------------------------------------------------------------
quitid = wx.NewId()
self.Bind(wx.EVT_MENU, self.quit_dialog, id=quitid)
entries = [wx.AcceleratorEntry(), wx.AcceleratorEntry(), wx.AcceleratorEntry()]
entries[0].Set(wx.ACCEL_CTRL, ord("W"), quitid)
entries[1].Set(wx.ACCEL_CTRL, ord("Q"), quitid)
entries[2].Set(wx.ACCEL_SHIFT, wx.WXK_ESCAPE, quitid)
accel = wx.AcceleratorTable(entries)
self.SetAcceleratorTable(accel)
# ---------------------------------------------------------------------
# ----------------------- Properties List -----------------------------
# ---------------------------------------------------------------------
self.data_list = wx.dataview.DataViewListCtrl(
self,
wx.ID_ANY,
wx.DefaultPosition,
wx.DefaultSize,
style=wx.dataview.DV_SINGLE,
)
self.property = self.data_list.AppendTextColumn(
"Property",
mode=wx.dataview.DATAVIEW_CELL_INERT,
width=int(self.parent.scale_factor * 200),
align=wx.ALIGN_LEFT,
)
self.value = self.data_list.AppendTextColumn(
"Value",
mode=wx.dataview.DATAVIEW_CELL_INERT,
width=int(self.parent.scale_factor * 300),
align=wx.ALIGN_LEFT,
)
# ---------------------------------------------------------------------
# ------------------------- Right side ------------------------------
# ---------------------------------------------------------------------
self.image = wx.StaticBitmap(
self,
wx.ID_ANY,
loadBitmapScaled("placeholder.png", self.parent.scale_factor, static=True),
wx.DefaultPosition,
HighResWxSize(parent.window, wx.Size(200, 200)),
0,
)
self.openpdf_button = wx.Button(
self,
wx.ID_ANY,
"Open Datasheet",
wx.DefaultPosition,
wx.DefaultSize,
0,
)
self.openpdf_button.Bind(wx.EVT_BUTTON, self.openpdf)
self.openpdf_button.SetBitmap(
loadBitmapScaled(
"mdi-file-document-outline.png",
self.parent.scale_factor,
)
)
self.openpdf_button.SetBitmapMargins((2, 0))
# ---------------------------------------------------------------------
# ------------------------ Layout and Sizers --------------------------
# ---------------------------------------------------------------------
right_side_layout = wx.BoxSizer(wx.VERTICAL)
right_side_layout.Add(self.image, 10, wx.ALL | wx.EXPAND, 5)
right_side_layout.AddStretchSpacer(50)
right_side_layout.Add(self.openpdf_button, 5, wx.LEFT | wx.RIGHT | wx.EXPAND, 5)
layout = wx.BoxSizer(wx.HORIZONTAL)
layout.Add(self.data_list, 30, wx.ALL | wx.EXPAND, 5)
layout.Add(right_side_layout, 10, wx.ALL | wx.EXPAND, 5)
self.SetSizer(layout)
self.Layout()
self.Centre(wx.BOTH)
self.get_part_data()
def quit_dialog(self, *_):
"""Close the dialog."""
self.Destroy()
self.EndModal(0)
def openpdf(self, *_):
"""Open the linked datasheet PDF on button click."""
self.logger.info("opening %s", str(self.pdfurl))
webbrowser.open(self.pdfurl)
def get_scaled_bitmap(self, url, width, height):
"""Download a picture from a URL and convert it into a wx Bitmap."""
content = requests.get(url, timeout=10).content
io_bytes = io.BytesIO(content)
image = wx.Image(io_bytes)
image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)
result = wx.Bitmap(image)
return result
def get_part_data(self):
"""Fetch part data from JLCPCB API and parse it into the table, set picture and PDF link."""
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36",
}
r = requests.get(
f"https://cart.jlcpcb.com/shoppingCart/smtGood/getComponentDetail?componentCode={self.part}",
headers=headers,
timeout=10,
)
if r.status_code != requests.codes.ok: # pylint: disable=no-member
self.report_part_data_fetch_error("non-OK HTTP response status")
data = r.json()
if not data.get("data"):
self.report_part_data_fetch_error(
"returned JSON data does not have expected 'data' attribute"
)
parameters = {
"componentCode": "Component code",
"firstTypeNameEn": "Primary category",
"secondTypeNameEn": "Secondary category",
"componentBrandEn": "Brand",
"componentName": "Full name",
"componentDesignator": "Designator",
"componentModelEn": "Model",
"componentSpecificationEn": "Specification",
"describe": "Description",
"matchedPartDetail": "Details",
"stockCount": "Stock",
"leastNumber": "Minimal Quantity",
"leastNumberPrice": "Minimum price",
}
parttype = data.get("data", {}).get("componentLibraryType")
if parttype and parttype == "base":
self.data_list.AppendItem(["Type", "Basic"])
elif parttype and parttype == "expand":
self.data_list.AppendItem(["Type", "Extended"])
for k, v in parameters.items():
val = data.get("data", {}).get(k)
if val:
self.data_list.AppendItem([v, str(val)])
prices = data.get("data", {}).get("jlcPrices", [])
if prices:
for price in prices:
start = price.get("startNumber")
end = price.get("endNumber")
if end == -1:
self.data_list.AppendItem(
[
f"JLC Price for >{start}",
str(price.get("productPrice")),
]
)
else:
self.data_list.AppendItem(
[
f"JLC Price for {start}-{end}",
str(price.get("productPrice")),
]
)
prices = data.get("data", {}).get("prices", [])
if prices:
for price in prices:
start = price.get("startNumber")
end = price.get("endNumber")
if end == -1:
self.data_list.AppendItem(
[
f"LCSC Price for >{start}",
str(price.get("productPrice")),
]
)
else:
self.data_list.AppendItem(
[
f"LCSC Price for {start}-{end}",
str(price.get("productPrice")),
]
)
for attribute in data.get("data", {}).get("attributes", []):
self.data_list.AppendItem(
[
attribute.get("attribute_name_en"),
str(attribute.get("attribute_value_name")),
]
)
picture = data.get("data", {}).get("minImage")
if picture:
# get the full resolution image instead of the thumbnail
picture = picture.replace("96x96", "900x900")
self.image.SetBitmap(
self.get_scaled_bitmap(
picture,
int(200 * self.parent.scale_factor),
int(200 * self.parent.scale_factor),
)
)
self.pdfurl = data.get("data", {}).get("dataManualUrl")
def report_part_data_fetch_error(self, reason):
"""Spawn a message box with an erro message if the fetch fails."""
wx.MessageBox(
f"Failed to download part detail from the JLCPCB API ({reason})\r\n"
f"We looked for a part named:\r\n{self.part}\r\n[hint: did you fill in the LCSC field correctly?]",
"Error",
style=wx.ICON_ERROR,
)
self.EndModal(-1)