text
stringlengths
1
2.05k
import
import os
import ctypes
import tvm from tvm
import te def load_lib(): """Load library, the functions will be registered into TVM""" curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) lib = ctypes.CDLL(os.path.join(curr_path, "../../lib/libtvm_ext.so"), ctypes.RTLD_GLOBAL) return lib _LIB = load_lib() bind_add = tvm.get_global_func("tvm_ext.bind_add") sym_add = tvm.get_global_func("tvm_ext.sym_add") ivec_create = tvm.get_global_func("tvm_ext.ivec_create") ivec_get = tvm.get_global_func("tvm_ext.ivec_get") @tvm.register_object("tvm_ext.IntVector")
class IntVec(tvm.Object): """Example for using extension class in c++""" @property def _tvm_handle(self): return self.handle.value def __getitem__(self, idx): return ivec_get(self, idx) nd_create = tvm.get_global_func("tvm_ext.nd_create") nd_add_two = tvm.get_global_func("tvm_ext.nd_add_two") nd_get_additional_info = tvm.get_global_func("tvm_ext.nd_get_additional_info") @tvm.register_object("tvm_ext.NDSubClass")
class NDSubClass(tvm.nd.NDArrayBase): """Example for subclassing TVM's NDArray infrastructure. By inheriting TVM's NDArray, external libraries could leverage TVM's FFI without any modification. """ @staticmethod def create(additional_info): return nd_create(additional_info) @property def additional_info(self): return nd_get_additional_info(self) def __add__(self, other): return nd_add_two(self, other)
import tvm_ext
import tvm
import tvm._ffi.registry
import tvm.testing from tvm
import te
import numpy as np def test_bind_add(): def add(a, b): return a + b f = tvm_ext.bind_add(add, 1) assert f(2) == 3 def test_ext_dev(): n = 10 A = te.placeholder((n,), name="A") B = te.compute((n,), lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) def check_llvm(): if not tvm.testing.device_enabled("llvm"): return f = tvm.build(s, [A, B], "ext_dev", "llvm") dev = tvm.ext_dev(0) a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev) f(a, b) tvm.testing.assert_allclose(b.numpy(), a.numpy() + 1) check_llvm() def test_sym_add(): a = te.var("a") b = te.var("b") c = tvm_ext.sym_add(a, b) assert c.a == a and c.b == b def test_ext_vec(): ivec = tvm_ext.ivec_create(1, 2, 3) assert isinstance(ivec, tvm_ext.IntVec) assert ivec[0] == 1 assert ivec[1] == 2 def ivec_cb(v2): assert isinstance(v2, tvm_ext.IntVec) assert v2[2] == 3 tvm.runtime.convert(ivec_cb)(ivec) def test_extract_ext(): fdict = tvm._ffi.registry.extract_ext_funcs(tvm_ext._LIB.TVMExtDeclare) assert fdict["mul"](3, 4) == 12 def test_extern_call(): n = 10 A = te.placeholder((n,), name="A") B = te.compute( (n,), lambda *i: tvm.tir.call_extern("float32", "TVMTestAddOne", A(*i)), name="B" ) s = te.create_schedule(B.op) def check_llvm(): if not tvm.testing.device_enabled("llvm"): return f = tvm.build(s, [A, B], "llvm") dev = tvm.cpu(0) a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(n, dtype=B.dtype), dev) f(a, b) tvm.testing.assert_allclose(b.numpy(), a.numpy() + 1) check_llvm() def test_nd_subclass(): a = tvm_ext.NDSubClass.create(additional_info=3) b = tvm_ext.NDSubClass.create(additional_info=5) assert isinstance(a, tvm_ext.N
DSubClass) c = a + b d = a + a e = b + b assert a.additional_info == 3 assert b.additional_info == 5 assert c.additional_info == 8 assert d.additional_info == 6 assert e.additional_info == 10 if __name__ == "__main__": test_nd_subclass() test_extern_call() test_ext_dev() test_ext_vec() test_bind_add() test_sym_add() test_extract_ext()
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http: * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
struct tensor_meta { int ndim; DLDataType dtype; int64_t shape[]; int meta_size() const { return meta_size(ndim); } int data_size() const { int size = tvm::runtime::DataType(dtype).bytes(); for (int d = 0; d != ndim; ++d) { size *= shape[d]; } return size; } static int meta_size(int ndim) { return sizeof(tensor_meta) + ndim * sizeof(int64_t); } std::string to_string() const; };
struct TensorConfig { static const std::string file_key; static const std::string shape_key; static const std::string dtype_key; std::string file_name; std::vector<int> shape; std::string dtype; bool bad = false; void Load(dmlc::JSONReader* reader); void Save(dmlc::JSONWriter* writer) const; };
struct ModelConfig { std::string model_library; std::string model_json; std::vector<TensorConfig> inputs; bool bad = false; void Load(dmlc::JSONReader* reader); };
struct OutputConfig { uint64_t pcycles; uint64_t usecs; std::vector<TensorConfig> outputs; void Save(dmlc::JSONWriter* writer) const; };
struct Model { Model(tvm::runtime::Module executor, tvm::runtime::Module module, std::string json); tvm::runtime::Module model_executor; tvm::runtime::Module graph_module; std::string graph_json; static tvm::Device device() { return tvm::Device{static_cast<DLDeviceType>(kDLHexagon), 0}; } static tvm::Device external() { return tvm::Device{static_cast<DLDeviceType>(kDLCPU), 0}; } tvm::runtime::PackedFunc run; };
struct ExecutionSession { explicit ExecutionSession(bool lwp_json = false) : gen_lwp_json(lwp_json) {} template <typename T> T* alloc(size_t bytes, size_t align = 1) { return reinterpret_cast<T*>(alloc_mem(bytes, align)); } void free(void* ptr) { free_mem(ptr); } virtual void* alloc_mem(size_t bytes, size_t align) = 0; virtual void free_mem(void* ptr) = 0; virtual bool load_model(const std::string& model_path, const std::string& model_json) = 0; virtual bool unload_model() = 0; virtual bool set_input(int input_idx, const tensor_meta* input_meta, const void* input_data) = 0; virtual bool run(uint64_t* pcycles, uint64_t* usecs) = 0; virtual bool get_num_outputs(int* num_outputs) = 0; virtual bool get_output(int output_idx, tensor_meta* output_meta, int meta_size, void* output_data, int data_size) = 0; bool gen_lwp_json = false; }; bool read_model_config(const std::string& file_name, ModelConfig* model_config); bool write_output_config(const std::string& file_name, OutputConfig* output_config); void reset_device_api(); tvm::runtime::Module load_module(const std::string& file_name); const tvm::runtime::PackedFunc get_runtime_func(const std::string& name); const tvm::runtime::PackedFunc get_module_func(tvm::runtime::Module module, const std::string& name); tvm::runtime::Module create_aot_executor(tvm::runtime::Module factory_module, tvm::Device device); tvm::runtime::Module create_graph_executor(const std::string& graph_json, tvm::runtime::Module graph_module, tvm::Device device);
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_UTIL_H_ #define TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_UTIL_H_ #include <cstddef> #include <fstream> #include <string> size_t get_file_size(std::ifstream& in_file); size_t get_file_size(std::ifstream&& in_file); std::string load_text_file(const std::string& file_name); void* load_binary_file(const std::string& file_name, void* buffer, size_t buffer_size); void write_binary_file(const std::string& file_name, void* buffer, size_t buffer_size); #endif // TVM_RUNTIME_HEXAGON_LAUNCHER_LAUNCHER_UTIL_H_
"""Script to prepare test_addone.so"""
import tvm
import numpy as np from tvm
import te from tvm
import relay
import os def prepare_test_libs(base_path): n = te.var("n") A = te.placeholder((n,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") s = te.create_schedule(B.op) fadd_dylib = tvm.build(s, [A, B], "llvm", name="addone") dylib_path = os.path.join(base_path, "test_addone_dll.so") fadd_dylib.export_library(dylib_path) fadd_syslib = tvm.build(s, [A, B], "llvm", name="addonesys") syslib_path = os.path.join(base_path, "test_addone_sys.o") fadd_syslib.save(syslib_path) def prepare_graph_lib(base_path): x = relay.var("x", shape=(2, 2), dtype="float32") y = relay.var("y", shape=(2, 2), dtype="float32") params = {"y": np.ones((2, 2), dtype="float32")} mod = tvm.IRModule.from_expr(relay.Function([x, y], x + y)) compiled_lib = relay.build(mod, tvm.target.create("llvm"), params=params) dylib_path = os.path.join(base_path, "test_relay_add.so") compiled_lib.export_library(dylib_path) if __name__ == "__main__": curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) prepare_test_libs(os.path.join(curr_path, "lib")) prepare_graph_lib(os.path.join(curr_path, "lib"))
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # brief Example code on load and run TVM module.s # file python_deploy.py import tvm from tvm import te import numpy as np def verify(mod, fname): # Get the function from the module f = mod.get_function(fname) # Use tvm.nd.array to convert numpy ndarray to tvm # NDArray type, so that function can be invoked normally N = 10 x = tvm.nd.array(np.arange(N, dtype=np.float32)) y = tvm.nd.array(np.zeros(N, dtype=np.float32)) # Invoke the function f(x, y) np_x = x.numpy() np_y = y.numpy() # Verify correctness of function assert np.all([xi + 1 == yi for xi, yi in zip(np_x, np_y)]) print("Finish verification...") if __name__ == "__main__": # The normal dynamic loading method for deployment mod_dylib = tvm.runtime.load_module("lib/test_addone_dll.so") print("Verify dynamic loading from test_addone_dll.so") verify(mod_dylib, "addone") # There might be methods to use the system lib way in # python, but dynamic loading is good enough for now.
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import argparse import re default_team_id = "3FR42MXLK9" default_tvm_build_dir = "path-to-tvm-ios-build-folder" parser = argparse.ArgumentParser( description="Update tvmrpc.xcodeproj\ developer information" ) parser.add_argument( "--team_id", type=str, required=True, help="Apple Developer Team ID.\n\ Can be found here:\n\ \n\ https://developer.apple.com/account/#/membership\n\ (example: {})".format( default_team_id ), ) parser.add_argument( "--tvm_build_dir", type=str, required=True, help="Path to directory with libtvm_runtime.dylib", ) args = parser.parse_args() team_id = args.team_id tvm_build_dir = args.tvm_build_dir fi = open("tvmrpc.xcodeproj/project.pbxproj") proj_config = fi.read() fi.close() proj_config = proj_config.replace(default_team_id, team_id) proj_config = proj_config.replace(default_tvm_build_dir, tvm_build_dir) fo = open("tvmrpc.xcodeproj/project.pbxproj", "w") fo.write(proj_config) fo.close()
import tvm from tvm
import rpc, relay from tvm.contrib.download
import download_testdata from tvm.relay.expr_functor
import ExprMutator from tvm.relay
import transform from tvm.relay.op.annotation
import compiler_begin, compiler_end from tvm.relay.quantize.quantize
import prerequisite_optimize from tvm.contrib
import utils, xcode, graph_executor, coreml_runtime from tvm.contrib.target
import coreml as _coreml
import os
import re
import sys
import numpy as np from mxnet
import gluon from PIL
import Image
import coremltools
import argparse arch = "arm64" sdk = "iphoneos" target_host = "llvm -mtriple=%s-apple-darwin" % arch MODES = {"proxy": rpc.connect, "tracker": rpc.connect_tracker, "standalone": rpc.connect} @tvm.register_func("tvm_callback_metal_compile") def compile_metal(src): return xcode.compile_metal(src, sdk=sdk) def prepare_input(): img_url = "https: img_name = "cat.png" synset_url = "".join( [ "https: "4d0b62f3d01426887599d4f7ede23ee5/raw/", "596b27d23537e5a1b5751d2b0481ef172f58b539/", "imagenet1000_clsid_to_human.txt", ] ) synset_name = "imagenet1000_clsid_to_human.txt" img_path = download_testdata(img_url, "cat.png", module="data") synset_path = download_testdata(synset_url, synset_name, module="data") with open(synset_path) as f: synset = eval(f.read()) image = Image.open(img_path).resize((224, 224)) image = np.array(image) - np.array([123.0, 117.0, 104.0]) image /= np.array([58.395, 57.12, 57.375]) image = image.transpose((2, 0, 1)) image = image[np.newaxis, :] return image.astype("float32"), synset def get_model(model_name, data_shape): gluon_model = gluon.model_zoo.vision.get_model(model_name, pretrained=True) mod, params = relay.frontend.from_mxnet(gluon_model, {"data": data_shape}) func = mod["main"] func = relay.Function( func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs ) return func, params def test_mobilenet(host, port, key, mode): temp = utils.tempdir() image, synset = prepare_input() model, params = get_model("mobilenetv2_1.0", image.shape) def run(mod, target): with relay.build_config(opt_level=3): lib = relay.build( mod, target=tvm.target.Target(target, host=target_host), params=params ) path_dso = temp.relpath("deploy.dylib") lib.export_library(path_dso, xcode.create_dylib, arch=arch, sdk=sdk) if
mode == "tracker": remote = MODES[mode](host, port).request(key) else: remote = MODES[mode](host, port, key=key) remote.upload(path_dso) if target == "metal": dev = remote.metal(0) else: dev = remote.cpu(0) lib = remote.load_module("deploy.dylib") m = graph_executor.GraphModule(lib["default"](dev)) m.set_input("data", tvm.nd.array(image, dev)) m.run() tvm_output = m.get_output(0) top1 = np.argmax(tvm_output.numpy()[0]) print("TVM prediction top-1:", top1, synset[top1]) ftimer = m.module.time_evaluator("run", dev, number=3, repeat=10) prof_res = np.array(ftimer().results) * 1000 print("%-19s (%s)" % ("%.2f ms" % np.mean(prof_res), "%.2f ms" % np.std(prof_res))) def annotate(func, compiler): """ An annotator for Core ML. """ bind_dict = {} for arg in func.params: name = arg.name_hint if name in params: bind_dict[arg] = relay.const(params[name]) func = relay.bind(func, bind_dict) mod = tvm.IRModule() mod["main"] = func seq = tvm.transform.Sequential( [ transform.SimplifyInference(), transform.FoldConstant(), transform.FoldScaleAxis(), transform.AnnotateTarget(compiler), transform.MergeCompilerRegions(), transform.PartitionGraph(), ] ) with relay.build_config(opt_level=3): mod = seq(mod) return mod run(model, target_host) run(model, "metal") run(annotate(model, "coremlcompiler"), target_host) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Demo app demonstrates how ios_rpc works.") parser.add_argument("--host", required=True, type=str, help="Adress of rpc server") parser.add_argument("--port
", type=int, default=9090, help="rpc port (default: 9090)") parser.add_argument("--key", type=str, default="iphone", help="device key (default: iphone)") parser.add_argument( "--mode", type=str, default="tracker", help="type of RPC connection (default: tracker), possible values: {}".format( ", ".join(MODES.keys()) ), ) args = parser.parse_args() assert args.mode in MODES.keys() test_mobilenet(args.host, args.port, args.key, args.mode)
"""Testcode for iOS RPC. To use it, start a rpc proxy with "python -m tvm.exec.rpc_proxy". And configure the proxy host field as commented. """
import tvm from tvm
import te
import os
import re
import sys from tvm
import rpc from tvm.contrib
import utils, xcode
import numpy as np
import argparse arch = "arm64" sdk = "iphoneos" target = "llvm -mtriple=%s-apple-darwin" % arch MODES = {"proxy": rpc.connect, "tracker": rpc.connect_tracker, "standalone": rpc.connect} @tvm.register_func("tvm_callback_metal_compile") def compile_metal(src): return xcode.compile_metal(src, sdk=sdk) def test_rpc_module(host, port, key, mode): n = tvm.runtime.convert(1024) A = te.placeholder((n,), name="A") B = te.compute(A.shape, lambda *i: A(*i) + 1.0, name="B") temp = utils.tempdir() s = te.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], factor=64) s[B].bind(xi, te.thread_axis("threadIdx.x")) s[B].bind(xo, te.thread_axis("blockIdx.x")) f = tvm.build(s, [A, B], tvm.target.Target("metal", host=target), name="myadd") path_dso1 = temp.relpath("dev_lib.dylib") f.export_library(path_dso1, xcode.create_dylib, arch=arch, sdk=sdk) s = te.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], factor=64) s[B].parallel(xi) s[B].pragma(xo, "parallel_launch_point") s[B].pragma(xi, "parallel_barrier_when_finish") f = tvm.build(s, [A, B], target, name="myadd_cpu") path_dso2 = temp.relpath("cpu_lib.dylib") f.export_library(path_dso2, xcode.create_dylib, arch=arch, sdk=sdk) if mode == "tracker": remote = MODES[mode](host, port).request(key) else: remote = MODES[mode](host, port, key=key) remote.upload(path_dso1) dev = remote.metal(0) f1 = remote.load_module("dev_lib.dylib") a_np = np.random.uniform(size=1024).astype(A.dtype) a = tvm.nd.array(a_np, dev) b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev) time_f = f1.time_evaluator(f1.entry_name, dev, number=10) cost = time_f(a, b).mean print("Metal: %g secs/op" % cost) np.testing.assert_equal(b.numpy(), a.numpy() + 1) dev = remote.cpu(0) remote.upload(path_dso2) f2 = remote.load_module("cpu_lib.dylib") a_np = np.random.uniform(size=1024).astype(A.dtype) a = tvm.nd.array(a_np,
dev) b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), dev) time_f = f2.time_evaluator(f2.entry_name, dev, number=10) cost = time_f(a, b).mean print("CPU: %g secs/op" % cost) np.testing.assert_equal(b.numpy(), a.numpy() + 1) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Demo app demonstrates how ios_rpc works.") parser.add_argument("--host", required=True, type=str, help="Adress of rpc server") parser.add_argument("--port", type=int, default=9090, help="rpc port (default: 9090)") parser.add_argument("--key", type=str, default="iphone", help="device key (default: iphone)") parser.add_argument( "--mode", type=str, default="tracker", help="type of RPC connection (default: tracker), possible values: {}".format( ", ".join(MODES.keys()) ), ) args = parser.parse_args() assert args.mode in MODES.keys() test_rpc_module(args.host, args.port, args.key, args.mode)
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file AppDelegate.h */ #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property(strong, nonatomic) UIWindow* window; @end
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http: * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ extern "C" { /*! * \brief Struct representing arguments of iOS RPC app */ typedef
struct RPCArgs_t { const char* host_url; int host_port; const char* key; const char* custom_addr; bool verbose; bool immediate_connect; RPCServerMode server_mode; } RPCArgs; /*! * \brief Get current global RPC args */ RPCArgs get_current_rpc_args(void); /*! * \brief Set current global RPC args and update values in app cache */ void set_current_rpc_args(RPCArgs args); /*! * \brief Pars command line args and update current global RPC args * Also updates values in app cache */ void update_rpc_args(int argc, char* argv[]); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http: * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file Provide interfaces to launch and control RPC Service routine */ /*! * \brief Enum with possible status of RPC server * Used to report state to listener */ typedef enum { RPCServerStatus_Launched, RPCServerStatus_Stopped, RPCServerStatus_Connected, RPCServerStatus_Disconnected, RPCServerStatus_RPCSessionStarted, RPCServerStatus_RPCSessionFinished } RPCServerStatus; /*! * \brief Enum with modes of servicing supported by RPCServer */ typedef enum { RPCServerMode_Tracker, RPCServerMode_Proxy, RPCServerMode_Standalone } RPCServerMode; /*! * \brief Listener for events happened with RPCServer */ @protocol RPCServerEventListener <NSObject> - (void)onError:(NSString*)msg; - (void)onStatusChanged:(RPCServerStatus)status; @end /*! * \brief RPC Server instance * Contains internal worker thread plus */ @interface RPCServer : NSObject <NSStreamDelegate> @property(retain) id<RPCServerEventListener> delegate; @property(retain) NSString* key; @property(retain) NSString* host; @property int port; @property(retain) NSString* custom_addr; @property BOOL verbose; @property int actual_port; @property(retain) NSString* device_addr; /*! * \brief Create server with spe
cified sevicing mode * \param mode Mode of server */ + (instancetype)serverWithMode:(RPCServerMode)mode; /*! * \brief Start RPC server with options. Non blocking method */ - (void)start; /*! * \brief Stop RPC server. Non blocking method */ - (void)stop; @end
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file ViewController.h */ #import <UIKit/UIKit.h> #import "RPCServer.h" @interface ViewController : UIViewController <RPCServerEventListener, UITextFieldDelegate> @property(weak, nonatomic) IBOutlet UITextField* proxyURL; @property(weak, nonatomic) IBOutlet UITextField* proxyPort; @property(weak, nonatomic) IBOutlet UITextField* proxyKey; @property(weak, nonatomic) IBOutlet UILabel* statusLabel; @property(weak, nonatomic) IBOutlet UITextView* infoText; - (IBAction)connect:(id)sender; @property(retain, nonatomic) IBOutlet UIButton* ConnectButton; @property(retain, nonatomic) IBOutlet UISegmentedControl* ModeSelector; @end
"""Pretty Printers for lldb debugger. Install the pretty printers by loading this file from .lldbinit: command script
import ~/bin/lldb/tvm.py Update the list of nodes for which debug information is displayed by adding to the list below. """
import lldb
import lldb.formatters g_indent = 0 def __lldb_init_module(debugger, _): for node in [ "tvm::Array", "tvm::AttrFieldInfo", "tvm::Attrs", "tvm::BijectiveLayout", "tvm::Buffer", "tvm::Channel", "tvm::EnvFunc", "tvm::Expr", "tvm::GenericFunc", "tvm::Integer", "tvm::IterVar", "tvm::IterVarAttr", "tvm::IterVarRelation", "tvm::Layout", "tvm::Map", "tvm::Map", "tvm::MemoryInfo", "tvm::Operation", "tvm::Range", "tvm::Schedule", "tvm::Stage", "tvm::Stmt", "tvm::Target", "tvm::Tensor", "tvm::TensorIntrin", "tvm::TensorIntrinCall", "tvm::TypedEnvFunc", "tvm::tir::Var", "tvm::ir::CommReducer", "tvm::ir::FunctionRef", "tvm::relay::BaseTensorType", "tvm::relay::CCacheKey", "tvm::relay::CCacheValue", "tvm::relay::CachedFunc", "tvm::relay::Call", "tvm::relay::Clause", "tvm::relay::Closure", "tvm::relay::CompileEngine", "tvm::relay::Constant", "tvm::relay::Constructor", "tvm::relay::ConstructorValue", "tvm::relay::Expr", "tvm::relay::FuncType", "tvm::relay::Function", "tvm::relay::GlobalTypeVar", "tvm::relay::GlobalVar", "tvm::relay::Id", "tvm::relay::If", "tvm::relay::IncompleteType", "tvm::relay::InterpreterState", "tvm::relay::Let", "tvm::relay::Match", "tvm::relay::Module", "tvm::relay::NamedNDArray", "tvm::relay::Op", "tvm::relay::Pattern", "tvm::relay::PatternConstructor", "tvm::relay::PatternTuple", "tvm::relay::PatternVar", "tvm::relay::PatternWildcard", "tvm::relay::RecClosure", "tvm::relay::RefCreate", "tvm::relay::RefRead", "tvm::relay::RefType", "tvm::relay::RefValue", "tvm::relay::RefWri
te", "tvm::relay::SourceName", "tvm::relay::Span", "tvm::relay::TempExpr", "tvm::relay::TensorType", "tvm::relay::Tuple", "tvm::relay::TupleGetItem", "tvm::relay::TupleType", "tvm::relay::Type", "tvm::relay::TypeCall", "tvm::relay::TypeConstraint", "tvm::relay::TypeData", "tvm::relay::TypeRelation", "tvm::relay::TypeReporter", "tvm::relay::TypeVar", "tvm::relay::Value", "tvm::relay::Var", "tvm::relay::alter_op_layout::LayoutAlternatedExpr", "tvm::relay::alter_op_layout::TransformMemorizer", "tvm::relay::fold_scale_axis::Message", "tvm::relay::fold_scale_axis:BackwardTransformer", ]: debugger.HandleCommand( "type summary add -F tvm.NodeRef_SummaryProvider {node} -w tvm".format(node=node) ) debugger.HandleCommand("command script add -f tvm.PrettyPrint pp") debugger.HandleCommand("type category enable tvm") def _log(logger, fmt, *args, **kwargs): global g_indent logger >> " " * g_indent + fmt.format(*args, **kwargs) def _GetContext(debugger): target = debugger.GetSelectedTarget() process = target.GetProcess() thread = process.GetThreadAtIndex(0) return thread.GetSelectedFrame() def PrettyPrint(debugger, command, result, internal_dict): ctx = _GetContext(debugger) rc = ctx.EvaluateExpression("tvm::PrettyPrint({command})".format(command=command)) result.AppendMessage(str(rc))
class EvaluateError(Exception): def __init__(self, error): super(Exception, self).__init__(str(error)) def _EvalExpression(logger, ctx, expr, value_name): _log(logger, "Evaluating {expr}".format(expr=expr)) rc = ctx.EvaluateExpression(expr) err = rc.GetError() if err.Fail(): _log(logger, "_EvalExpression failed: {err}".format(err=err)) raise EvaluateError(err) _log(logger, "_EvalExpression success: {typename}".format(typename=rc.GetTypeName())) return rc def _EvalExpressionAsString(logger, ctx, expr): result = _EvalExpression(logger, ctx, expr, None) return result.GetSummary() or result.GetValue() or "--" def _EvalAsNodeRef(logger, ctx, value): return _EvalExpressionAsString(logger, ctx, "tvm::PrettyPrint({name})".format(name=value.name)) def NodeRef_SummaryProvider(value, _): global g_indent g_indent += 2 try: if not value or not value.IsValid(): return "<invalid>" lldb.formatters.Logger._lldb_formatters_debug_level = 0 logger = lldb.formatters.Logger.Logger() ctx = _GetContext(lldb.debugger) return _EvalAsNodeRef(logger, ctx, value) except EvaluateError as e: return str(e) finally: g_indent -= 2
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http: * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \brief CRT configuration for the host-linked CRT. */ /*! Log level of the CRT runtime */ /*! Support low-level debugging in MISRA-C runtime */ /*! Maximum supported dimension in NDArray */ /*! Maximum supported arguments in generated functions */ /*! Maximum supported string length in dltype, e.g. "int8", "int16", "float32" */ /*! Maximum supported string length in function names */ /*! Maximum supported string length in parameter names */ /*! Maximum number of registered modules. */ /*! Size of the global function registry, in bytes. */ /*! Maximum packet size, in bytes, including the length header. */ /*! \brief Maximum length of a PackedFunc function name. */
import json
import logging
import os.path
import pathlib
import re
import shutil
import subprocess
import tarfile
import tempfile
import time from string
import Template from packaging
import version from tvm.micro.project_api
import server _LOG = logging.getLogger(__name__) MODEL_LIBRARY_FORMAT_RELPATH = pathlib.Path("src") / "model" / "model.tar" API_SERVER_DIR = pathlib.Path(os.path.dirname(__file__) or os.path.getcwd()) BUILD_DIR = API_SERVER_DIR / "build" MODEL_LIBRARY_FORMAT_PATH = API_SERVER_DIR / MODEL_LIBRARY_FORMAT_RELPATH IS_TEMPLATE = not (API_SERVER_DIR / MODEL_LIBRARY_FORMAT_RELPATH).exists() MIN_ARDUINO_CLI_VERSION = version.parse("0.18.0") BOARDS = API_SERVER_DIR / "boards.json" ARDUINO_CLI_CMD = shutil.which("arduino-cli") MAKEFILE_FILENAME = "Makefile" try: with open(BOARDS) as boards: BOARD_PROPERTIES = json.load(boards) except FileNotFoundError: raise FileNotFoundError(f"Board file {{{BOARDS}}} does not exist.") def get_cmsis_path(cmsis_path: pathlib.Path) -> pathlib.Path: """Returns CMSIS dependency path""" if cmsis_path: return pathlib.Path(cmsis_path) if os.environ.get("CMSIS_PATH"): return pathlib.Path(os.environ.get("CMSIS_PATH")) assert False, "'cmsis_path' option not passed!"
class BoardAutodetectFailed(Exception): """Raised when no attached hardware is found matching the requested board""" PROJECT_TYPES = ["example_project", "host_driven"] PROJECT_OPTIONS = server.default_project_options( project_type={"choices": tuple(PROJECT_TYPES)}, board={"choices": list(BOARD_PROPERTIES), "optional": ["flash", "open_transport"]}, warning_as_error={"optional": ["build", "flash"]}, ) + [ server.ProjectOption( "arduino_cli_cmd", required=(["generate_project", "flash", "open_transport"] if not ARDUINO_CLI_CMD else None), optional=( ["generate_project", "build", "flash", "open_transport"] if ARDUINO_CLI_CMD else None ), type="str", default=ARDUINO_CLI_CMD, help="Path to the arduino-cli tool.", ), server.ProjectOption( "port", optional=["flash", "open_transport"], type="int", default=None, help="Port to use for connecting to hardware.", ), ]
class Handler(server.ProjectAPIHandler): def __init__(self): super(Handler, self).__init__() self._proc = None self._port = None self._serial = None self._version = None def server_info_query(self, tvm_version): return server.ServerInfo( platform_name="arduino", is_template=IS_TEMPLATE, model_library_format_path="" if IS_TEMPLATE else MODEL_LIBRARY_FORMAT_PATH, project_options=PROJECT_OPTIONS, ) def _copy_project_files(self, api_server_dir, project_dir, project_type): """Copies the files for project_type into project_dir. Notes ----- template_dir is NOT a project type, and that directory is never copied in this function. template_dir only holds this file and its unit tests, so this file is copied separately in generate_project. """ for item in (API_SERVER_DIR / "src" / project_type).iterdir(): if item.name == "project.ino": continue dest = project_dir / "src" / item.name if item.is_dir(): shutil.copytree(item, dest) else: shutil.copy2(item, dest) shutil.copy2( API_SERVER_DIR / "src" / project_type / "project.ino", project_dir / f"{project_dir.stem}.ino", ) CRT_COPY_ITEMS = ("include", "src") def _copy_standalone_crt(self, source_dir, standalone_crt_dir): output_crt_dir = source_dir / "standalone_crt" for item in self.CRT_COPY_ITEMS: src_path = os.path.join(standalone_crt_dir, item) dst_path = output_crt_dir / item if os.path.isdir(src_path): shutil.copytree(src_path, dst_path) else: shutil.copy2(src_path, dst_path) EXAMPLE_PROJECT_UNUSED_COMPONENTS = [ "include/dmlc", "src/support", "src/runtime/minrpc", "src/runtime/crt/graph_executor",
"src/runtime/crt/microtvm_rpc_common", "src/runtime/crt/microtvm_rpc_server", "src/runtime/crt/tab", ] def _remove_unused_components(self, source_dir, project_type): unused_components = [] if project_type == "example_project": unused_components = self.EXAMPLE_PROJECT_UNUSED_COMPONENTS for component in unused_components: shutil.rmtree(source_dir / "standalone_crt" / component) def _disassemble_mlf(self, mlf_tar_path, source_dir): with tempfile.TemporaryDirectory() as mlf_unpacking_dir_str: mlf_unpacking_dir = pathlib.Path(mlf_unpacking_dir_str) with tarfile.open(mlf_tar_path, "r:") as tar: tar.extractall(mlf_unpacking_dir) model_dir = source_dir / "model" model_dir.mkdir() source_dir = mlf_unpacking_dir / "codegen" / "host" / "src" for file in source_dir.rglob("*.c"): shutil.copy(file, model_dir) with open(os.path.join(mlf_unpacking_dir, "metadata.json")) as f: metadata = json.load(f) return metadata def _template_model_header(self, source_dir, metadata): with open(source_dir / "model.h", "r") as f: model_h_template = Template(f.read()) all_module_names = [] for name in metadata["modules"].keys(): all_module_names.append(name) assert all( metadata["modules"][mod_name]["style"] == "full-model" for mod_name in all_module_names ), "when generating AOT, expect only full-model Model Library Format" workspace_size_bytes = 0 for mod_name in all_module_names: workspace_size_bytes += metadata["modules"][mod_name]["memory"]["functions"]["main"][0][ "workspace_size_bytes" ] template_values = { "workspace_size_bytes": workspace_size_bytes, } with open(source_dir / "model.h", "w") a
s f: f.write(model_h_template.substitute(template_values)) CPP_FILE_EXTENSION_SYNONYMS = ("cc", "cxx") def _change_cpp_file_extensions(self, source_dir): for ext in self.CPP_FILE_EXTENSION_SYNONYMS: for filename in source_dir.rglob(f"*.{ext}"): filename.rename(filename.with_suffix(".cpp")) for filename in source_dir.rglob("*.inc"): filename.rename(filename.with_suffix(".h")) def _convert_includes(self, project_dir, source_dir): """Changes all containing file's location. Arduino only supports includes relative to a file's location, so this function finds each time we be relative to the file location. Does not do this for standard C libraries. Also changes angle brackets syntax to double quotes syntax. See Also ----- https: """ for ext in ("c", "h", "cpp"): for filename in source_dir.rglob(f"*.{ext}"): with filename.open("rb") as src_file: lines = src_file.readlines() with filename.open("wb") as dst_file: for line in lines: line_str = str(line, "utf-8") result = re.search(r" if not result: dst_file.write(line) else: new_
include = self._find_modified_include_path( project_dir, filename, result.groups()[0] ) updated_line = f' dst_file.write(updated_line.encode("utf-8")) POSSIBLE_BASE_PATHS = ["src/standalone_crt/include/", "src/standalone_crt/crt_config/"] def _find_modified_include_path(self, project_dir, file_path, include_path): """Takes a single Examples -------- >>> _find_modified_include_path( ... "/path/to/project/dir" ... "/path/to/project/dir/src/standalone_crt/src/runtime/crt/common/ndarray.c" ... "tvm/runtime/crt/platform.h" ... ) "../../../../../../src/standalone_crt/include/tvm/runtime/crt/platform.h" """ if include_path.endswith(".inc"): include_path = re.sub(r"\.[a-z]+$", ".h", include_path) if include_path.endswith(self.CPP_FILE_EXTENSION_SYNONYMS): include_path = re.sub(r"\.[a-z]+$", ".cpp", include_path) if (file_path.parents[0] / include_path).exists(): return include_path relative_path = file_path.relative_to(project_dir) up_dirs_path = "../" * str(relative_path).count("/") for base_path in self.POSSIBLE_BASE_PATHS: full_potential_path = project_dir / base_path / include_path if full_potential_path.exists(): return up_dirs_path + base_path + include_path return include_path CMSIS_INCLUDE_HEADERS = [ "arm_nn_math_types.h", "arm_nn_tables.h", "arm_nn_types.h", "arm_nnfunctions.h", "arm_nnsupportfunctions.h", ] def _cmsis_required(self, project_path: pathlib.Path) -> bool: """Check if CMSIS dependency is required.""" project_path = pathlib.Path(project_path) for path in (project_path / "src" / "model").iterdir():
if path.is_file(): with open(path, "r", encoding="ISO-8859-1") as lib_f: lib_content = lib_f.read() if any(header in lib_content for header in self.CMSIS_INCLUDE_HEADERS): return True return False def _copy_cmsis(self, project_path: pathlib.Path, cmsis_path: str): """Copy CMSIS header files to project. Note: We use this CMSIS package:https: However, the latest release does not
include header files that are copied in this function. """ (project_path / "include" / "cmsis").mkdir() cmsis_path = get_cmsis_path(cmsis_path) for item in self.CMSIS_INCLUDE_HEADERS: shutil.copy2( cmsis_path / "CMSIS" / "NN" / "Include" / item, project_path / "include" / "cmsis" / item, ) def _populate_makefile( self, makefile_template_path: pathlib.Path, makefile_path: pathlib.Path, board: str, verbose: bool, arduino_cli_cmd: str, build_extra_flags: str, ): """Generate Makefile from template.""" flags = { "FQBN": self._get_fqbn(board), "VERBOSE_FLAG": "--verbose" if verbose else "", "ARUINO_CLI_CMD": self._get_arduino_cli_cmd(arduino_cli_cmd), "BOARD": board, "BUILD_EXTRA_FLAGS": build_extra_flags, } with open(makefile_path, "w") as makefile_f: with open(makefile_template_path, "r") as makefile_template_f: for line in makefile_template_f: SUBST_TOKEN_RE = re.compile(r"<([A-Z_]+)>") outs = [] for i, m in enumerate(re.split(SUBST_TOKEN_RE, line)): if i % 2 == 1: m = flags[m] outs.append(m) line = "".join(outs) makefile_f.write(line) def generate_project(self, model_library_format_path, standalone_crt_dir, project_dir, options): board = options["board"] verbose = options.get("verbose") project_type = options["project_type"] arduino_cli_cmd = options.get("arduino_cli_cmd") cmsis_path = options.get("cmsis_path") compile_definitions = options.get("compile_definitions") extra_files_tar = options.get("extra_files_tar") project_dir = pathlib.Path(project_dir) project_dir.mkdir()
source_dir = project_dir / "src" source_dir.mkdir() shutil.copy2(API_SERVER_DIR / "microtvm_api_server.py", project_dir) shutil.copy2(BOARDS, project_dir / BOARDS.name) self._copy_project_files(API_SERVER_DIR, project_dir, project_type) self._copy_standalone_crt(source_dir, standalone_crt_dir) self._remove_unused_components(source_dir, project_type) crt_config_dir = project_dir / "src" / "standalone_crt" / "crt_config" crt_config_dir.mkdir() shutil.copy2( API_SERVER_DIR / "crt_config" / "crt_config.h", crt_config_dir / "crt_config.h" ) metadata = self._disassemble_mlf(model_library_format_path, source_dir) shutil.copy2(model_library_format_path, project_dir / MODEL_LIBRARY_FORMAT_RELPATH) if project_type == "example_project": self._template_model_header(source_dir, metadata) self._change_cpp_file_extensions(source_dir) self._convert_includes(project_dir, source_dir) (project_dir / "include").mkdir() if extra_files_tar: with tarfile.open(extra_files_tar, mode="r:*") as tf: tf.extractall(project_dir) build_extra_flags = '"build.extra_flags=' if extra_files_tar: build_extra_flags += "-I./
include " if compile_definitions: for item in compile_definitions: build_extra_flags += f"{item} " if self._cmsis_required(project_dir): build_extra_flags += f"-I./include/cmsis " self._copy_cmsis(project_dir, cmsis_path) build_extra_flags += '"' if build_extra_flags == '"build.extra_flags="': build_extra_flags = '""' self._populate_makefile( API_SERVER_DIR / f"{MAKEFILE_FILENAME}.template", project_dir / MAKEFILE_FILENAME, board, verbose, arduino_cli_cmd, build_extra_flags, ) def _get_arduino_cli_cmd(self, arduino_cli_cmd: str): if not arduino_cli_cmd: arduino_cli_cmd = ARDUINO_CLI_CMD assert arduino_cli_cmd, "'arduino_cli_cmd' command not passed and not found by default!" return arduino_cli_cmd def _get_platform_version(self, arduino_cli_path: str) -> float: version_output = subprocess.run( [arduino_cli_path, "version"], check=True, stdout=subprocess.PIPE ).stdout.decode("utf-8") str_version = re.search(r"Version: ([\.0-9]*)", version_output).group(1) return version.parse(str_version) def _check_platform_version(self, cli_command: str, warning_as_error: bool): if not self._version: self._version = self._get_platform_version(cli_command) if self._version < MIN_ARDUINO_CLI_VERSION: message = ( f"Arduino CLI version too old: found {self._version}, " f"need at least {str(MIN_ARDUINO_CLI_VERSION)}." ) if warning_as_error is not None and warning_as_error: raise server.ServerError(message=message) _LOG.warning(message) def _get_fqbn(self, board: str): o = BOARD_PROPERTIES[board] return f"{o['package']}:{o['architecture']}:{o['bo
ard']}" def build(self, options): arduino_cli_cmd = options.get("arduino_cli_cmd") warning_as_error = options.get("warning_as_error") cli_command = self._get_arduino_cli_cmd(arduino_cli_cmd) self._check_platform_version(cli_command, warning_as_error) compile_cmd = ["make", "build"] subprocess.run(compile_cmd, check=True, cwd=API_SERVER_DIR) POSSIBLE_BOARD_LIST_HEADERS = ("Port", "Protocol", "Type", "Board Name", "FQBN", "Core") def _parse_connected_boards(self, tabular_str): """Parses the tabular output from `arduino-cli board list` into a 2D array Examples -------- >>> list(_parse_connected_boards(bytes( ... "Port Type Board Name FQBN Core \n" ... "/dev/ttyS4 Serial Port Unknown \n" ... "/dev/ttyUSB0 Serial Port (USB) Spresense SPRESENSE:spresense:spresense SPRESENSE:spresense\n" ... "\n", ... "utf-8"))) [['/dev/ttys4', 'Serial Port', 'Unknown', '', ''], ['/dev/ttyUSB0', 'Serial Port (USB)', 'Spresense', 'SPRESENSE:spresense:spresense', 'SPRESENSE:spresense']] """ column_regex = r"\s*|".join(self.POSSIBLE_BOARD_LIST_HEADERS) + r"\s*" str_rows = tabular_str.split("\n") column_headers = list(re.finditer(column_regex, str_rows[0])) assert len(column_headers) > 0 for str_row in str_rows[1:]: if not str_row.strip(): continue device = {} for column in column_headers: col_name = column.group(0).strip().lower() device[col_name] = str_row[column.start() : column.end()].strip() yield device def _auto_detect_port(self, arduino_cli_cmd: str, board: str) -> str: list_cmd = [self._get_arduino_cli_cmd(arduino_cli_cmd), "board", "list"] list_cmd_outpu
t = subprocess.run( list_cmd, check=True, stdout=subprocess.PIPE ).stdout.decode("utf-8") desired_fqbn = self._get_fqbn(board) for device in self._parse_connected_boards(list_cmd_output): if device["fqbn"] == desired_fqbn: return device["port"] raise BoardAutodetectFailed() def _get_arduino_port(self, arduino_cli_cmd: str, board: str, port: int): if not self._port: if port: self._port = port else: self._port = self._auto_detect_port(arduino_cli_cmd, board) return self._port def _get_board_from_makefile(self, makefile_path: pathlib.Path) -> str: """Get Board from generated Makefile.""" with open(makefile_path) as makefile_f: line = makefile_f.readline() if "BOARD" in line: board = re.sub(r"\s", "", line).split(":=")[1] return board raise RuntimeError("Board was not found in Makefile: {}".format(makefile_path)) FLASH_TIMEOUT_SEC = 60 FLASH_MAX_RETRIES = 5 def flash(self, options): arduino_cli_cmd = options.get("arduino_cli_cmd") warning_as_error = options.get("warning_as_error") port = options.get("port") board = options.get("board") if not board: board = self._get_board_from_makefile(API_SERVER_DIR / MAKEFILE_FILENAME) cli_command = self._get_arduino_cli_cmd(arduino_cli_cmd) self._check_platform_version(cli_command, warning_as_error) port = self._get_arduino_port(cli_command, board, port) upload_cmd = ["make", "flash", f"PORT={port}"] for _ in range(self.FLASH_MAX_RETRIES): try: subprocess.run( upload_cmd, check=True, timeout=self.FLASH_TIMEOUT_SEC, cwd=API_SERVER_DIR ) break except subprocess.TimeoutExpired: _LO
G.warning( f"Upload attempt to port {port} timed out after {self.FLASH_TIMEOUT_SEC} seconds" ) else: raise RuntimeError( f"Unable to flash Arduino board after {self.FLASH_MAX_RETRIES} attempts" ) def open_transport(self, options):
import serial
import serial.tools.list_ports arduino_cli_cmd = options.get("arduino_cli_cmd") port = options.get("port") board = options.get("board") if not board: board = self._get_board_from_makefile(API_SERVER_DIR / MAKEFILE_FILENAME) if self._serial is not None: return port = self._get_arduino_port(arduino_cli_cmd, board, port) for _ in range(10): if any(serial.tools.list_ports.grep(port)): break time.sleep(0.5) self._serial = serial.Serial(port, baudrate=115200, timeout=10) return server.TransportTimeouts( session_start_retry_timeout_sec=2.0, session_start_timeout_sec=5.0, session_established_timeout_sec=5.0, ) def close_transport(self): if self._serial is None: return self._serial.close() self._serial = None def read_transport(self, n, timeout_sec): self._serial.timeout = timeout_sec if self._serial is None: raise server.TransportClosedError() return self._serial.read(n) def write_transport(self, data, timeout_sec): self._serial.write_timeout = timeout_sec if self._serial is None: raise server.TransportClosedError() return self._serial.write(data) if __name__ == "__main__": server.main(Handler())