traceforge-pcb 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. traceforge/__init__.py +3 -0
  2. traceforge/__main__.py +3 -0
  3. traceforge/acp_server.py +570 -0
  4. traceforge/agent.py +680 -0
  5. traceforge/altium/__init__.py +6 -0
  6. traceforge/altium/cfb.py +70 -0
  7. traceforge/altium/cli.py +60 -0
  8. traceforge/altium/model.py +163 -0
  9. traceforge/altium/outputs.py +24 -0
  10. traceforge/altium/pcb.py +301 -0
  11. traceforge/altium/project.py +328 -0
  12. traceforge/altium/schematic.py +400 -0
  13. traceforge/altium/tools.py +166 -0
  14. traceforge/approval.py +219 -0
  15. traceforge/attachments.py +346 -0
  16. traceforge/background.py +253 -0
  17. traceforge/bench/__init__.py +5 -0
  18. traceforge/bench/adapters.py +337 -0
  19. traceforge/bench/checks.py +410 -0
  20. traceforge/bench/cli.py +121 -0
  21. traceforge/bench/design.py +439 -0
  22. traceforge/bench/kicad.py +99 -0
  23. traceforge/bench/partscheck.py +159 -0
  24. traceforge/bench/review.py +100 -0
  25. traceforge/bench/runner.py +226 -0
  26. traceforge/bench/score.py +204 -0
  27. traceforge/bench/tasks.py +102 -0
  28. traceforge/chat.py +1185 -0
  29. traceforge/checks.py +328 -0
  30. traceforge/checks_sides.py +118 -0
  31. traceforge/cli.py +2224 -0
  32. traceforge/clipboard.py +107 -0
  33. traceforge/config.py +299 -0
  34. traceforge/context.py +276 -0
  35. traceforge/design/__init__.py +1 -0
  36. traceforge/design/constraints.py +397 -0
  37. traceforge/design/generate.py +1789 -0
  38. traceforge/design/outline.py +905 -0
  39. traceforge/design/schematic_layout.py +932 -0
  40. traceforge/design/schematic_lint.py +329 -0
  41. traceforge/design/schematic_route.py +207 -0
  42. traceforge/design/sheets.py +854 -0
  43. traceforge/design/sides.py +328 -0
  44. traceforge/design/spec.py +462 -0
  45. traceforge/design/specsheet.py +2351 -0
  46. traceforge/design/specsheet_render.py +183 -0
  47. traceforge/desktop/__init__.py +109 -0
  48. traceforge/desktop/keys.py +90 -0
  49. traceforge/desktop/project.py +443 -0
  50. traceforge/desktop/review.py +20 -0
  51. traceforge/desktop/server.py +1277 -0
  52. traceforge/desktop/static/app.css +223 -0
  53. traceforge/desktop/static/app.js +683 -0
  54. traceforge/desktop/static/highlight.js +77 -0
  55. traceforge/desktop/static/index.html +89 -0
  56. traceforge/desktop/static/md.js +90 -0
  57. traceforge/desktop/static/viewer.js +213 -0
  58. traceforge/desktop/symbols.py +212 -0
  59. traceforge/desktop/update.py +65 -0
  60. traceforge/diagnostics.py +67 -0
  61. traceforge/errata.py +219 -0
  62. traceforge/fab.py +108 -0
  63. traceforge/fab_layers.py +44 -0
  64. traceforge/features/__init__.py +6 -0
  65. traceforge/features/candidates.py +117 -0
  66. traceforge/features/cli.py +200 -0
  67. traceforge/features/package.py +433 -0
  68. traceforge/features/revdiff.py +224 -0
  69. traceforge/features/sarif.py +145 -0
  70. traceforge/features/viewer.py +265 -0
  71. traceforge/firmware/__init__.py +3 -0
  72. traceforge/firmware/cli.py +174 -0
  73. traceforge/firmware/drivers.py +372 -0
  74. traceforge/firmware/drivers_data.py +256 -0
  75. traceforge/firmware/mcus.py +177 -0
  76. traceforge/firmware/netlist.py +55 -0
  77. traceforge/firmware/pinmap.py +296 -0
  78. traceforge/firmware/scaffold.py +466 -0
  79. traceforge/firmware/toolchain.py +262 -0
  80. traceforge/hooks.py +237 -0
  81. traceforge/kicad/__init__.py +0 -0
  82. traceforge/kicad/cli.py +519 -0
  83. traceforge/kicad/diffpair.py +174 -0
  84. traceforge/kicad/edgegeom.py +191 -0
  85. traceforge/kicad/edit.py +405 -0
  86. traceforge/kicad/escape.py +1410 -0
  87. traceforge/kicad/formats.py +1073 -0
  88. traceforge/kicad/impedance.py +320 -0
  89. traceforge/kicad/install.py +75 -0
  90. traceforge/kicad/libraries.py +490 -0
  91. traceforge/kicad/models3d.py +942 -0
  92. traceforge/kicad/outputs.py +81 -0
  93. traceforge/kicad/pcb.py +787 -0
  94. traceforge/kicad/planes.py +1242 -0
  95. traceforge/kicad/project.py +136 -0
  96. traceforge/kicad/route.py +2698 -0
  97. traceforge/kicad/routegeom.py +164 -0
  98. traceforge/kicad/schematic.py +268 -0
  99. traceforge/kicad/sides.py +34 -0
  100. traceforge/kicad/stackup.py +424 -0
  101. traceforge/kicad_plugin/__init__.py +12 -0
  102. traceforge/kicad_plugin/actions.py +92 -0
  103. traceforge/kicad_plugin/cli.py +66 -0
  104. traceforge/kicad_plugin/client.py +86 -0
  105. traceforge/kicad_plugin/context.py +257 -0
  106. traceforge/kicad_plugin/discovery.py +81 -0
  107. traceforge/kicad_plugin/install.py +203 -0
  108. traceforge/kicad_plugin/overlay.py +60 -0
  109. traceforge/kicad_plugin/payload/action_plugin.py +65 -0
  110. traceforge/kicad_plugin/payload/ipc_main.py +42 -0
  111. traceforge/kicad_plugin/payload/plugin.json +90 -0
  112. traceforge/kicad_plugin/payload/requirements.txt +1 -0
  113. traceforge/kicad_plugin/views.py +202 -0
  114. traceforge/langchain.py +57 -0
  115. traceforge/local.py +580 -0
  116. traceforge/mcp_server.py +304 -0
  117. traceforge/models.py +310 -0
  118. traceforge/next_steps.py +110 -0
  119. traceforge/parts/__init__.py +52 -0
  120. traceforge/parts/alternates.py +488 -0
  121. traceforge/parts/bom.py +423 -0
  122. traceforge/parts/brief.py +705 -0
  123. traceforge/parts/catalog.py +297 -0
  124. traceforge/parts/cli_sourcing.py +156 -0
  125. traceforge/parts/data/duty_rates.yaml +37 -0
  126. traceforge/parts/data/hs_codes.yaml +103 -0
  127. traceforge/parts/datasheet.py +278 -0
  128. traceforge/parts/fx.py +100 -0
  129. traceforge/parts/model.py +185 -0
  130. traceforge/parts/net.py +187 -0
  131. traceforge/parts/offers.py +46 -0
  132. traceforge/parts/packages.py +397 -0
  133. traceforge/parts/pinout.py +714 -0
  134. traceforge/parts/providers/__init__.py +17 -0
  135. traceforge/parts/providers/base.py +100 -0
  136. traceforge/parts/providers/jlc.py +364 -0
  137. traceforge/parts/providers/keyed.py +661 -0
  138. traceforge/parts/report.py +508 -0
  139. traceforge/parts/supply.py +330 -0
  140. traceforge/parts/verify.py +455 -0
  141. traceforge/parts/web.py +575 -0
  142. traceforge/plans.py +70 -0
  143. traceforge/preferences.py +127 -0
  144. traceforge/prices.py +130 -0
  145. traceforge/prices.yaml +28 -0
  146. traceforge/prompts/__init__.py +54 -0
  147. traceforge/prompts/system.md +103 -0
  148. traceforge/providers.py +764 -0
  149. traceforge/remote/__init__.py +33 -0
  150. traceforge/remote/client.py +422 -0
  151. traceforge/remote/oidc.py +240 -0
  152. traceforge/remote/orgs.py +510 -0
  153. traceforge/remote/server.py +690 -0
  154. traceforge/remote/store.py +100 -0
  155. traceforge/review_changes.py +187 -0
  156. traceforge/routing.py +99 -0
  157. traceforge/runtime.py +435 -0
  158. traceforge/sessions.py +324 -0
  159. traceforge/sexpr.py +279 -0
  160. traceforge/sim/__init__.py +17 -0
  161. traceforge/sim/acmath.py +234 -0
  162. traceforge/sim/circuit.py +499 -0
  163. traceforge/sim/cli.py +162 -0
  164. traceforge/sim/engine.py +172 -0
  165. traceforge/sim/ltspice.py +175 -0
  166. traceforge/sim/measure.py +123 -0
  167. traceforge/sim/models.py +76 -0
  168. traceforge/sim/project.py +218 -0
  169. traceforge/sim/rawfile.py +123 -0
  170. traceforge/sim/results.py +298 -0
  171. traceforge/sim/tune.py +172 -0
  172. traceforge/skill_commands.py +165 -0
  173. traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
  174. traceforge/skill_library/compliance-review/SKILL.md +51 -0
  175. traceforge/skill_library/design-review/SKILL.md +47 -0
  176. traceforge/skill_library/errata-hunt/SKILL.md +30 -0
  177. traceforge/skill_library/firmware/SKILL.md +26 -0
  178. traceforge/skill_library/power-budget/SKILL.md +27 -0
  179. traceforge/skill_library/release-package/SKILL.md +29 -0
  180. traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
  181. traceforge/skill_library/thermal-review/SKILL.md +15 -0
  182. traceforge/skills.py +131 -0
  183. traceforge/thermal.py +557 -0
  184. traceforge/tools/__init__.py +48 -0
  185. traceforge/tools/agent_tools.py +213 -0
  186. traceforge/tools/base.py +303 -0
  187. traceforge/tools/batch.py +155 -0
  188. traceforge/tools/connections.py +245 -0
  189. traceforge/tools/files.py +777 -0
  190. traceforge/tools/firmware_tools.py +218 -0
  191. traceforge/tools/kicad_tools.py +1072 -0
  192. traceforge/tools/models3d_tools.py +141 -0
  193. traceforge/tools/parts_tools.py +473 -0
  194. traceforge/tools/processes.py +246 -0
  195. traceforge/tools/review_tools.py +178 -0
  196. traceforge/tools/sim_tools.py +230 -0
  197. traceforge/tui.py +620 -0
  198. traceforge/updates.py +124 -0
  199. traceforge/validate/__init__.py +77 -0
  200. traceforge/validate/builtins.py +1091 -0
  201. traceforge/validate/circuits.py +1240 -0
  202. traceforge/validate/config.py +410 -0
  203. traceforge/validate/default.yaml +113 -0
  204. traceforge/validate/design.py +191 -0
  205. traceforge/validate/explain.py +112 -0
  206. traceforge/validate/grounding.py +169 -0
  207. traceforge/validate/ipc2221.py +350 -0
  208. traceforge/validate/multilayer.py +805 -0
  209. traceforge/validate/netmodel.py +261 -0
  210. traceforge/validate/partcheck.py +472 -0
  211. traceforge/validate/report.py +280 -0
  212. traceforge/validate/review.py +322 -0
  213. traceforge/validate/runner.py +662 -0
  214. traceforge/workspace.py +171 -0
  215. traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
  216. traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
  217. traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
  218. traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
  219. traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,372 @@
1
+ """Generate C driver sources (init + read) for common parts from the register tables.
2
+
3
+ The code talks to the bus through a small HAL (``tf_hal.h``) that the project provides:
4
+ ``tf_i2c_write``/``tf_i2c_read``/``tf_delay_ms`` (and the GPIO calls for single-wire parts).
5
+ ``hal_arduino()`` returns an Arduino ``Wire`` implementation of it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import Any
12
+
13
+ from traceforge.firmware.drivers_data import PARTS
14
+
15
+ HAL_H = """\
16
+ /* HAL used by the generated drivers. Implement these for your platform. */
17
+ #ifndef TF_HAL_H
18
+ #define TF_HAL_H
19
+ #include <stddef.h>
20
+ #include <stdint.h>
21
+ #ifdef __cplusplus
22
+ extern "C" {
23
+ #endif
24
+ /* Return 0 on success, non-zero on a bus error. */
25
+ int tf_i2c_write(uint8_t addr, const uint8_t *data, size_t len);
26
+ int tf_i2c_read(uint8_t addr, uint8_t *data, size_t len);
27
+ void tf_delay_ms(uint32_t ms);
28
+ /* Single-wire parts (DHT11) */
29
+ void tf_delay_us(uint32_t us);
30
+ void tf_pin_output_low(int pin);
31
+ void tf_pin_release(int pin); /* input with pull-up */
32
+ int tf_pin_read(int pin);
33
+ #ifdef __cplusplus
34
+ }
35
+ #endif
36
+ #endif /* TF_HAL_H */
37
+ """
38
+
39
+
40
+ def hal_arduino() -> str:
41
+ return """\
42
+ // Arduino implementation of tf_hal.h (Wire for I2C).
43
+ #include <Arduino.h>
44
+ #include <Wire.h>
45
+ extern "C" {
46
+ #include "tf_hal.h"
47
+ }
48
+ extern "C" int tf_i2c_write(uint8_t addr, const uint8_t *data, size_t len) {
49
+ Wire.beginTransmission(addr);
50
+ Wire.write(data, len);
51
+ return Wire.endTransmission() == 0 ? 0 : 1;
52
+ }
53
+ extern "C" int tf_i2c_read(uint8_t addr, uint8_t *data, size_t len) {
54
+ if (Wire.requestFrom(addr, (uint8_t)len) != len) return 1;
55
+ for (size_t i = 0; i < len; i++) data[i] = Wire.read();
56
+ return 0;
57
+ }
58
+ extern "C" void tf_delay_ms(uint32_t ms) { delay(ms); }
59
+ extern "C" void tf_delay_us(uint32_t us) { delayMicroseconds(us); }
60
+ extern "C" void tf_pin_output_low(int pin) { pinMode(pin, OUTPUT); digitalWrite(pin, LOW); }
61
+ extern "C" void tf_pin_release(int pin) { pinMode(pin, INPUT_PULLUP); }
62
+ extern "C" int tf_pin_read(int pin) { return digitalRead(pin); }
63
+ """
64
+
65
+
66
+ def supported_parts() -> list[str]:
67
+ return sorted(PARTS)
68
+
69
+
70
+ def _lookup(part: str) -> tuple[str, dict[str, Any]]:
71
+ key = re.sub(r"[^A-Z0-9]", "", part.upper())
72
+ for name, data in PARTS.items():
73
+ if re.sub(r"[^A-Z0-9]", "", name) == key:
74
+ return name, data
75
+ raise KeyError(f"no driver for {part!r} (available: {', '.join(supported_parts())})")
76
+
77
+
78
+ def _hex(value: int, width: int = 2) -> str:
79
+ return f"0x{value:0{width}X}"
80
+
81
+
82
+ def generate_driver(part: str, address: int | None = None) -> dict[str, str]:
83
+ """Return {filename: text} (``<part>.h`` and ``<part>.c``) for a part."""
84
+ name, data = _lookup(part)
85
+ lower = name.lower()
86
+ addr = address if address is not None else data["address"]
87
+ builders = {
88
+ "regs": _regs,
89
+ "cmd": _cmd,
90
+ "oled": _oled,
91
+ "onewire": _onewire,
92
+ }
93
+ header, source = builders[data["kind"]](name, lower, data, addr)
94
+ return {f"{lower}.h": header, f"{lower}.c": source}
95
+
96
+
97
+ def _prologue(name: str, data: dict[str, Any], addr: int | None) -> list[str]:
98
+ lines = [f"/* {name} driver. Generated by traceforge firmware driver. */"]
99
+ lines.append(f"/* Datasheet: {data['datasheet']} */")
100
+ if addr is not None:
101
+ note = data.get("address_note", "")
102
+ lines.append(f"/* I2C address: {_hex(addr)} ({note}) */")
103
+ return lines
104
+
105
+
106
+ def _read_struct(name: str, read: dict[str, Any]) -> list[str]:
107
+ if read.get("raw_bytes"):
108
+ return []
109
+ lines = ["typedef struct {"]
110
+ for ctype, field, _ in read["fields"]:
111
+ lines.append(f" {ctype} {field};")
112
+ lines.append(f"}} {name.lower()}_{read['name']}_t;")
113
+ return lines
114
+
115
+
116
+ def _read_proto(name: str, read: dict[str, Any]) -> str:
117
+ lower = name.lower()
118
+ if read.get("raw_bytes"):
119
+ return f"int {lower}_read_{read['name']}(uint8_t out[{read['length']}]);"
120
+ return f"int {lower}_read_{read['name']}({lower}_{read['name']}_t *out);"
121
+
122
+
123
+ def _header(
124
+ name: str, data: dict[str, Any], addr: int | None, body: list[str], protos: list[str]
125
+ ) -> str:
126
+ lower = name.lower()
127
+ guard = f"{name.upper()}_H"
128
+ lines = _prologue(name, data, addr) + [
129
+ f"#ifndef {guard}",
130
+ f"#define {guard}",
131
+ "#include <stdint.h>",
132
+ "",
133
+ ]
134
+ if addr is not None:
135
+ lines.append(f"#define {name.upper()}_ADDR {_hex(addr)}")
136
+ lines += body + [""] + protos + ["", f"#endif /* {guard} */", ""]
137
+ del lower
138
+ return "\n".join(lines)
139
+
140
+
141
+ def _crc_fn() -> list[str]:
142
+ return [
143
+ "/* CRC-8, polynomial 0x31, init 0xFF (datasheet 4.12) */",
144
+ "static uint8_t crc8(const uint8_t *d, int n) {",
145
+ " uint8_t crc = 0xFF;",
146
+ " for (int i = 0; i < n; i++) {",
147
+ " crc ^= d[i];",
148
+ " for (int b = 0; b < 8; b++) crc = (crc & 0x80) ? (uint8_t)((crc << 1) ^ 0x31) : (uint8_t)(crc << 1);",
149
+ " }",
150
+ " return crc;",
151
+ "}",
152
+ "",
153
+ ]
154
+
155
+
156
+ def _regs(name: str, lower: str, data: dict[str, Any], addr: int):
157
+ up = name.upper()
158
+ body = []
159
+ for reg, value, doc in data["registers"]:
160
+ body.append(f"#define {up}_REG_{reg} {_hex(value)} /* {doc} */")
161
+ protos = [f"int {lower}_init(void);"]
162
+ structs = []
163
+ for read in data["reads"]:
164
+ structs += _read_struct(name, read) + [""]
165
+ protos.append(_read_proto(name, read))
166
+ for write in data.get("writes", []):
167
+ protos.append(f"int {lower}_{write['name']}(const uint8_t v[{write['length']}]);")
168
+ header = _header(name, data, addr, body + [""] + structs, protos)
169
+
170
+ src = _prologue(name, data, addr) + [f'#include "{lower}.h"', '#include "tf_hal.h"', ""]
171
+ src += [
172
+ "static int write_reg(uint8_t reg, uint8_t value) {",
173
+ " uint8_t buf[2] = {reg, value};",
174
+ f" return tf_i2c_write({up}_ADDR, buf, 2);",
175
+ "}",
176
+ "",
177
+ "static int read_regs(uint8_t reg, uint8_t *out, size_t len) {",
178
+ f" if (tf_i2c_write({up}_ADDR, &reg, 1)) return 1;",
179
+ f" return tf_i2c_read({up}_ADDR, out, len);",
180
+ "}",
181
+ "",
182
+ f"int {lower}_init(void) {{",
183
+ ]
184
+ if "check" in data:
185
+ reg, expect = data["check"]
186
+ src += [
187
+ " uint8_t id;",
188
+ f" if (read_regs({up}_REG_{reg}, &id, 1)) return 1;",
189
+ f" if (id != {_hex(expect)}) return 2; /* wrong chip id */",
190
+ ]
191
+ for reg, value, doc in data["init"]:
192
+ src.append(f" if (write_reg({up}_REG_{reg}, {_hex(value)})) return 1; /* {doc} */")
193
+ if data.get("init_delay_ms"):
194
+ src.append(f" tf_delay_ms({data['init_delay_ms']});")
195
+ src += [" return 0;", "}", ""]
196
+ for read in data["reads"]:
197
+ start = f"{up}_REG_{read['start']}"
198
+ if read.get("raw_bytes"):
199
+ src += [
200
+ f"/* {read['doc']} */",
201
+ f"int {lower}_read_{read['name']}(uint8_t out[{read['length']}]) {{",
202
+ f" return read_regs({start}, out, {read['length']});",
203
+ "}",
204
+ "",
205
+ ]
206
+ continue
207
+ src += [
208
+ f"/* {read['doc']} */",
209
+ f"int {lower}_read_{read['name']}({lower}_{read['name']}_t *out) {{",
210
+ f" uint8_t b[{read['length']}];",
211
+ f" if (read_regs({start}, b, {read['length']})) return 1;",
212
+ ]
213
+ for _ctype, field, expr in read["fields"]:
214
+ src.append(f" out->{field} = {expr};")
215
+ src += [" return 0;", "}", ""]
216
+ for write in data.get("writes", []):
217
+ n = write["length"]
218
+ src += [
219
+ f"/* {write['doc']} */",
220
+ f"int {lower}_{write['name']}(const uint8_t v[{n}]) {{",
221
+ f" uint8_t buf[{n + 1}];",
222
+ f" buf[0] = {up}_REG_{write['start']};",
223
+ f" for (int i = 0; i < {n}; i++) buf[i + 1] = v[i];",
224
+ f" return tf_i2c_write({up}_ADDR, buf, {n + 1}); /* address auto-increments (SEQOP=0) */",
225
+ "}",
226
+ "",
227
+ ]
228
+ return header, "\n".join(src)
229
+
230
+
231
+ def _cmd(name: str, lower: str, data: dict[str, Any], addr: int):
232
+ up = name.upper()
233
+ cmds = {c[0]: c for c in data["commands"]}
234
+ body = [f"#define {up}_CMD_{c} {_hex(v, 4)} /* {doc} */" for c, v, doc in data["commands"]]
235
+ protos = [f"int {lower}_init(void);"]
236
+ structs = []
237
+ for read in data["reads"]:
238
+ structs += _read_struct(name, read) + [""]
239
+ protos.append(_read_proto(name, read))
240
+ header = _header(name, data, addr, body + [""] + structs, protos)
241
+ src = _prologue(name, data, addr) + [f'#include "{lower}.h"', '#include "tf_hal.h"', ""]
242
+ src += _crc_fn()
243
+ src += [
244
+ "static int send_cmd(uint16_t cmd) {",
245
+ " uint8_t buf[2] = {(uint8_t)(cmd >> 8), (uint8_t)(cmd & 0xFF)};",
246
+ f" return tf_i2c_write({up}_ADDR, buf, 2);",
247
+ "}",
248
+ "",
249
+ f"int {lower}_init(void) {{",
250
+ ]
251
+ for cmd, _v, doc in data["init"]:
252
+ assert cmd in cmds
253
+ src.append(f" if (send_cmd({up}_CMD_{cmd})) return 1; /* {doc} */")
254
+ if data.get("init_delay_ms"):
255
+ src.append(f" tf_delay_ms({data['init_delay_ms']});")
256
+ src += [" return 0;", "}", ""]
257
+ for read in data["reads"]:
258
+ n = read["length"]
259
+ src += [
260
+ f"/* {read['doc']} */",
261
+ f"int {lower}_read_{read['name']}({lower}_{read['name']}_t *out) {{",
262
+ f" uint8_t b[{n}];",
263
+ f" if (send_cmd({up}_CMD_{read['command']})) return 1;",
264
+ f" tf_delay_ms({read['delay_ms']});",
265
+ f" if (tf_i2c_read({up}_ADDR, b, {n})) return 1;",
266
+ ]
267
+ for first, _second, crc in read.get("crc", []):
268
+ src.append(f" if (crc8(&b[{first}], 2) != b[{crc}]) return 3; /* CRC error */")
269
+ for _ctype, field, expr in read["fields"]:
270
+ src.append(f" out->{field} = {expr};")
271
+ src += [" return 0;", "}", ""]
272
+ return header, "\n".join(src)
273
+
274
+
275
+ def _oled(name: str, lower: str, data: dict[str, Any], addr: int):
276
+ up = name.upper()
277
+ w, h = data["width"], data["height"]
278
+ ctl = data["control"]
279
+ body = [
280
+ f"#define {up}_WIDTH {w}",
281
+ f"#define {up}_HEIGHT {h}",
282
+ f"#define {up}_CTRL_CMD {_hex(ctl['command'])} /* Co=0 D/C#=0 */",
283
+ f"#define {up}_CTRL_DATA {_hex(ctl['data'])} /* Co=0 D/C#=1 */",
284
+ ]
285
+ protos = [
286
+ f"int {lower}_init(void);",
287
+ f"/* Write a full framebuffer of {w * h // 8} bytes (page-major, 1 bit per pixel). */",
288
+ f"int {lower}_write_frame(const uint8_t fb[{w * h // 8}]);",
289
+ ]
290
+ header = _header(name, data, addr, body, protos)
291
+ src = _prologue(name, data, addr) + [f'#include "{lower}.h"', '#include "tf_hal.h"', ""]
292
+ src += [
293
+ "static int cmd(uint8_t c) {",
294
+ f" uint8_t buf[2] = {{{up}_CTRL_CMD, c}};",
295
+ f" return tf_i2c_write({up}_ADDR, buf, 2);",
296
+ "}",
297
+ "",
298
+ f"int {lower}_init(void) {{",
299
+ " tf_delay_ms(100); /* power-up (datasheet 8.9) */",
300
+ ]
301
+ for opcode, params, doc in data["init"]:
302
+ src.append(f" if (cmd({_hex(opcode)})) return 1; /* {doc} */")
303
+ for p in params:
304
+ src.append(f" if (cmd({_hex(p)})) return 1;")
305
+ src += [" return 0;", "}", ""]
306
+ src += [
307
+ f"int {lower}_write_frame(const uint8_t fb[{w * h // 8}]) {{",
308
+ " if (cmd(0x21) || cmd(0) || cmd(" + str(w - 1) + ")) return 1; /* column range */",
309
+ " if (cmd(0x22) || cmd(0) || cmd(" + str(h // 8 - 1) + ")) return 1; /* page range */",
310
+ " for (int i = 0; i < " + str(w * h // 8) + "; i += 16) {",
311
+ f" uint8_t buf[17] = {{{up}_CTRL_DATA}};",
312
+ " for (int j = 0; j < 16; j++) buf[j + 1] = fb[i + j];",
313
+ f" if (tf_i2c_write({up}_ADDR, buf, 17)) return 1;",
314
+ " }",
315
+ " return 0;",
316
+ "}",
317
+ "",
318
+ ]
319
+ return header, "\n".join(src)
320
+
321
+
322
+ def _onewire(name: str, lower: str, data: dict[str, Any], addr: None):
323
+ up = name.upper()
324
+ body = [
325
+ "typedef struct {",
326
+ " float temperature_c;",
327
+ " float humidity_pct;",
328
+ f"}} {lower}_reading_t;",
329
+ ]
330
+ protos = [
331
+ "/* pin: the data pin number used by tf_pin_* in tf_hal.h. Returns 0, 1 = no response,",
332
+ " 2 = timeout, 3 = checksum error. Call at most once per second. */",
333
+ f"int {lower}_read(int pin, {lower}_reading_t *out);",
334
+ ]
335
+ header = _header(name, data, None, body, protos)
336
+ src = _prologue(name, data, None) + [f'#include "{lower}.h"', '#include "tf_hal.h"', ""]
337
+ src += [
338
+ f"#define {up}_START_LOW_MS {data['start_low_ms']}",
339
+ f"#define {up}_BIT_THRESHOLD_US {data['bit_threshold_us']}",
340
+ "",
341
+ "/* wait until the pin equals level; return the time waited in us or -1 */",
342
+ "static int wait_level(int pin, int level, int max_us) {",
343
+ " for (int t = 0; t < max_us; t++) {",
344
+ " if (tf_pin_read(pin) == level) return t;",
345
+ " tf_delay_us(1);",
346
+ " }",
347
+ " return -1;",
348
+ "}",
349
+ "",
350
+ f"int {lower}_read(int pin, {lower}_reading_t *out) {{",
351
+ " uint8_t d[5] = {0, 0, 0, 0, 0};",
352
+ " tf_pin_output_low(pin);",
353
+ f" tf_delay_ms({up}_START_LOW_MS);",
354
+ " tf_pin_release(pin);",
355
+ " tf_delay_us(30);",
356
+ " if (wait_level(pin, 0, 100) < 0) return 1; /* response low 80 us */",
357
+ " if (wait_level(pin, 1, 120) < 0) return 2; /* response high 80 us */",
358
+ " if (wait_level(pin, 0, 120) < 0) return 2;",
359
+ " for (int i = 0; i < 40; i++) {",
360
+ " if (wait_level(pin, 1, 80) < 0) return 2; /* 50 us low gap */",
361
+ " int high = wait_level(pin, 0, 120); /* 26-28 us = 0, 70 us = 1 */",
362
+ " if (high < 0) return 2;",
363
+ f" d[i / 8] = (uint8_t)((d[i / 8] << 1) | (high > {up}_BIT_THRESHOLD_US ? 1 : 0));",
364
+ " }",
365
+ " if ((uint8_t)(d[0] + d[1] + d[2] + d[3]) != d[4]) return 3;",
366
+ " out->humidity_pct = (float)d[0] + (float)d[1] / 10.0f;",
367
+ " out->temperature_c = (float)d[2] + (float)d[3] / 10.0f;",
368
+ " return 0;",
369
+ "}",
370
+ "",
371
+ ]
372
+ return header, "\n".join(src)
@@ -0,0 +1,256 @@
1
+ """Register tables for common parts (data). Every entry cites the datasheet section.
2
+
3
+ Kinds (see drivers.py): ``regs`` = register-addressed I2C part with an init list and read
4
+ blocks; ``cmd`` = command-addressed I2C part (command write, then read); ``oled`` =
5
+ command/data-byte display; ``onewire`` = DHT-style single-wire timing protocol.
6
+ Addresses are 7-bit.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ PARTS: dict[str, dict[str, Any]] = {
14
+ "BME280": {
15
+ "kind": "regs",
16
+ "bus": "i2c",
17
+ "address": 0x76,
18
+ "address_note": "0x76 with SDO low, 0x77 with SDO high (datasheet 6.2 I2C interface)",
19
+ "datasheet": "Bosch BST-BME280-DS002, sections 5.3 (registers) and 4.2.3 (compensation)",
20
+ "registers": [
21
+ ("ID", 0xD0, "chip id, reads 0x60 (5.4.1)"),
22
+ ("RESET", 0xE0, "write 0xB6 to soft-reset (5.4.2)"),
23
+ ("CTRL_HUM", 0xF2, "humidity oversampling; write before CTRL_MEAS (5.4.3)"),
24
+ ("STATUS", 0xF3, "bit 3 measuring, bit 0 im_update (5.4.4)"),
25
+ ("CTRL_MEAS", 0xF4, "osrs_t[7:5] osrs_p[4:2] mode[1:0] (5.4.5)"),
26
+ ("CONFIG", 0xF5, "t_sb[7:5] filter[4:2] spi3w_en[0] (5.4.6)"),
27
+ ("PRESS_MSB", 0xF7, "press[19:12]; 8 bytes F7..FE = press, temp, hum (5.4.7-9)"),
28
+ ("CALIB00", 0x88, "dig_T1.. dig_H1 block, 26 bytes 0x88..0xA1 (4.2.2)"),
29
+ ("CALIB26", 0xE1, "dig_H2.. dig_H6 block, 7 bytes 0xE1..0xE7 (4.2.2)"),
30
+ ],
31
+ "check": ("ID", 0x60),
32
+ "init": [
33
+ ("RESET", 0xB6, "soft reset"),
34
+ ("CTRL_HUM", 0x01, "humidity x1"),
35
+ ("CONFIG", 0x00, "standby 0.5 ms, filter off"),
36
+ ("CTRL_MEAS", 0x27, "temp x1, pressure x1, normal mode"),
37
+ ],
38
+ "init_delay_ms": 10,
39
+ "reads": [
40
+ {
41
+ "name": "raw",
42
+ "doc": "raw 20-bit pressure/temperature and 16-bit humidity (needs the "
43
+ "calibration block and the datasheet 4.2.3 compensation formulas for units)",
44
+ "start": "PRESS_MSB",
45
+ "length": 8,
46
+ "fields": [
47
+ (
48
+ "uint32_t",
49
+ "press_raw",
50
+ "((uint32_t)b[0] << 12) | ((uint32_t)b[1] << 4) | (b[2] >> 4)",
51
+ ),
52
+ (
53
+ "uint32_t",
54
+ "temp_raw",
55
+ "((uint32_t)b[3] << 12) | ((uint32_t)b[4] << 4) | (b[5] >> 4)",
56
+ ),
57
+ ("uint16_t", "hum_raw", "((uint16_t)b[6] << 8) | b[7]"),
58
+ ],
59
+ },
60
+ {
61
+ "name": "calibration",
62
+ "doc": "calibration bytes 0x88..0xA1 (dig_T1.. in little endian pairs)",
63
+ "start": "CALIB00",
64
+ "length": 26,
65
+ "raw_bytes": True,
66
+ },
67
+ ],
68
+ },
69
+ "SHT31": {
70
+ "kind": "cmd",
71
+ "bus": "i2c",
72
+ "address": 0x44,
73
+ "address_note": "0x44 with ADDR low, 0x45 with ADDR high (datasheet 4.3)",
74
+ "datasheet": "Sensirion SHT3x-DIS datasheet, sections 4.3 (I2C address), 4.5 (commands), "
75
+ "4.12 (CRC-8 poly 0x31 init 0xFF), 4.13 (conversion)",
76
+ "commands": [
77
+ ("SOFT_RESET", 0x30A2, "soft reset (4.9)"),
78
+ ("MEAS_HIGHREP", 0x2400, "single shot, high repeatability, no clock stretching (4.5)"),
79
+ ("STATUS", 0xF32D, "read status register (4.10)"),
80
+ ],
81
+ "init": [("SOFT_RESET", None, "soft reset")],
82
+ "init_delay_ms": 2,
83
+ "reads": [
84
+ {
85
+ "name": "measurement",
86
+ "doc": "temperature in degC and relative humidity in percent",
87
+ "command": "MEAS_HIGHREP",
88
+ "delay_ms": 16,
89
+ "length": 6,
90
+ "crc": [(0, 1, 2), (3, 4, 5)],
91
+ "fields": [
92
+ (
93
+ "float",
94
+ "temperature_c",
95
+ "-45.0f + 175.0f * (float)(((uint16_t)b[0] << 8) | b[1]) / 65535.0f",
96
+ ),
97
+ (
98
+ "float",
99
+ "humidity_pct",
100
+ "100.0f * (float)(((uint16_t)b[3] << 8) | b[4]) / 65535.0f",
101
+ ),
102
+ ],
103
+ }
104
+ ],
105
+ },
106
+ "MCP23017": {
107
+ "kind": "regs",
108
+ "bus": "i2c",
109
+ "address": 0x20,
110
+ "address_note": "0x20 + A2:A0 straps, 0x20..0x27 (datasheet 3.3.1, Figure 1-1)",
111
+ "datasheet": "Microchip MCP23017 datasheet DS20001952, Table 3-3 (register map, IOCON.BANK=0)",
112
+ "registers": [
113
+ ("IODIRA", 0x00, "port A direction, 1 = input (default 0xFF)"),
114
+ ("IODIRB", 0x01, "port B direction"),
115
+ ("IPOLA", 0x02, "port A input polarity"),
116
+ ("GPPUA", 0x0C, "port A pull-up enable"),
117
+ ("GPPUB", 0x0D, "port B pull-up enable"),
118
+ ("IOCON", 0x0A, "configuration (BANK, MIRROR, SEQOP, ODR, INTPOL)"),
119
+ ("GPIOA", 0x12, "port A pins; read returns the pin levels"),
120
+ ("GPIOB", 0x13, "port B pins"),
121
+ ("OLATA", 0x14, "port A output latch"),
122
+ ("OLATB", 0x15, "port B output latch"),
123
+ ],
124
+ "init": [
125
+ ("IODIRA", 0xFF, "port A all inputs"),
126
+ ("IODIRB", 0xFF, "port B all inputs"),
127
+ ("GPPUA", 0x00, "no pull-ups on A"),
128
+ ("GPPUB", 0x00, "no pull-ups on B"),
129
+ ],
130
+ "reads": [
131
+ {
132
+ "name": "gpio",
133
+ "doc": "both ports: bits 0-7 = GPIOA, bits 8-15 = GPIOB",
134
+ "start": "GPIOA",
135
+ "length": 2,
136
+ "fields": [("uint16_t", "pins", "((uint16_t)b[1] << 8) | b[0]")],
137
+ }
138
+ ],
139
+ "writes": [
140
+ {
141
+ "name": "set_output",
142
+ "doc": "drive output latches (A low byte, B high byte)",
143
+ "start": "OLATA",
144
+ "length": 2,
145
+ },
146
+ ],
147
+ },
148
+ "PCF85063A": {
149
+ "kind": "regs",
150
+ "bus": "i2c",
151
+ "address": 0x51,
152
+ "address_note": "fixed 0x51 (datasheet 8.1 I2C interface, 7-bit)",
153
+ "datasheet": "NXP PCF85063A datasheet, Table 4 (register overview, 0x00..0x11) and "
154
+ "section 8.4 (time and date, BCD)",
155
+ "registers": [
156
+ ("CONTROL_1", 0x00, "EXT_TEST, STOP bit 5, SR, CIE, 12_24, CAP_SEL (Table 5)"),
157
+ ("CONTROL_2", 0x01, "AIE, AF, MI, HMI, TF, COF (Table 8)"),
158
+ ("OFFSET", 0x02, "offset register"),
159
+ ("SECONDS", 0x04, "bit 7 OS = oscillator stop, bits 6:0 BCD seconds (Table 15)"),
160
+ ("MINUTES", 0x05, "BCD minutes"),
161
+ ("HOURS", 0x06, "BCD hours, 24 h mode"),
162
+ ("DAYS", 0x07, "BCD day of month"),
163
+ ("WEEKDAYS", 0x08, "weekday 0-6"),
164
+ ("MONTHS", 0x09, "BCD month"),
165
+ ("YEARS", 0x0A, "BCD year 00-99"),
166
+ ],
167
+ "init": [("CONTROL_1", 0x00, "clock running, 24 h mode, normal operation")],
168
+ "reads": [
169
+ {
170
+ "name": "time",
171
+ "doc": "date and time (year 2000 + yy); sets osc_stopped if the time is invalid",
172
+ "start": "SECONDS",
173
+ "length": 7,
174
+ "fields": [
175
+ ("uint8_t", "second", "(uint8_t)(((b[0] >> 4) & 0x7) * 10 + (b[0] & 0xF))"),
176
+ ("uint8_t", "minute", "(uint8_t)(((b[1] >> 4) & 0x7) * 10 + (b[1] & 0xF))"),
177
+ ("uint8_t", "hour", "(uint8_t)(((b[2] >> 4) & 0x3) * 10 + (b[2] & 0xF))"),
178
+ ("uint8_t", "day", "(uint8_t)(((b[3] >> 4) & 0x3) * 10 + (b[3] & 0xF))"),
179
+ ("uint8_t", "weekday", "(uint8_t)(b[4] & 0x7)"),
180
+ ("uint8_t", "month", "(uint8_t)(((b[5] >> 4) & 0x1) * 10 + (b[5] & 0xF))"),
181
+ ("uint16_t", "year", "(uint16_t)(2000 + (b[6] >> 4) * 10 + (b[6] & 0xF))"),
182
+ ("uint8_t", "osc_stopped", "(uint8_t)(b[0] >> 7)"),
183
+ ],
184
+ }
185
+ ],
186
+ },
187
+ "LM75": {
188
+ "kind": "regs",
189
+ "bus": "i2c",
190
+ "address": 0x48,
191
+ "address_note": "0x48 + A2:A0 straps, 0x48..0x4F (datasheet 'Slave address')",
192
+ "datasheet": "NXP LM75B datasheet, section 7.4 (register map: Temp 0x00, Conf 0x01, "
193
+ "Thyst 0x02, Tos 0x03) and 7.4.3 (11-bit temperature, 0.125 degC/LSB)",
194
+ "registers": [
195
+ ("TEMP", 0x00, "temperature, 11 bits left-justified in 16, 0.125 degC/LSB"),
196
+ ("CONF", 0x01, "bit 0 SHUTDOWN, bit 1 OS comparator/interrupt, bit 2 OS polarity"),
197
+ ("THYST", 0x02, "hysteresis, 9 bits, 0.5 degC/LSB"),
198
+ ("TOS", 0x03, "over-temperature shutdown threshold, 9 bits"),
199
+ ],
200
+ "init": [("CONF", 0x00, "normal operation, comparator mode")],
201
+ "reads": [
202
+ {
203
+ "name": "temperature",
204
+ "doc": "temperature in degC",
205
+ "start": "TEMP",
206
+ "length": 2,
207
+ "fields": [
208
+ (
209
+ "float",
210
+ "temperature_c",
211
+ "(float)((int16_t)(((uint16_t)b[0] << 8) | b[1]) >> 5) * 0.125f",
212
+ ),
213
+ ],
214
+ }
215
+ ],
216
+ },
217
+ "SSD1306": {
218
+ "kind": "oled",
219
+ "bus": "i2c",
220
+ "address": 0x3C,
221
+ "address_note": "0x3C with D/C# (SA0) low, 0x3D with SA0 high (datasheet 8.1.5.1)",
222
+ "datasheet": "Solomon Systech SSD1306 datasheet, section 8.1.5.1 (I2C control byte: "
223
+ "Co, D/C#) and section 9 (command table)",
224
+ "control": {"command": 0x00, "data": 0x40},
225
+ "width": 128,
226
+ "height": 64,
227
+ "init": [
228
+ (0xAE, [], "display off (9.1.7)"),
229
+ (0xD5, [0x80], "clock divide / oscillator (9.1.8)"),
230
+ (0xA8, [0x3F], "multiplex ratio 64 (9.1.6)"),
231
+ (0xD3, [0x00], "display offset 0 (9.1.5)"),
232
+ (0x40, [], "start line 0 (9.1.4)"),
233
+ (0x8D, [0x14], "charge pump on (2.1 of the application note)"),
234
+ (0x20, [0x00], "horizontal addressing mode (9.1.3)"),
235
+ (0xA1, [], "segment remap (9.1.1)"),
236
+ (0xC8, [], "COM scan direction remapped"),
237
+ (0xDA, [0x12], "COM pins configuration"),
238
+ (0x81, [0xCF], "contrast"),
239
+ (0xD9, [0xF1], "pre-charge period"),
240
+ (0xDB, [0x40], "VCOMH deselect level"),
241
+ (0xA4, [], "resume from RAM content"),
242
+ (0xA6, [], "normal (non-inverted) display"),
243
+ (0xAF, [], "display on"),
244
+ ],
245
+ },
246
+ "DHT11": {
247
+ "kind": "onewire",
248
+ "bus": "gpio",
249
+ "address": None,
250
+ "datasheet": "Aosong DHT11 datasheet, sections 5 (communication process: 18 ms start "
251
+ "low, 20-40 us release, 80 us response, bit = 26-28 us high for 0 / 70 us for 1) and "
252
+ "5.2 (40-bit frame: RH int, RH dec, T int, T dec, checksum)",
253
+ "start_low_ms": 18,
254
+ "bit_threshold_us": 40,
255
+ },
256
+ }