From fe5622ed95a736130521bb7d090d93ac90d2fda5 Mon Sep 17 00:00:00 2001 From: Alexander Peskov Date: Mon, 31 May 2021 18:04:53 +0300 Subject: [PATCH] [IOS-RPC] lint fix Signed-off-by: Alexander Peskov --- apps/ios_rpc/tvmrpc/RPCServer.h | 19 +- apps/ios_rpc/tvmrpc/RPCServer.mm | 204 +++++++++--------- apps/ios_rpc/tvmrpc/ViewController.h | 8 +- apps/ios_rpc/tvmrpc/ViewController.mm | 16 +- apps/ios_rpc/tvmrpc/rpc_args.h | 22 +- apps/ios_rpc/tvmrpc/rpc_args.mm | 83 ++++--- apps/ios_rpc/tvmrpcLauncher/tvmrpcLauncher.mm | 12 +- 7 files changed, 178 insertions(+), 186 deletions(-) diff --git a/apps/ios_rpc/tvmrpc/RPCServer.h b/apps/ios_rpc/tvmrpc/RPCServer.h index 1ad9b1f71c36b..1101119a85ccf 100644 --- a/apps/ios_rpc/tvmrpc/RPCServer.h +++ b/apps/ios_rpc/tvmrpc/RPCServer.h @@ -28,10 +28,10 @@ * Used to report state to listener */ typedef enum { - RPCServerStatus_Launched, // Worker thread is launched - RPCServerStatus_Stopped, // Worker thread stopped - RPCServerStatus_Connected, // Connected to Proxy/Tracker - RPCServerStatus_Disconnected, // Disconnected from Proxy/Tracker + RPCServerStatus_Launched, // Worker thread is launched + RPCServerStatus_Stopped, // Worker thread stopped + RPCServerStatus_Connected, // Connected to Proxy/Tracker + RPCServerStatus_Disconnected, // Disconnected from Proxy/Tracker RPCServerStatus_RPCSessionStarted, // RPC session is started RPCServerStatus_RPCSessionFinished // RPC session is finished } RPCServerStatus; @@ -53,12 +53,11 @@ typedef enum { */ @protocol RPCServerEventListener /// Callback to notifying about new status -- (void)onError:(NSString*) msg; +- (void)onError:(NSString*)msg; /// Callback to notifying about error -- (void)onStatusChanged:(RPCServerStatus) status; +- (void)onStatusChanged:(RPCServerStatus)status; @end - /*! * \brief RPC Server instance * Contains internal worker thread plus @@ -69,13 +68,13 @@ typedef enum { * \brief Create server with specified sevicing mode * \param mode Mode of server */ -+ (instancetype)serverWithMode:(RPCServerMode) mode; ++ (instancetype)serverWithMode:(RPCServerMode)mode; /*! * \brief Set listener delegate * \param delegate Event listener delegate to set */ -- (void)setDelegate:(id) delegate; +- (void)setDelegate:(id)delegate; /*! * \brief Start RPC server with options. Non blocking method @@ -83,7 +82,7 @@ typedef enum { * \param port Port of Tracker/Proxy to connect. Skipped for PureServer mode * \param key device key to use in RPC server */ -- (void)startWithHost:(NSString*) host port:(int) port key:(NSString*) key; +- (void)startWithHost:(NSString*)host port:(int)port key:(NSString*)key; /*! * \brief Stop RPC server. Non blocking method diff --git a/apps/ios_rpc/tvmrpc/RPCServer.mm b/apps/ios_rpc/tvmrpc/RPCServer.mm index 0e95b47e64702..ab55346f40cb0 100644 --- a/apps/ios_rpc/tvmrpc/RPCServer.mm +++ b/apps/ios_rpc/tvmrpc/RPCServer.mm @@ -26,14 +26,14 @@ #include #include -#include #include +#include // To get device WiFi IP +#include #include -#include #include -#include +#include // TVM internal header to access Magic keys like kRPCMagic and others #include "../../../src/runtime/rpc/rpc_endpoint.h" @@ -65,12 +65,13 @@ FEventHandler CreateServerEventHandler(NSOutputStream* outputStream, std::string std::string remote_key) { const PackedFunc* event_handler_factor = Registry::Get("rpc.CreateEventDrivenServer"); ICHECK(event_handler_factor != nullptr) - << "You are using tvm_runtime module built without RPC support. " - << "Please rebuild it with USE_RPC flag."; + << "You are using tvm_runtime module built without RPC support. " + << "Please rebuild it with USE_RPC flag."; PackedFunc writer_func([outputStream](TVMArgs args, TVMRetValue* rv) { - TVMByteArray *data = args[0].ptr(); - int64_t nbytes = [outputStream write:reinterpret_cast(data->data) maxLength:data->size]; + TVMByteArray* data = args[0].ptr(); + int64_t nbytes = [outputStream write:reinterpret_cast(data->data) + maxLength:data->size]; if (nbytes < 0) { NSLog(@"%@", [outputStream streamError].localizedDescription); throw tvm::Error("Stream error"); @@ -87,21 +88,21 @@ PackedFunc writer_func([outputStream](TVMArgs args, TVMRetValue* rv) { */ static std::string getWiFiAddress() { std::string address = "unknown"; - ifaddrs *interfaces = nullptr; + ifaddrs* interfaces = nullptr; int success = getifaddrs(&interfaces); if (success == 0) { - // Loop through linked list of interfaces - ifaddrs *temp_addr = interfaces; - while(temp_addr != NULL) { - if(temp_addr->ifa_addr->sa_family == AF_INET) { - // Check if interface is en0 which is the wifi connection on the iPhone - if(std::string(temp_addr->ifa_name) == "en0") { - address = std::string(inet_ntoa(((sockaddr_in *)temp_addr->ifa_addr)->sin_addr)); - } - } - temp_addr = temp_addr->ifa_next; + // Loop through linked list of interfaces + ifaddrs* temp_addr = interfaces; + while (temp_addr != NULL) { + if (temp_addr->ifa_addr->sa_family == AF_INET) { + // Check if interface is en0 which is the wifi connection on the iPhone + if (std::string(temp_addr->ifa_name) == "en0") { + address = std::string(inet_ntoa(((sockaddr_in*)temp_addr->ifa_addr)->sin_addr)); + } } + temp_addr = temp_addr->ifa_next; + } } freeifaddrs(interfaces); @@ -111,9 +112,8 @@ PackedFunc writer_func([outputStream](TVMArgs args, TVMRetValue* rv) { } // namespace runtime } // namespace tvm - // Forward declaration -@interface RPCTrackerClien : RPCServer +@interface RPCTrackerClien : RPCServer @end // Forward declaration @@ -125,7 +125,7 @@ @interface RPCServerPure : RPCServer * Will automatically connect/reconnect to RPCProxy server */ @implementation RPCServer { -@protected + @protected // The key of the server. NSString* key_; // The url of host. @@ -133,7 +133,7 @@ @implementation RPCServer { // The port of host. NSInteger port_; // Event listener - id delegate_; + id delegate_; // Worker thread NSThread* worker_thread_; // Triger to continue processing @@ -158,13 +158,10 @@ @implementation RPCServer { tvm::runtime::FEventHandler handler_; } -+ (instancetype)serverWithMode:(RPCServerMode) mode { - if (mode == RPCServerMode_PureServer) - return [[RPCServerPure alloc] init]; - if (mode == RPCServerMode_Proxy) - return [[RPCServer alloc] init]; - if (mode == RPCServerMode_Tracker) - return [[RPCTrackerClien alloc] init]; ++ (instancetype)serverWithMode:(RPCServerMode)mode { + if (mode == RPCServerMode_PureServer) return [[RPCServerPure alloc] init]; + if (mode == RPCServerMode_Proxy) return [[RPCServer alloc] init]; + if (mode == RPCServerMode_Tracker) return [[RPCTrackerClien alloc] init]; return nil; } @@ -177,10 +174,18 @@ - (instancetype)init { /*! * Internal setters methods */ -- (void)setDelegate:(id) delegate { delegate_ = delegate; } -- (void)setKey:(NSString*) key { key_ = key; } -- (void)setUrl:(NSString*) url { url_ = url; } -- (void)setPort:(NSInteger) port { port_ = port; } +- (void)setDelegate:(id)delegate { + delegate_ = delegate; +} +- (void)setKey:(NSString*)key { + key_ = key; +} +- (void)setUrl:(NSString*)url { + url_ = url; +} +- (void)setPort:(NSInteger)port { + port_ = port; +} /*! * \brief Main event listener method. All stream event handling starts here @@ -216,13 +221,12 @@ - (void)stream:(NSStream*)strm handleEvent:(NSStreamEvent)event { } } --(void)notifyError:(NSString*) msg { +- (void)notifyError:(NSString*)msg { NSLog(@"[IOS-RPC] ERROR: %@", msg); - if (delegate_ != nil) - [delegate_ onError:msg]; + if (delegate_ != nil) [delegate_ onError:msg]; } --(void)notifyState:(RPCServerStatus) state { +- (void)notifyState:(RPCServerStatus)state { if (state == RPCServerStatus_Launched) { // Notify host runner script with actual address NSLog(@"[IOS-RPC] IP: %s", server_ip_.c_str()); @@ -231,8 +235,7 @@ -(void)notifyState:(RPCServerStatus) state { // Notify host runner script with current status NSLog(@"[IOS-RPC] STATE: %d", state); // Notify listener - if (delegate_ != nil) - [delegate_ onStatusChanged:state]; + if (delegate_ != nil) [delegate_ onStatusChanged:state]; } - (void)onReadAvailable { @@ -270,7 +273,7 @@ - (void)onReadAvailable { } // always try to write try { - TVMByteArray arr {recvBuffer_.data(), recvBuffer_.size()}; + TVMByteArray arr{recvBuffer_.data(), recvBuffer_.size()}; flag = handler_(arr, flag); if (flag == 2) { [self onShutdownReceived]; @@ -290,7 +293,7 @@ - (void)onWriteAvailable { [self notifyState:RPCServerStatus_Connected]; if (initialized_) { try { - TVMByteArray dummy {nullptr, 0}; + TVMByteArray dummy{nullptr, 0}; int flag = handler_(dummy, 2); if (flag == 2) { [self onShutdownReceived]; @@ -324,12 +327,11 @@ - (void)open { initialized_ = false; initBytes_ = os.str(); initSendPtr_ = 0; - + // Initialize the network. CFReadStreamRef readStream; CFWriteStreamRef writeStream; - CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)url_, port_, - &readStream, &writeStream); + CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)url_, port_, &readStream, &writeStream); inputStream_ = (NSInputStream*)readStream; outputStream_ = (NSOutputStream*)writeStream; [inputStream_ setDelegate:self]; @@ -356,18 +358,20 @@ - (void)close { [self notifyState:RPCServerStatus_Disconnected]; } -- (void)startWithHost:(NSString*) host port: (int) port key:(NSString*) key { +- (void)startWithHost:(NSString*)host port:(int)port key:(NSString*)key { key_ = [key copy]; port_ = port; url_ = [host copy]; - + // process in separate thead with runloop worker_thread_ = [[NSThread alloc] initWithBlock:^{ @autoreleasepool { [self open]; [self notifyState:RPCServerStatus_Launched]; shouldKeepRunning = YES; - while (shouldKeepRunning && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); + while (shouldKeepRunning && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode + beforeDate:[NSDate distantFuture]]) + ; [self notifyState:RPCServerStatus_Stopped]; } }]; @@ -375,8 +379,7 @@ - (void)startWithHost:(NSString*) host port: (int) port key:(NSString*) key { } - (void)stop { - if (worker_thread_ == nil) - return; + if (worker_thread_ == nil) return; [self performSelector:@selector(stop_) onThread:worker_thread_ withObject:nil waitUntilDone:NO]; worker_thread_ = nil; @@ -394,9 +397,9 @@ @implementation RPCServerPure { CFSocketNativeHandle socket_; } -- (void)handleConnect:(const CFSocketNativeHandle) hdl { +- (void)handleConnect:(const CFSocketNativeHandle)hdl { socket_ = hdl; - + // Initialize the data states. std::string full_key = std::string("server:") + [key_ UTF8String]; std::ostringstream os; @@ -408,7 +411,7 @@ - (void)handleConnect:(const CFSocketNativeHandle) hdl { initialized_ = false; initBytes_ = os.str(); initSendPtr_ = 0; - + // Initialize the network. CFReadStreamRef readStream; CFWriteStreamRef writeStream; @@ -427,18 +430,18 @@ - (void)handleConnect:(const CFSocketNativeHandle) hdl { ICHECK(handler_ != nullptr); } -static void handleConnect(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { +static void handleConnect(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, + const void* data, void* info) { RPCServerPure* it = static_cast(info); [it handleConnect:*static_cast(data)]; } - (void)open { - CFSocketContext ctx {}; + CFSocketContext ctx{}; ctx.info = self; - CFSocketRef myipv4cfsock = CFSocketCreate( - kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, - kCFSocketAcceptCallBack, handleConnect, &ctx); + CFSocketRef myipv4cfsock = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, + kCFSocketAcceptCallBack, handleConnect, &ctx); struct sockaddr_in sin; int rpc_port = 9090; // TODO: hardcoded. Should try bind in range of ports @@ -446,21 +449,20 @@ - (void)open { sin.sin_len = sizeof(sin); sin.sin_family = AF_INET; sin.sin_port = htons(rpc_port); - sin.sin_addr.s_addr= INADDR_ANY; + sin.sin_addr.s_addr = INADDR_ANY; - CFDataRef sincfd = CFDataCreate( - kCFAllocatorDefault, - (UInt8 *)&sin, - sizeof(sin)); + CFDataRef sincfd = CFDataCreate(kCFAllocatorDefault, (UInt8*)&sin, sizeof(sin)); if (CFSocketSetAddress(myipv4cfsock, sincfd) != 0) - @throw [NSException exceptionWithName:@"SocketError" - reason:[NSString stringWithFormat:@"Can not bind to port %d", rpc_port] - userInfo:nil]; + @throw [NSException + exceptionWithName:@"SocketError" + reason:[NSString stringWithFormat:@"Can not bind to port %d", rpc_port] + userInfo:nil]; CFRelease(sincfd); server_port_ = rpc_port; - CFRunLoopSourceRef socketsource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, myipv4cfsock, 0); + CFRunLoopSourceRef socketsource = + CFSocketCreateRunLoopSource(kCFAllocatorDefault, myipv4cfsock, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), socketsource, kCFRunLoopDefaultMode); } @@ -492,9 +494,9 @@ @implementation RPCTrackerClien { TrackerClientState state_; } -- (void)toSend:(NSData*) data { +- (void)toSend:(NSData*)data { // try to send - NSInteger sent_size = [outputStream_ write:(uint8_t*)data.bytes maxLength:data.length]; + NSInteger sent_size = [outputStream_ write:(uint8_t*)data.bytes maxLength:data.length]; // assume that all data is sent if (sent_size != data.length) @throw [NSException exceptionWithName:@"SocketError" @@ -502,16 +504,16 @@ - (void)toSend:(NSData*) data { userInfo:nil]; } -- (void)toSendPacked:(NSData*) data { +- (void)toSendPacked:(NSData*)data { // try to send int packet_size = data.length; - NSInteger sent_size = [outputStream_ write:(uint8_t*)&packet_size maxLength:sizeof(packet_size)]; + NSInteger sent_size = [outputStream_ write:(uint8_t*)&packet_size maxLength:sizeof(packet_size)]; if (sent_size != sizeof(packet_size)) @throw [NSException exceptionWithName:@"SocketError" reason:[NSString stringWithFormat:@"Unable to send data"] userInfo:nil]; - - NSInteger sent_data = [outputStream_ write:(uint8_t*)data.bytes maxLength:data.length]; + + NSInteger sent_data = [outputStream_ write:(uint8_t*)data.bytes maxLength:data.length]; // assume that all data is sent if (sent_data != data.length) @throw [NSException exceptionWithName:@"SocketError" @@ -526,10 +528,9 @@ - (void)onReadAvailable { size_t nbytes = [inputStream_ read:(uint8_t*)recvBuffer_.data() + prev_size maxLength:recvBuffer_.size() - prev_size]; recvBuffer_.resize(nbytes + prev_size); - - if (recvBuffer_.size() < required_data_size) - return; - + + if (recvBuffer_.size() < required_data_size) return; + switch (state_) { case HandshakeToRecv: { int code = tvm::runtime::kRPCTrackerMagic; @@ -537,13 +538,13 @@ - (void)onReadAvailable { required_data_size = sizeof(code); break; } - + if (recvBuffer_.size() != sizeof(code) || *(int*)recvBuffer_.data() != code) { [self notifyError:@"Wrong responce, server is not tracker."]; [self close]; break; } - + recvBuffer_.erase(recvBuffer_.begin(), recvBuffer_.begin() + sizeof(code)); required_data_size = 0; [self notifyState:RPCServerStatus_Connected]; @@ -557,7 +558,7 @@ - (void)onReadAvailable { required_data_size = sizeof(packet_size); break; } - + packet_size = *(int*)recvBuffer_.data(); if (recvBuffer_.size() < sizeof(packet_size) + packet_size) { required_data_size = sizeof(packet_size) + packet_size; @@ -569,8 +570,9 @@ - (void)onReadAvailable { [self close]; break; } - - recvBuffer_.erase(recvBuffer_.begin(), recvBuffer_.begin() + sizeof(packet_size) + packet_size); + + recvBuffer_.erase(recvBuffer_.begin(), + recvBuffer_.begin() + sizeof(packet_size) + packet_size); required_data_size = 0; state_ = ReportResToSend; break; @@ -582,7 +584,7 @@ - (void)onReadAvailable { required_data_size = sizeof(packet_size); break; } - + packet_size = *(int*)recvBuffer_.data(); if (recvBuffer_.size() < sizeof(packet_size) + packet_size) { required_data_size = sizeof(packet_size) + packet_size; @@ -594,8 +596,9 @@ - (void)onReadAvailable { [self close]; break; } - - recvBuffer_.erase(recvBuffer_.begin(), recvBuffer_.begin() + sizeof(packet_size) + packet_size); + + recvBuffer_.erase(recvBuffer_.begin(), + recvBuffer_.begin() + sizeof(packet_size) + packet_size); required_data_size = 0; state_ = WaitConnection; break; @@ -605,8 +608,7 @@ - (void)onReadAvailable { break; } - if (outputStream_.hasSpaceAvailable) - [self onWriteAvailable]; + if (outputStream_.hasSpaceAvailable) [self onWriteAvailable]; } - (void)onWriteAvailable { @@ -620,8 +622,8 @@ - (void)onWriteAvailable { } case ServerInfoToSend: { std::ostringstream ss; - ss << "[" << static_cast(tvm::runtime::TrackerCode::kUpdateInfo) << ", {\"key\": \"server:" << key_.UTF8String - << "\"}]"; + ss << "[" << static_cast(tvm::runtime::TrackerCode::kUpdateInfo) + << ", {\"key\": \"server:" << key_.UTF8String << "\"}]"; std::string data_s = ss.str(); NSData* data = [NSData dataWithBytes:data_s.data() length:data_s.length()]; [self toSendPacked:data]; @@ -631,15 +633,15 @@ - (void)onWriteAvailable { case ReportResToSend: { std::mt19937 gen(std::random_device{}()); std::uniform_real_distribution dis(0.0, 1.0); - + // TODO: All values are hardcoded int port = 9090; std::string custom_addr = "null"; std::string matchkey = std::string(key_.UTF8String) + ":" + std::to_string(dis(gen)); - + std::ostringstream ss; - ss << "[" << static_cast(tvm::runtime::TrackerCode::kPut) << ", \"" << key_.UTF8String << "\", [" << port - << ", \"" << matchkey << "\"], " << custom_addr << "]"; + ss << "[" << static_cast(tvm::runtime::TrackerCode::kPut) << ", \"" << key_.UTF8String + << "\", [" << port << ", \"" << matchkey << "\"], " << custom_addr << "]"; std::string data_s = ss.str(); NSData* data = [NSData dataWithBytes:data_s.data() length:data_s.length()]; @@ -651,12 +653,11 @@ - (void)onWriteAvailable { // Nothing break; } - - if (inputStream_.hasBytesAvailable) - [self onReadAvailable]; + + if (inputStream_.hasBytesAvailable) [self onReadAvailable]; } --(void)open { +- (void)open { // create RPC pure server // * set self as delegate (to register back when servicing is finished) // * mute printing status @@ -665,14 +666,13 @@ -(void)open { rpc_server_.key = key_; rpc_server_.delegate = self; [rpc_server_ open]; - + // Initialize the network. CFReadStreamRef readStream; CFWriteStreamRef writeStream; - CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)url_, port_, - &readStream, &writeStream); - + CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)url_, port_, &readStream, &writeStream); + inputStream_ = (NSInputStream*)readStream; outputStream_ = (NSOutputStream*)writeStream; [inputStream_ setDelegate:self]; @@ -693,12 +693,12 @@ - (void)onEndEvent { [self close]; } -- (void)onError:(NSString*) msg { +- (void)onError:(NSString*)msg { // transfer error form rpc_server_ to real delegate [self notifyError:msg]; } -- (void)onStatusChanged:(RPCServerStatus) status { +- (void)onStatusChanged:(RPCServerStatus)status { if (status == RPCServerStatus_RPCSessionFinished) { [self notifyState:status]; state_ = ReportResToSend; diff --git a/apps/ios_rpc/tvmrpc/ViewController.h b/apps/ios_rpc/tvmrpc/ViewController.h index 7f664074857e6..f634e60f959bf 100644 --- a/apps/ios_rpc/tvmrpc/ViewController.h +++ b/apps/ios_rpc/tvmrpc/ViewController.h @@ -25,7 +25,7 @@ #import "RPCServer.h" @interface ViewController : UIViewController { - RPCServer* server_; + RPCServer* server_; } @property(weak, nonatomic) IBOutlet UITextField* proxyURL; @@ -36,8 +36,8 @@ - (IBAction)connect:(id)sender; - (IBAction)disconnect:(id)sender; -@property (retain, nonatomic) IBOutlet UIButton *DisconnectButton; -@property (retain, nonatomic) IBOutlet UIButton *ConnectButton; -@property (retain, nonatomic) IBOutlet UISegmentedControl *ModeSelector; +@property(retain, nonatomic) IBOutlet UIButton* DisconnectButton; +@property(retain, nonatomic) IBOutlet UIButton* ConnectButton; +@property(retain, nonatomic) IBOutlet UISegmentedControl* ModeSelector; @end diff --git a/apps/ios_rpc/tvmrpc/ViewController.mm b/apps/ios_rpc/tvmrpc/ViewController.mm index e136fb08ee00e..d5b0149ce0e36 100644 --- a/apps/ios_rpc/tvmrpc/ViewController.mm +++ b/apps/ios_rpc/tvmrpc/ViewController.mm @@ -36,9 +36,9 @@ - (void)viewDidLoad { self.proxyURL.text = @(args.host_url); self.proxyPort.text = @(args.host_port).stringValue; self.proxyKey.text = @(args.key); - + self.ModeSelector.selectedSegmentIndex = args.server_mode; - + // Connect to tracker immediately if (args.immediate_connect) { [self disableUIInteraction]; @@ -74,7 +74,7 @@ - (void)open { [server_ startWithHost:self.proxyURL.text port:self.proxyPort.text.intValue key:self.proxyKey.text]; - + NSLog(@"Connecting to the proxy server..."); self.infoText.text = @""; self.statusLabel.text = @"Connecting..."; @@ -101,15 +101,14 @@ - (IBAction)disconnect:(id)sender { [self close]; } - #pragma mark - UITextFieldDelegate -- (BOOL)textFieldShouldReturn:(UITextField *)textField { +- (BOOL)textFieldShouldReturn:(UITextField*)textField { [[self view] endEditing:YES]; // to hide keyboard on ret key return FALSE; } -- (void)textFieldDidEndEditing:(UITextField *)textField { +- (void)textFieldDidEndEditing:(UITextField*)textField { // Update values in app arg cache RPCArgs args = get_current_rpc_args(); args.host_url = [self.proxyURL.text UTF8String]; @@ -118,16 +117,15 @@ - (void)textFieldDidEndEditing:(UITextField *)textField { set_current_rpc_args(args); } - #pragma mark - RPCServerEvenlListener -- (void)onError:(NSString*) msg { +- (void)onError:(NSString*)msg { dispatch_sync(dispatch_get_main_queue(), ^{ self.infoText.text = [NSString stringWithFormat:@"Error: %@", msg]; }); } -- (void)onStatusChanged:(RPCServerStatus) status { +- (void)onStatusChanged:(RPCServerStatus)status { dispatch_sync(dispatch_get_main_queue(), ^{ switch (status) { case RPCServerStatus_Connected: diff --git a/apps/ios_rpc/tvmrpc/rpc_args.h b/apps/ios_rpc/tvmrpc/rpc_args.h index 9bbf147cdadd8..e174da27f7753 100644 --- a/apps/ios_rpc/tvmrpc/rpc_args.h +++ b/apps/ios_rpc/tvmrpc/rpc_args.h @@ -29,18 +29,18 @@ extern "C" { */ typedef struct RPCArgs_t { const char* host_url; /// Tracker or Proxy address (actually ip) - int host_port; /// Tracker or Proxy port - + int host_port; /// Tracker or Proxy port + const char* key; /// device key to report - const char* custom_addr; /// custom adress to report into Tracker. Ignored for other server modes. - int port; /// begin of port range to try to bind RPC port - int port_end; /// end of port range to try to bind RPC port - + const char* + custom_addr; /// custom adress to report into Tracker. Ignored for other server modes. + int port; /// begin of port range to try to bind RPC port + int port_end; /// end of port range to try to bind RPC port + char immediate_connect; /// 0 - UI interaction, 1 - automatically connect on launch - char server_mode; /// 0 - connect to Tracker, 1 - connect to Proxy, 2 - pure RPC server + char server_mode; /// 0 - connect to Tracker, 1 - connect to Proxy, 2 - pure RPC server } RPCArgs; - /*! * \brief Get current global RPC args */ @@ -55,10 +55,10 @@ void set_current_rpc_args(RPCArgs args); * \brief Pars command line args and update current global RPC args * Also update values in app cache */ -void update_rpc_args(int argc, char * argv[]); +void update_rpc_args(int argc, char* argv[]); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif -#endif // TVM_APPS_IOS_RPC_ARGS_H_ +#endif // TVM_APPS_IOS_RPC_ARGS_H_ diff --git a/apps/ios_rpc/tvmrpc/rpc_args.mm b/apps/ios_rpc/tvmrpc/rpc_args.mm index 5194ab8f020fd..38ddf0488a000 100644 --- a/apps/ios_rpc/tvmrpc/rpc_args.mm +++ b/apps/ios_rpc/tvmrpc/rpc_args.mm @@ -21,50 +21,50 @@ #import -#import "../../../src/support/utils.h" #import "../../../src/support/socket.h" +#import "../../../src/support/utils.h" #import using std::string; -const char* kUsage = "\n" -"iOS tvmrpc application supported flags:\n" -"--host_url - The tracker/proxy address, Default=0.0.0.0\n" -"--host_port - The tracker/proxy port, Default=9190\n" -"--port - The port of the RPC, Default=9090\n" -"--port_end - The end search port of the RPC, Default=9099\n" -"--key - The key used to identify the device type in tracker. Default=\"\"\n" -"--custom_addr - Custom IP Address to Report to RPC Tracker. Default=\"\"\n" -"--immediate_connect - No UI interconnection, connect to tracker immediately. Default=False\n" -"--server_mode - Server mode. Can be \"pure_server\", \"proxy\" or \"tracker\". Default=pure_server \n" -"\n"; +const char* kUsage = + "\n" + "iOS tvmrpc application supported flags:\n" + "--host_url - The tracker/proxy address, Default=0.0.0.0\n" + "--host_port - The tracker/proxy port, Default=9190\n" + "--port - The port of the RPC, Default=9090\n" + "--port_end - The end search port of the RPC, Default=9099\n" + "--key - The key used to identify the device type in tracker. Default=\"\"\n" + "--custom_addr - Custom IP Address to Report to RPC Tracker. Default=\"\"\n" + "--immediate_connect - No UI interconnection, connect to tracker immediately. Default=False\n" + "--server_mode - Server mode. Can be \"pure_server\", \"proxy\" or \"tracker\". " + "Default=pure_server \n" + "\n"; struct RPCArgs_cpp { string host_url = "0.0.0.0"; int host_port = 9190; - + string key; string custom_addr = ""; int port = 9090; int port_end = 9099; - + bool immediate_connect = false; char server_mode = 0; - + operator RPCArgs() const { - return RPCArgs { - .host_url = host_url.c_str(), - .host_port = host_port, - .key = key.c_str(), - .custom_addr = custom_addr.c_str(), - .port = port, - .port_end = port_end, - .immediate_connect = immediate_connect, - .server_mode = server_mode - }; + return RPCArgs{.host_url = host_url.c_str(), + .host_port = host_port, + .key = key.c_str(), + .custom_addr = custom_addr.c_str(), + .port = port, + .port_end = port_end, + .immediate_connect = immediate_connect, + .server_mode = server_mode}; }; - + RPCArgs_cpp& operator=(const RPCArgs& args) { host_url = args.host_url; host_port = args.host_port; @@ -81,28 +81,29 @@ operator RPCArgs() const { struct RPCArgs_cpp g_rpc_args; static void restore_from_cache() { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - - auto get_string_from_cache = [defaults] (const char* key) { + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + + auto get_string_from_cache = [defaults](const char* key) { NSString* ns_key = [NSString stringWithUTF8String:key]; NSString* ns_val = [defaults stringForKey:ns_key]; return std::string(ns_val != nil ? [ns_val UTF8String] : ""); }; - - auto get_int_from_cache = [defaults] (const char* key) { + + auto get_int_from_cache = [defaults](const char* key) { NSString* ns_key = [NSString stringWithUTF8String:key]; return static_cast([defaults integerForKey:ns_key]); }; - + g_rpc_args.host_url = get_string_from_cache("tmvrpc_url"); g_rpc_args.host_port = get_int_from_cache("tmvrpc_port"); g_rpc_args.key = get_string_from_cache("tmvrpc_key"); } static void update_in_cache() { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - - [defaults setObject:[NSString stringWithUTF8String:g_rpc_args.host_url.c_str()] forKey:@"tmvrpc_url"]; + NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; + + [defaults setObject:[NSString stringWithUTF8String:g_rpc_args.host_url.c_str()] + forKey:@"tmvrpc_url"]; [defaults setInteger:g_rpc_args.host_port forKey:@"tmvrpc_port"]; [defaults setObject:[NSString stringWithUTF8String:g_rpc_args.key.c_str()] forKey:@"tmvrpc_key"]; } @@ -127,12 +128,12 @@ string GetCmdOption(int argc, char* argv[], string option, bool key = false) { void update_rpc_args(int argc, char* argv[]) { restore_from_cache(); - RPCArgs_cpp &args = g_rpc_args; - + RPCArgs_cpp& args = g_rpc_args; + using tvm::support::IsNumber; using tvm::support::ValidateIP; constexpr int MAX_PORT_NUM = 65535; - + const string immediate_connect = GetCmdOption(argc, argv, "--immediate_connect", true); if (!immediate_connect.empty()) { args.immediate_connect = true; @@ -207,13 +208,11 @@ void update_rpc_args(int argc, char* argv[]) { } args.custom_addr = '"' + custom_addr + '"'; } - + update_in_cache(); } -RPCArgs get_current_rpc_args(void) { - return g_rpc_args; -} +RPCArgs get_current_rpc_args(void) { return g_rpc_args; } void set_current_rpc_args(RPCArgs args) { g_rpc_args = args; diff --git a/apps/ios_rpc/tvmrpcLauncher/tvmrpcLauncher.mm b/apps/ios_rpc/tvmrpcLauncher/tvmrpcLauncher.mm index 85e60a324b18e..2efd1a8f72d6e 100644 --- a/apps/ios_rpc/tvmrpcLauncher/tvmrpcLauncher.mm +++ b/apps/ios_rpc/tvmrpcLauncher/tvmrpcLauncher.mm @@ -23,8 +23,8 @@ */ #import -#import "rpc_args.h" #import "RPCServer.h" +#import "rpc_args.h" @interface tvmrpcLauncher : XCTestCase @@ -34,16 +34,12 @@ @implementation tvmrpcLauncher - (void)testRPC { RPCArgs args = get_current_rpc_args(); - RPCServerMode server_mode = args.server_mode == 0 ? RPCServerMode_Tracker : - args.server_mode == 1 ? RPCServerMode_Proxy : - RPCServerMode_PureServer; - + RPCServerMode server_mode = static_cast(args.server_mode); + RPCServer* server_ = [RPCServer serverWithMode:server_mode]; RPCServer* server = [RPCServer serverWithMode:server_mode]; - [server startWithHost:@(args.host_url) - port:args.host_port - key:@(args.key)]; + [server startWithHost:@(args.host_url) port:args.host_port key:@(args.key)]; } @end