99 "regexp"
1010 "slices"
1111 "strings"
12+ "sync"
1213
1314 "github.com/arduino/arduino-cli/commands"
1415 "github.com/arduino/arduino-cli/pkg/fqbn"
@@ -41,7 +42,16 @@ const (
4142 SerialPath = "/sys/devices/soc0/serial_number"
4243)
4344
45+ // Cache the initialized Arduino CLI service, so it don't need to be re-initialized
46+ // TODO: provide a way to get the board information by event instead of polling.
47+ var arduinoCLIServer rpc.ArduinoCoreServiceServer
48+ var arduinoCLIInstance * rpc.Instance
49+ var arduinoCLILock sync.Mutex
50+
4451func FromFQBN (ctx context.Context , fqbn string ) ([]Board , error ) {
52+ arduinoCLILock .Lock ()
53+ defer arduinoCLILock .Unlock ()
54+
4555 if micro .OnBoard {
4656 var customName string
4757 if name , err := GetCustomName (ctx , & local.LocalConnection {}); err == nil {
@@ -60,29 +70,34 @@ func FromFQBN(ctx context.Context, fqbn string) ([]Board, error) {
6070 }}, nil
6171 }
6272
63- logrus .SetLevel (logrus .ErrorLevel ) // Reduce the log level of arduino-cli
64- srv := commands .NewArduinoCoreServer ()
65-
66- var inst * rpc.Instance
67- if resp , err := srv .Create (ctx , & rpc.CreateRequest {}); err != nil {
68- return nil , err
69- } else {
70- inst = resp .GetInstance ()
73+ if arduinoCLIServer == nil {
74+ logrus .SetLevel (logrus .ErrorLevel ) // Reduce the log level of arduino-cli
75+ arduinoCLIServer = commands .NewArduinoCoreServer ()
7176 }
72- defer func () {
73- _ , _ = srv .Destroy (ctx , & rpc.DestroyRequest {Instance : inst })
74- }()
7577
76- if err := srv .Init (
77- & rpc.InitRequest {Instance : inst },
78- // TODO: implement progress callback function
79- commands .InitStreamResponseToCallbackFunction (ctx , func (r * rpc.InitResponse ) error { return nil }),
80- ); err != nil {
81- return nil , err
78+ if arduinoCLIInstance == nil {
79+ var inst * rpc.Instance
80+ if resp , err := arduinoCLIServer .Create (ctx , & rpc.CreateRequest {}); err != nil {
81+ return nil , err
82+ } else {
83+ inst = resp .GetInstance ()
84+ }
85+
86+ if err := arduinoCLIServer .Init (
87+ & rpc.InitRequest {Instance : inst },
88+ // TODO: implement progress callback function
89+ commands .InitStreamResponseToCallbackFunction (ctx , func (r * rpc.InitResponse ) error { return nil }),
90+ ); err != nil {
91+ // in case of error destroy invalid instance
92+ _ , _ = arduinoCLIServer .Destroy (ctx , & rpc.DestroyRequest {Instance : inst })
93+ return nil , err
94+ }
95+
96+ arduinoCLIInstance = inst
8297 }
8398
84- list , err := srv .BoardList (ctx , & rpc.BoardListRequest {
85- Instance : inst ,
99+ list , err := arduinoCLIServer .BoardList (ctx , & rpc.BoardListRequest {
100+ Instance : arduinoCLIInstance ,
86101 Timeout : 2000 , // 2 seconds
87102 Fqbn : fqbn ,
88103 })
0 commit comments