-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVibeCoderArduino-Ai.py
More file actions
1966 lines (1733 loc) · 86.9 KB
/
VibeCoderArduino-Ai.py
File metadata and controls
1966 lines (1733 loc) · 86.9 KB
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
#!/usr/bin/env python3
"""
VibeCoder v6.1 — Universal AI Hardware Agent
=============================================
Cross-platform: Linux, Windows, macOS
Auto-updating board database from GitHub
Usage:
Linux/macOS : python3 vibecoder.py
Windows : python vibecoder.py
"""
import os, sys, json, time, re, subprocess, requests, webbrowser, platform
# ── Platform Detection ────────────────────────────────────────────────────────
IS_WINDOWS = platform.system() == "Windows"
IS_MAC = platform.system() == "Darwin"
IS_LINUX = platform.system() == "Linux"
# ── Paths ─────────────────────────────────────────────────────────────────────
HOME = os.path.expanduser("~")
SKETCH_DIR = os.path.join(HOME, "vibe_sketch")
DIAGRAM_FILE = os.path.join(HOME, "wiring_diagram.html")
CONFIG_FILE = os.path.join(HOME, ".vibecoder_config.json")
AVR_BAUDS = [57600, 115200, 38400, 19200, 9600]
# ── Online board database ─────────────────────────────────────────────────────
BOARDS_DB_URL = "https://raw.githubusercontent.com/orfeastops/vibecoder/main/boards.json"
BOARDS_DB_FILE = os.path.join(HOME, ".vibecoder_boards.json")
BOARDS_DB_TTL = 86400 # Re-download every 24 hours
# Project history
HISTORY_DIR = os.path.join(HOME, ".vibecoder_history")
HISTORY_INDEX = os.path.join(HISTORY_DIR, "index.json")
# ── AI Backend Configuration ──────────────────────────────────────────────────
AI_BACKENDS = {
"groq": {
"name": "Groq (free, ~150 tokens/sec)",
"url": "https://api.groq.com/openai/v1/chat/completions",
"model": "llama-3.3-70b-versatile",
"models": ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "mixtral-8x7b-32768"],
"key_url": "https://console.groq.com/keys",
"free": True,
"needs_key": True,
},
"openrouter": {
"name": "OpenRouter (free tier available)",
"url": "https://openrouter.ai/api/v1/chat/completions",
"model": "qwen/qwen-2.5-coder-32b-instruct:free",
"models": ["qwen/qwen-2.5-coder-32b-instruct:free",
"google/gemini-2.0-flash-exp:free",
"meta-llama/llama-3.3-70b-instruct:free"],
"key_url": "https://openrouter.ai/keys",
"free": True,
"needs_key": True,
},
"anthropic": {
"name": "Anthropic Claude (paid, best quality)",
"url": "https://api.anthropic.com/v1/messages",
"model": "claude-haiku-4-5",
"models": ["claude-haiku-4-5", "claude-sonnet-4-5"],
"key_url": "https://console.anthropic.com/",
"free": False,
"needs_key": True,
},
"openai": {
"name": "OpenAI (paid)",
"url": "https://api.openai.com/v1/chat/completions",
"model": "gpt-4o-mini",
"models": ["gpt-4o-mini", "gpt-4o", "gpt-3.5-turbo"],
"key_url": "https://platform.openai.com/api-keys",
"free": False,
"needs_key": True,
},
"mistral": {
"name": "Mistral AI (free, 1B tokens/month)",
"url": "https://api.mistral.ai/v1/chat/completions",
"model": "mistral-small-latest",
"models": ["mistral-small-latest", "open-mistral-7b"],
"key_url": "https://console.mistral.ai/",
"free": True,
"needs_key": True,
},
"ollama": {
"name": "Ollama (local, offline, no internet needed)",
"url": "http://localhost:11434/api/chat",
"model": "qwen2.5-coder:3b",
"models": ["qwen2.5-coder:7b", "qwen2.5-coder:3b", "llama3:8b"],
"key_url": "",
"free": True,
"needs_key": False,
},
"custom": {
"name": "Custom API (DeepSeek, Together, Cohere, any OpenAI-compatible)",
"url": "",
"model": "",
"models": [],
"key_url": "",
"free": None,
"needs_key": True,
},
}
KNOWN_CUSTOM_APIS = {
"deepseek": ("https://api.deepseek.com/v1/chat/completions", "deepseek-coder", "https://platform.deepseek.com"),
"together": ("https://api.together.xyz/v1/chat/completions", "Qwen/Qwen2.5-Coder-32B-Instruct", "https://api.together.ai"),
"cohere": ("https://api.cohere.ai/v1/chat", "command-r-plus", "https://dashboard.cohere.com"),
"fireworks": ("https://api.fireworks.ai/inference/v1/chat/completions","accounts/fireworks/models/qwen2p5-coder-32b-instruct", "https://fireworks.ai"),
"nvidia": ("https://integrate.api.nvidia.com/v1/chat/completions", "qwen/qwen2.5-coder-32b-instruct", "https://build.nvidia.com"),
"ollama": ("http://localhost:11434/v1/chat/completions", "qwen2.5-coder:7b", "local"),
}
AI_CFG: dict = {}
# ── Smart input with arrow keys, history ─────────────────────────────────────
try:
from prompt_toolkit import prompt as _pt_prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.styles import Style
_pt_style = Style.from_dict({"prompt": "ansigreen bold"})
_pt_history = InMemoryHistory()
_HAS_PT = True
except ImportError:
_HAS_PT = False
try:
import readline
readline.parse_and_bind("tab: complete")
except ImportError:
pass
def smart_input(prompt_text: str) -> str:
if _HAS_PT:
try:
return _pt_prompt(prompt_text, history=_pt_history,
auto_suggest=AutoSuggestFromHistory(),
style=_pt_style).strip()
except (KeyboardInterrupt, EOFError):
raise
except Exception:
pass
return input(prompt_text).strip()
# ══════════════════════════════════════════════════════════════════════════════
# SECTION 0 - AI Backend Setup
# ══════════════════════════════════════════════════════════════════════════════
def _save_config(cfg: dict):
with open(CONFIG_FILE, "w") as f:
json.dump(cfg, f, indent=2)
def _load_config() -> dict:
try:
with open(CONFIG_FILE) as f:
return json.load(f)
except Exception:
return {}
def setup_ai_backend(force: bool = False) -> dict:
saved = _load_config()
if saved.get("backend") and not force:
b = saved["backend"]
info = AI_BACKENDS.get(b, {})
print(f" AI Backend : {info.get('name', b)}")
print(f" Model : {saved.get('model','?')}")
return saved
print("\n" + "="*60)
print(" VibeCoder - AI Backend Setup")
print("="*60)
print("\nChoose your AI backend:")
print("(Recommended: Groq — free, fast, no credit card needed)\n")
backends = list(AI_BACKENDS.items())
for i, (key, info) in enumerate(backends, 1):
free_tag = "FREE" if info["free"] else "paid"
print(f" {i}. {info['name']} [{free_tag}]")
print()
while True:
pick = smart_input("Your choice (1-5): ")
if pick.isdigit() and 1 <= int(pick) <= len(backends):
backend_key, backend_info = backends[int(pick)-1]
break
print(" Enter a number 1-5.")
cfg = {"backend": backend_key, "model": backend_info["model"], "api_key": ""}
if backend_key == "custom":
print("\n Known providers (or enter your own):")
known = list(KNOWN_CUSTOM_APIS.items())
for i, (name, (url, model, key_url)) in enumerate(known, 1):
print(f" {i}. {name:<12} {url[:45]}")
print(f" {len(known)+1}. Enter custom URL manually")
pick = smart_input(" Choose provider (Enter for manual): ").strip()
if pick.isdigit() and 1 <= int(pick) <= len(known):
pname, (url, model, key_url) = known[int(pick)-1]
cfg["url"] = url
cfg["model"] = model
print(f"\n API key for {pname}: {key_url}")
elif pick.isdigit() and int(pick) == len(known)+1 or not pick:
cfg["url"] = smart_input(" API endpoint URL: ").strip()
cfg["model"] = smart_input(" Model name: ").strip()
key_url = ""
else:
hits = [(n,v) for n,v in known if pick.lower() in n.lower()]
if hits:
pname, (url, model, key_url) = hits[0]
cfg["url"] = url
cfg["model"] = model
print(f" Selected: {pname}")
else:
cfg["url"] = smart_input(" API endpoint URL: ").strip()
cfg["model"] = smart_input(" Model name: ").strip()
override = smart_input(f" Model [{cfg['model']}] (Enter to keep): ").strip()
if override:
cfg["model"] = override
key = smart_input(" API key (Enter to skip): ").strip()
cfg["api_key"] = key
cfg["api_format"] = "anthropic" if "anthropic.com" in cfg.get("url","") else "openai"
_save_config(cfg)
print(f"\n Saved! Custom API: {cfg['url']}")
print(f" Model: {cfg['model']}\n")
return cfg
if backend_info["needs_key"]:
if backend_info.get("key_url"):
print(f"\n Get API key at: {backend_info['key_url']}")
key = smart_input(" Paste your API key (Enter to skip): ").strip()
if key:
cfg["api_key"] = key
elif backend_key != "ollama":
print(" ⚠️ No API key entered.")
print(" You can add it later by typing 'setup' inside VibeCoder.")
print(" Without a key, this backend will not work.")
models = backend_info["models"]
if len(models) > 1:
print("\n Available models:")
for i, m in enumerate(models, 1):
tag = " <- recommended" if i == 1 else ""
print(f" {i}. {m}{tag}")
pick = smart_input(" Choose model (Enter for default): ").strip()
if pick.isdigit() and 1 <= int(pick) <= len(models):
cfg["model"] = models[int(pick)-1]
_save_config(cfg)
print(f"\n Saved! Backend: {AI_BACKENDS[cfg['backend']]['name']}")
print(f" Model: {cfg['model']}\n")
return cfg
def ai_ask(messages: list, timeout: int = 300) -> str | None:
backend = AI_CFG.get("backend", "groq")
model = AI_CFG.get("model", "qwen2.5-coder:3b")
key = AI_CFG.get("api_key", "")
info = AI_BACKENDS.get(backend, list(AI_BACKENDS.values())[0])
if backend == "custom":
url = AI_CFG.get("url", "")
api_format = AI_CFG.get("api_format", "openai")
else:
url = info["url"]
api_format = "anthropic" if backend == "anthropic" else \
"ollama" if backend == "ollama" else "openai"
try:
if api_format == "anthropic":
system = next((m["content"] for m in messages if m["role"]=="system"), "")
msgs = [m for m in messages if m["role"] != "system"]
resp = requests.post(url,
headers={"x-api-key":key,"anthropic-version":"2023-06-01",
"content-type":"application/json"},
json={"model":model,"max_tokens":2048,"temperature":0.2,"system":system,"messages":msgs},
timeout=timeout)
resp.raise_for_status()
return resp.json()["content"][0]["text"]
elif api_format == "ollama":
resp = requests.post(url,
json={"model":model,"messages":messages,"stream":False},
timeout=timeout)
resp.raise_for_status()
return resp.json()["message"]["content"]
else:
headers = {"Authorization":f"Bearer {key}","Content-Type":"application/json"}
if backend == "openrouter":
headers["HTTP-Referer"] = "https://github.com/vibecoder"
headers["X-Title"] = "VibeCoder"
resp = requests.post(url, headers=headers,
json={"model":model,"messages":messages,
"max_tokens":2048,"temperature":0.2},
timeout=timeout)
resp.raise_for_status()
return resp.json()["choices"][0]["message"]["content"]
except requests.exceptions.ConnectionError:
if backend == "ollama":
print("\n Cannot reach Ollama.")
print(" Make sure Ollama is running: ollama serve")
print(" Or switch to a cloud API: type 'setup'")
else:
print(f"\n Cannot reach {info['name']}. Check internet connection.")
print(" Type 'setup' to switch to a different backend.")
except requests.exceptions.Timeout:
if backend == "ollama":
print("\n Timeout. Ollama is slow on CPU.")
print(" Try a smaller model: ollama pull qwen2.5-coder:3b")
print(" Or switch to a fast free API: type 'setup' → choose Groq")
else:
print("\n Timeout. Check your internet connection.")
print(" Type 'setup' to switch to a different backend.")
except requests.exceptions.HTTPError as e:
code = e.response.status_code if e.response else 0
if code == 401: print("\n Invalid API key. Type 'setup' to update.")
elif code == 429: print("\n Rate limit hit. Wait or type 'setup' to switch.")
else: print(f"\n HTTP {code}: {e}")
except Exception as e:
print(f"\n AI error: {e}")
return None
# ══════════════════════════════════════════════════════════════════════════════
# SECTION 1 — Board Database (Online + Local Fallback)
# ══════════════════════════════════════════════════════════════════════════════
_DB: dict = {}
def _load_builtin_db() -> dict:
return {
"_meta": {"version": "builtin"},
"usb_fingerprints": [
{"vid":"1a86","pid":"7523","chip":"ch34","fqbn":"arduino:avr:uno", "name":"Arduino Uno (CH340)", "upload_speed":57600, "upload_method":"avrdude"},
{"vid":"1a86","pid":"7523","chip":"ch34","fqbn":"arduino:avr:nano", "name":"Arduino Nano (CH340)", "upload_speed":57600, "upload_method":"avrdude"},
{"vid":"1a86","pid":"7523","chip":"ch34","fqbn":"esp8266:esp8266:nodemcuv2", "name":"NodeMCU ESP8266 (CH340)", "upload_speed":921600, "upload_method":"esptool"},
{"vid":"1a86","pid":"7523","chip":"ch34","fqbn":"esp32:esp32:esp32", "name":"ESP32 DevKit (CH340)", "upload_speed":921600, "upload_method":"esptool"},
{"vid":"1a86","pid":"55d4","chip":"ch910","fqbn":"esp32:esp32:esp32", "name":"ESP32 DevKit (CH9102)", "upload_speed":921600, "upload_method":"esptool"},
{"vid":"10c4","pid":"ea60","chip":"cp210","fqbn":"esp8266:esp8266:nodemcuv2","name":"NodeMCU ESP8266 (CP2102)", "upload_speed":921600, "upload_method":"esptool"},
{"vid":"10c4","pid":"ea60","chip":"cp210","fqbn":"esp32:esp32:esp32", "name":"ESP32 DevKit (CP2102)", "upload_speed":921600, "upload_method":"esptool"},
{"vid":"0403","pid":"6001","chip":"ftdi", "fqbn":"arduino:avr:uno", "name":"Arduino Uno (FTDI)", "upload_speed":115200, "upload_method":"avrdude"},
{"vid":"2341","pid":"0043","chip":"", "fqbn":"arduino:avr:uno", "name":"Arduino Uno R3", "upload_speed":115200, "upload_method":"avrdude"},
{"vid":"2341","pid":"0036","chip":"", "fqbn":"arduino:avr:nano", "name":"Arduino Nano", "upload_speed":57600, "upload_method":"avrdude"},
{"vid":"2341","pid":"0010","chip":"", "fqbn":"arduino:avr:mega2560", "name":"Arduino Mega 2560", "upload_speed":115200, "upload_method":"avrdude"},
{"vid":"2e8a","pid":"0003","chip":"", "fqbn":"rp2040:rp2040:rpipico", "name":"Raspberry Pi Pico", "upload_speed":None, "upload_method":"uf2"},
{"vid":"2e8a","pid":"000a","chip":"", "fqbn":"rp2040:rp2040:rpipicow", "name":"Raspberry Pi Pico W", "upload_speed":None, "upload_method":"uf2"},
],
"pin_rules": {},
"manual_selection_boards": [
{"fqbn":"arduino:avr:uno", "name":"Arduino Uno", "upload_speed":115200, "upload_method":"avrdude"},
{"fqbn":"arduino:avr:nano", "name":"Arduino Nano", "upload_speed":57600, "upload_method":"avrdude"},
{"fqbn":"arduino:avr:mega2560", "name":"Arduino Mega 2560", "upload_speed":115200, "upload_method":"avrdude"},
{"fqbn":"esp8266:esp8266:nodemcuv2", "name":"NodeMCU ESP8266", "upload_speed":921600, "upload_method":"esptool"},
{"fqbn":"esp32:esp32:esp32", "name":"ESP32 DevKit", "upload_speed":921600, "upload_method":"esptool"},
{"fqbn":"rp2040:rp2040:rpipico", "name":"Raspberry Pi Pico", "upload_speed":None, "upload_method":"uf2"},
]
}
def load_db() -> dict:
global _DB
if os.path.exists(BOARDS_DB_FILE):
age = time.time() - os.path.getmtime(BOARDS_DB_FILE)
if age < BOARDS_DB_TTL:
try:
with open(BOARDS_DB_FILE) as f:
_DB = json.load(f)
v = _DB.get("_meta",{}).get("version","?")
print(f" 📋 Board database v{v} (cached)")
return _DB
except Exception:
pass
try:
print(" 🌐 Checking for board database updates...")
resp = requests.get(BOARDS_DB_URL, timeout=10)
if resp.status_code == 200:
_DB = resp.json()
with open(BOARDS_DB_FILE, "w") as f:
json.dump(_DB, f, indent=2)
v = _DB.get("_meta",{}).get("version","?")
print(f" ✅ Board database v{v} updated from GitHub")
return _DB
except Exception:
pass
if os.path.exists(BOARDS_DB_FILE):
try:
with open(BOARDS_DB_FILE) as f:
_DB = json.load(f)
print(f" 📋 Board database loaded (offline mode)")
return _DB
except Exception:
pass
print(" 📋 Using built-in board database (offline)")
_DB = _load_builtin_db()
return _DB
def get_pin_rules(fqbn: str, board_name: str = "") -> dict:
rules_db = _DB.get("pin_rules", {})
for key, rules in rules_db.items():
if key in fqbn or fqbn in key:
norm = {}
for pin, val in rules.get("reserved", {}).items():
if isinstance(val, list) and len(val) >= 2:
norm[pin] = (val[0], val[1])
else:
norm[pin] = (str(val), "")
r = dict(rules)
r["reserved"] = norm
return r
if fqbn in _pin_rules_cache:
return _pin_rules_cache[fqbn]
print(f" 🤖 Fetching pin rules for {board_name or fqbn}...")
try:
text = ai_ask([{"role":"user","content":(
f"For {board_name} (FQBN: {fqbn}), list reserved/unsafe GPIO pins "
"that must not be used for external components, and safe pins. "
'Reply ONLY with JSON: {"reserved":{"PIN":["reason","alternative"]},'
'"safe":["pin1",...],"analog":["pin1",...],"note":"voltage/current info","code_fixes":{}}'
)}], timeout=60)
if not text: raise ValueError("no response")
s, e = text.find("{"), text.rfind("}") + 1
data = json.loads(text[s:e])
norm = {}
for pin, val in data.get("reserved", {}).items():
if isinstance(val, list) and len(val) >= 2:
norm[pin] = (val[0], val[1])
else:
norm[pin] = (str(val), data.get("safe",[""])[0])
data["reserved"] = norm
data.setdefault("code_fixes", {})
_pin_rules_cache[fqbn] = data
print(f" ✅ Got pin rules for {board_name or fqbn}")
return data
except Exception:
return {"reserved":{}, "safe":[], "analog":[], "note":"", "code_fixes":{}}
_pin_rules_cache: dict = {}
# ══════════════════════════════════════════════════════════════════════════════
# SECTION 2 — Cross-Platform Port Detection
# ══════════════════════════════════════════════════════════════════════════════
def list_serial_ports() -> list[str]:
if IS_WINDOWS:
try:
from serial.tools import list_ports
return [p.device for p in list_ports.comports()]
except ImportError:
ports = []
for i in range(1, 20):
port = f"COM{i}"
try:
import serial
s = serial.Serial(port)
s.close()
ports.append(port)
except Exception:
pass
return ports
elif IS_MAC:
import glob
return (glob.glob("/dev/tty.usbserial*") +
glob.glob("/dev/tty.usbmodem*") +
glob.glob("/dev/cu.usbserial*"))
else:
ports = []
for p in [f"/dev/ttyUSB{i}" for i in range(8)] + \
[f"/dev/ttyACM{i}" for i in range(8)]:
if os.path.exists(p):
ports.append(p)
return ports
def _usb_ids(port: str) -> tuple:
if IS_WINDOWS:
try:
from serial.tools import list_ports
for p in list_ports.comports():
if p.device == port and p.vid and p.pid:
return (f"{p.vid:04x}", f"{p.pid:04x}")
except Exception:
pass
return ("", "")
elif IS_MAC:
try:
r = subprocess.run(["system_profiler","SPUSBDataType"],
capture_output=True, text=True, timeout=5)
vid = pid = ""
for line in r.stdout.splitlines():
if "Vendor ID:" in line:
vid = line.split("0x")[-1].strip()[:4].lower()
if "Product ID:" in line:
pid = line.split("0x")[-1].strip()[:4].lower()
return (vid, pid)
except Exception:
return ("", "")
else:
try:
name = os.path.basename(port)
path = os.path.realpath(f"/sys/class/tty/{name}/device")
for _ in range(6):
path = os.path.dirname(path)
v = os.path.join(path, "idVendor")
if os.path.exists(v):
return (open(v).read().strip().lower(),
open(os.path.join(path,"idProduct")).read().strip().lower())
except Exception:
pass
return ("", "")
def _chip_from_dmesg(port: str) -> str:
if not IS_LINUX: return ""
try:
name = os.path.basename(port)
out = subprocess.run(["dmesg"], capture_output=True, text=True, timeout=5).stdout
for line in reversed(out.splitlines()):
if name in line:
for kw in ("ch341","ch340","ch9102","cp210","ftdi","cdc_acm","rp2040"):
if kw in line.lower():
return kw
except Exception:
pass
return ""
def _ensure_serial_permissions(port: str):
if not IS_LINUX: return
try:
import grp, pwd
dialout = grp.getgrnam("dialout")
user = pwd.getpwuid(os.getuid()).pw_name
if user not in dialout.gr_mem and os.environ.get("VIBECODER_REEXEC") != "1":
print(f" 🔑 Adding {user} to dialout group...")
subprocess.run(["sudo","usermod","-aG","dialout",user], capture_output=True)
os.environ["VIBECODER_REEXEC"] = "1"
os.execvpe("sg", ["sg","dialout","-c",
f"python3 {' '.join(sys.argv)}"], os.environ)
except Exception:
pass
def _fingerprint(port: str) -> list[dict]:
vid, pid = _usb_ids(port)
chip = _chip_from_dmesg(port)
print(f" 🔬 USB {vid or '?'}:{pid or '?'} chip: {chip or 'unknown'}")
matches, seen = [], set()
for row in _DB.get("usb_fingerprints", []):
score = 0
if vid and pid and vid == row["vid"] and pid == row["pid"]: score += 10
elif vid and vid == row["vid"]: score += 4
if row.get("chip") and chip and row["chip"] in chip: score += 3
if score >= 3 and row["fqbn"] not in seen:
seen.add(row["fqbn"])
matches.append({**row, "score": score})
return sorted(matches, key=lambda x: -x["score"])
def _manual_select(port: str, candidates: list[dict]) -> dict:
manual = _DB.get("manual_selection_boards", [])
seen, options = set(), []
for o in candidates + manual:
if o["fqbn"] not in seen:
seen.add(o["fqbn"])
options.append(o)
print(f"\n Select your board (number or type to search):")
for i, o in enumerate(options, 1):
print(f" {i:2}. {o['name']}")
while True:
pick = smart_input(" Your choice: ").lower()
if pick.isdigit() and 1 <= int(pick) <= len(options):
chosen = options[int(pick)-1]
print(f" ✔ {chosen['name']}")
return chosen
hits = [o for o in options
if pick in o["name"].lower() or pick in o["fqbn"].lower()]
if len(hits) == 1:
print(f" ✔ {hits[0]['name']}")
return hits[0]
elif len(hits) > 1:
print(" Multiple matches:")
for i, h in enumerate(hits, 1):
print(f" {i}. {h['name']}")
else:
if "raspberry" in pick and "pico" not in pick:
print(" ℹ️ The standard Raspberry Pi runs Linux and cannot be")
print(" programmed with Arduino. Did you mean 'Raspberry Pi Pico'?")
else:
print(f" No match for '{pick}'. Try a number or different keyword.")
def detect_board() -> dict:
print("\n🔍 Scanning for connected boards...")
try:
r = subprocess.run(
["arduino-cli","board","list","--format","json"],
capture_output=True, text=True, timeout=10)
if r.returncode == 0 and r.stdout.strip():
data = json.loads(r.stdout)
entries = data.get("detected_ports", data) if isinstance(data,dict) else data
if not isinstance(entries, list): entries = []
for entry in entries:
p = entry.get("port",{})
port = p.get("address","") if isinstance(p,dict) else str(p)
if not port: continue
boards = entry.get("matching_boards", entry.get("boards",[]))
if boards and boards[0].get("fqbn","") not in ("","unknown"):
fqbn = boards[0]["fqbn"]
name = boards[0].get("name", fqbn)
print(f" ✅ Identified: {name}")
for row in _DB.get("usb_fingerprints",[]):
if row["fqbn"] == fqbn:
return {"port":port,"fqbn":fqbn,"name":name,
"upload_speed":row["upload_speed"],
"upload_method":row["upload_method"]}
return {"port":port,"fqbn":fqbn,"name":name,
"upload_speed":None,"upload_method":"arduino-cli"}
elif port:
print(f" 🔍 Port {port} found, fingerprinting...")
candidates = _fingerprint(port)
if len(candidates) == 1:
c = candidates[0]; c["port"] = port
print(f" ✅ Identified: {c['name']}")
return c
print(f" ⚠️ Multiple boards match this USB chip.")
chosen = _manual_select(port, candidates)
chosen["port"] = port
return chosen
except Exception:
pass
ports = list_serial_ports()
if ports:
port = ports[0]
candidates = _fingerprint(port)
if len(candidates) == 1:
c = candidates[0]; c["port"] = port
print(f" ✅ Identified: {c['name']}")
return c
if candidates:
print(f" ⚠️ Multiple boards match.")
chosen = _manual_select(port, candidates)
chosen["port"] = port
return chosen
print(" ⚠️ No board found. Make sure it's plugged in.")
chosen = _manual_select("unknown", [])
chosen["port"] = None
return chosen
# ══════════════════════════════════════════════════════════════════════════════
# SECTION 3 — Core Installation
# ══════════════════════════════════════════════════════════════════════════════
def ensure_core(fqbn: str):
parts = fqbn.split(":")
if len(parts) < 2: return
platform_id = f"{parts[0]}:{parts[1]}"
r = subprocess.run(["arduino-cli","core","list"], capture_output=True, text=True)
if platform_id in r.stdout: return
print(f"\n📦 Installing core '{platform_id}' (first time only)...")
url = _DB.get("_meta",{}).get("board_manager_urls",{}).get(parts[0])
if url:
subprocess.run(["arduino-cli","config","init","--overwrite"], capture_output=True)
subprocess.run(["arduino-cli","config","add",
"board_manager.additional_urls", url], capture_output=True)
subprocess.run(["arduino-cli","core","update-index"], capture_output=True)
r = subprocess.run(["arduino-cli","core","install", platform_id])
print(f" {'✅' if r.returncode==0 else '⚠️ '} Core '{platform_id}' "
f"{'installed' if r.returncode==0 else 'install may have failed'}.\n")
# ══════════════════════════════════════════════════════════════════════════════
# SECTION 4 — AI Code Generation
# ══════════════════════════════════════════════════════════════════════════════
class AIAgent:
def __init__(self, board: dict):
self.board = board
self.messages = [{"role":"system","content": self._build_prompt()}]
def _build_prompt(self) -> str:
fqbn = self.board["fqbn"]
name = self.board["name"]
rules = get_pin_rules(fqbn, name)
safe_pins = ", ".join(rules.get("safe",[])[:15]) or "standard GPIO pins"
reserved_text = "\n".join(
f" - {pin}: {reason} → use {alt} instead"
for pin, (reason, alt) in rules.get("reserved",{}).items()
) or " None"
if "esp8266" in fqbn:
naming = "D-prefix: D1, D2, D5, D6, D7 (NOT GPIO numbers)"
elif "esp32" in fqbn:
naming = "GPIO numbers: GPIO4, GPIO5, GPIO13..."
elif "avr" in fqbn:
naming = "Plain integers: 2, 3, 13 (NOT D2, D13)"
elif "rp2040" in fqbn:
naming = "GP prefix: GP0, GP1, GP2..."
else:
naming = "Labels as printed on the board silkscreen"
return f"""You are an expert embedded engineer programming the {name} ({fqbn}).
## OUTPUT FORMAT — always follow exactly:
1. Complete Arduino C++ sketch in ```cpp ... ``` block.
No placeholders, no TODOs — fully working code only.
2. Wiring table:
WIRING_START
Component | Component Pin | Board Label | Notes
LED | Anode (+) | D1 | Through 220Ω resistor
WIRING_END
## PIN NAMING for {name}:
{naming}
## SAFE PINS (use these):
{safe_pins}
## RESERVED PINS — NEVER use for components:
{reserved_text}
## BOARD NOTE:
{rules.get('note','')}
## RULES:
- Use ONLY safe pins
- {'Use #include <ESP8266WiFi.h>' if 'esp8266' in fqbn else 'Use #include <WiFi.h>' if 'esp32' in fqbn else 'No WiFi on this board'}
- 2 sentence explanation max — code and wiring table are the priority
"""
def ask(self, prompt: str) -> str | None:
self.messages.append({"role":"user","content":prompt})
text = ai_ask(self.messages)
if text:
self.messages.append({"role":"assistant","content":text})
return text
# ══════════════════════════════════════════════════════════════════════════════
# SECTION 5 — Code Sanitization
# ══════════════════════════════════════════════════════════════════════════════
def extract_code(text: str) -> str:
for marker in ("```cpp","```arduino","```c","```"):
if marker in text:
return text.split(marker)[1].split("```")[0].strip()
return text.strip()
def sanitize_code(code: str, board: dict) -> str:
fqbn = board["fqbn"]
rules = get_pin_rules(fqbn, board.get("name",""))
for wrong, correct in rules.get("code_fixes",{}).items():
code = code.replace(wrong, correct)
for h in ["#include <WiFi.h>","#include <ESP8266WiFi.h>"]:
if h in code and "WiFi." not in code.replace(h,""):
code = code.replace(h, "")
if "avr" in fqbn:
code = re.sub(r'\bD(\d+)\b', r'\1', code)
if "esp32" in fqbn and "esp8266" not in fqbn:
code = re.sub(r'\bD(\d+)\b', r'\1', code)
for bad_pin, (reason, good_pin) in rules.get("reserved",{}).items():
fp = rf'((?:digitalWrite|digitalRead|pinMode|analogWrite|analogRead)\s*\(\s*){re.escape(bad_pin)}(\s*[,)])'
ap = rf'((?:=|#define\s+\w+)\s*){re.escape(bad_pin)}\b'
if re.search(fp, code) or re.search(ap, code):
print(f"\n ⚠️ WARNING: Pin {bad_pin} is reserved!")
print(f" Reason : {reason}")
print(f" Safe alternative: {good_pin}")
print(f" Risk : May cause boot issues or programming failures")
choice = smart_input(f" Replace {bad_pin} → {good_pin}? [Y/n]: ").lower()
if choice != "n":
code = re.sub(fp, rf'\g<1>{good_pin}\2', code)
code = re.sub(ap, rf'\g<1>{good_pin}', code)
print(f" ✅ Replaced {bad_pin} → {good_pin}")
else:
print(f" ⚡ Keeping {bad_pin} — proceed with caution.")
write_pins = re.findall(r'digitalWrite\s*\(\s*(\w+)\s*,', code)
read_pins = re.findall(r'digitalRead\s*\(\s*(\w+)\s*\)', code)
all_pins = list(dict.fromkeys(write_pins + read_pins))
setup_m = re.search(r'void\s+setup\s*\(\s*\)\s*\{([^}]*)\}', code, re.DOTALL)
if setup_m and all_pins:
body, adds = setup_m.group(1), []
for pin in all_pins:
if f"pinMode({pin}" not in body:
d = "OUTPUT" if pin in write_pins else "INPUT"
adds.append(f" pinMode({pin}, {d});")
if adds:
nb = body.rstrip() + "\n" + "\n".join(adds) + "\n"
code = code[:setup_m.start(1)] + nb + code[setup_m.end(1):]
return code
# ══════════════════════════════════════════════════════════════════════════════
# SECTION 6 — Compile with AI Auto-Fix
# ══════════════════════════════════════════════════════════════════════════════
def auto_install_libraries(code: str):
includes = re.findall(r'#include\s*[<"]([^>"]+)[>"]', code)
builtin = {
"Arduino.h","Wire.h","SPI.h","EEPROM.h","Servo.h",
"SoftwareSerial.h","LiquidCrystal.h","SD.h","Stepper.h",
"WiFi.h","WiFiClient.h","WiFiServer.h","WebServer.h",
"ESP8266WiFi.h","ESP8266WebServer.h","HTTPClient.h",
"BluetoothSerial.h","BLEDevice.h","Preferences.h",
"FS.h","SPIFFS.h","LittleFS.h","Update.h",
"math.h","string.h","stdlib.h","stdio.h",
}
lib_map = {
"DHT.h": "DHT sensor library",
"DHT_U.h": "DHT sensor library",
"Adafruit_Sensor.h": "Adafruit Unified Sensor",
"Adafruit_BMP280.h": "Adafruit BMP280 Library",
"Adafruit_BME280.h": "Adafruit BME280 Library",
"Adafruit_MPU6050.h": "Adafruit MPU6050",
"Adafruit_GFX.h": "Adafruit GFX Library",
"Adafruit_SSD1306.h": "Adafruit SSD1306",
"Adafruit_ILI9341.h": "Adafruit ILI9341",
"Adafruit_NeoPixel.h":"Adafruit NeoPixel",
"LiquidCrystal_I2C.h":"LiquidCrystal I2C",
"FastLED.h": "FastLED",
"IRremote.h": "IRremote",
"IRremoteESP8266.h": "IRremote",
"PubSubClient.h": "PubSubClient",
"ArduinoJson.h": "ArduinoJson",
"RTClib.h": "RTClib",
"OneWire.h": "OneWire",
"DallasTemperature.h":"DallasTemperature",
"Ultrasonic.h": "Ultrasonic",
"NewPing.h": "NewPing",
"Keypad.h": "Keypad",
"TM1637Display.h": "TM1637",
"MAX30105.h": "SparkFun MAX3010x Pulse and Proximity Sensor Library",
"MPU6050.h": "MPU6050",
"HX711.h": "HX711",
"Stepper.h": "Stepper",
"AccelStepper.h": "AccelStepper",
"ESP32Servo.h": "ESP32Servo",
"ESPAsyncWebServer.h":"ESPAsyncWebServer-esphome",
"AsyncTCP.h": "AsyncTCP",
"MQTT.h": "MQTT",
"Ticker.h": "Ticker",
}
to_install = []
for inc in includes:
if inc in builtin: continue
lib_name = lib_map.get(inc)
if lib_name:
to_install.append((inc, lib_name))
if not to_install:
return
print(f"\n 📚 Found {len(to_install)} library/ies to install:")
for inc, lib in to_install:
print(f" {inc} → {lib}")
r = subprocess.run(["arduino-cli","lib","list"],
capture_output=True, text=True)
installed = r.stdout.lower()
for inc, lib in to_install:
if lib.lower() in installed:
print(f" ✅ {lib} already installed")
continue
print(f" 📦 Installing {lib}...", end="", flush=True)
r = subprocess.run(
["arduino-cli","lib","install", lib],
capture_output=True, text=True
)
if r.returncode == 0:
print(" ✅")
else:
search = subprocess.run(
["arduino-cli","lib","search", inc.replace(".h",""),"--format","json"],
capture_output=True, text=True
)
try:
results = json.loads(search.stdout)
libs = results.get("libraries", results) if isinstance(results,dict) else results
if libs:
best = libs[0].get("name","") if isinstance(libs[0],dict) else ""
if best:
r2 = subprocess.run(
["arduino-cli","lib","install", best],
capture_output=True, text=True
)
print(f" {'✅' if r2.returncode==0 else '⚠️ failed'}")
else:
print(" ⚠️ not found")
else:
print(" ⚠️ not found in registry")
except Exception:
print(" ⚠️ install failed")
def compile_sketch(fqbn: str) -> tuple:
build_dir = os.path.join(SKETCH_DIR, "build")
os.makedirs(build_dir, exist_ok=True)
r = subprocess.run(
["arduino-cli","compile","--fqbn",fqbn,"--output-dir",build_dir, SKETCH_DIR],
capture_output=True, text=True)
return r.returncode == 0, r.stderr + r.stdout
def compile_with_autofix(code: str, board: dict) -> bool:
fqbn = board["fqbn"]
hints = {
"esp8266": "Use #include <ESP8266WiFi.h>, D-prefix pins (D1,D2,D5,D6,D7), 3.3V.",
"esp32": "Use #include <WiFi.h>, GPIO numbers, 3.3V.",
"avr": "Plain pin numbers (13 not D13), 5V logic.",
"rp2040": "GP prefix (GP0,GP1...), 3.3V, Arduino-Pico framework.",
}
hint = next((v for k,v in hints.items() if k in fqbn), f"Board: {board['name']}")
current = code
auto_install_libraries(current)
for attempt in range(3):
os.makedirs(SKETCH_DIR, exist_ok=True)
sketch_file = os.path.join(SKETCH_DIR, os.path.basename(SKETCH_DIR)+".ino")
with open(sketch_file,"w") as f: f.write(current)
ok, output = compile_sketch(fqbn)
for line in output.splitlines():
if any(k in line for k in ("Sketch uses","Global variables","error:","warning:")):
print(f" {line.strip()}")
if ok:
if attempt > 0: print(f" ✅ Fixed on attempt {attempt+1}")
return True
errors = [l.strip() for l in output.splitlines() if "error:" in l.lower()][:6]
if not errors: break
print(f" 🔧 [{attempt+1}/3] AI fixing {len(errors)} error(s)...")
try:
fixed = ai_ask([{"role":"user","content":(
f"Fix this Arduino code for {board['name']} ({fqbn}).\n"
f"Errors:\n" + "\n".join(errors) +
f"\nRules: {hint}\n"
f"Code:\n```cpp\n{current}\n```\n"
"Return ONLY fixed code in ```cpp block."
)}], timeout=120)
fixed = extract_code(fixed) if fixed else None
if fixed and fixed != current: current = fixed
else: break
except Exception: break
print("❌ Compilation failed after all attempts.")
return False
# ══════════════════════════════════════════════════════════════════════════════
# SECTION 7 — Universal Upload
# ══════════════════════════════════════════════════════════════════════════════
def _dtr_reset(port: str):
try:
import serial
with serial.Serial(port, 115200, timeout=0.5) as s:
s.dtr = False; time.sleep(0.1)
s.dtr = True; time.sleep(0.1)
s.dtr = False; time.sleep(0.25)
except Exception:
if IS_LINUX:
try:
subprocess.run(["stty","-F",port,"hupcl"], capture_output=True)
time.sleep(0.3)
except Exception: pass
def _find_file(root: str, exts: list, exclude: list=[]) -> str:
for r, _, files in os.walk(root):
for f in sorted(files):
if any(f.endswith(e) for e in exts):
if not any(x in f.lower() for x in exclude):
return os.path.join(r, f)
return ""
def _find_avrdude() -> tuple:
roots = [os.path.join(HOME,".arduino15","packages","arduino","tools","avrdude")]
if IS_LINUX:
roots.append("/root/.arduino15/packages/arduino/tools/avrdude")
avrdude = conf = ""
for base in roots: