#import "ViewController.h"
@import UniPRT;
@interface ViewController ()
@property (strong)
TcpComm *tcpComm;
@property (nonatomic, strong) UITextField *ipTextField;
@property (nonatomic, strong) UITextView *resultTextView;
@property (nonatomic, strong) UIButton *openButton;
@property (nonatomic, strong) UIButton *writeButton;
@property (nonatomic, strong) UIButton *readButton;
@property (nonatomic, strong) UIButton *connectCloseButton;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIButton *connectWriteAndWaitForResponseButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.ipTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 50, 200, 30)];
self.ipTextField.placeholder = @"Enter IP Address";
self.ipTextField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.ipTextField];
self.ipTextField.text = @"10.0.10.170";
self.resultTextView = [[UITextView alloc] initWithFrame:CGRectMake(20, 150, 300, 200)];
self.resultTextView.editable = NO;
self.resultTextView.layer.borderWidth = 1.0;
self.resultTextView.layer.borderColor = [[UIColor blackColor] CGColor];
[self.view addSubview:self.resultTextView];
self.openButton = [self createButtonWithTitle:@"Open" frame:CGRectMake(20, 370, 80, 30)];
self.openButton.backgroundColor = [UIColor redColor];
[self.openButton addTarget:self action:@selector(openButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.openButton];
self.writeButton = [self createButtonWithTitle:@"Write" frame:CGRectMake(120, 370, 80, 30)];
self.writeButton.backgroundColor = [UIColor redColor];
[self.writeButton addTarget:self action:@selector(writeButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.writeButton];
self.readButton = [self createButtonWithTitle:@"Read" frame:CGRectMake(220, 370, 80, 30)];
self.readButton.backgroundColor = [UIColor redColor];
[self.readButton addTarget:self action:@selector(readButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.readButton];
self.connectCloseButton = [self createButtonWithTitle:@"Connect" frame:CGRectMake(20, 420, 120, 30)];
self.connectCloseButton.backgroundColor = [UIColor redColor];
[self.connectCloseButton addTarget:self action:@selector(connectCloseButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.connectCloseButton];
self.connectWriteAndWaitForResponseButton = [self createButtonWithTitle:@"writeAndWaitForResponse" frame:CGRectMake(20, 470, 300, 30)];
self.connectWriteAndWaitForResponseButton.backgroundColor = [UIColor redColor];
[self.connectWriteAndWaitForResponseButton addTarget:self action:@selector(writeAndWaitForResponseButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.connectWriteAndWaitForResponseButton];
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 600, 600, 200)];
self.textView.font = [UIFont systemFontOfSize:17];
self.textView.layer.borderWidth = 1.0;
self.textView.layer.borderColor = [[UIColor blackColor] CGColor];
self.textView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
self.textView.returnKeyType = UIReturnKeyDone;
self.textView.delegate = self;
self.textView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);
self.textView.backgroundColor = [UIColor whiteColor];
self.textView.scrollEnabled = YES;
self.textView.showsVerticalScrollIndicator = YES;
[self.view addSubview:self.textView];
}
- (UIButton *)createButtonWithTitle:(NSString *)title frame:(CGRect)frame {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = frame;
[button setTitle:title forState:UIControlStateNormal];
return button;
}
- (void)openButtonPressed {
[self.tcpComm open];
}
- (void)writeButtonPressed {
NSString *writeData = self.textView.text;
NSData *textData = [writeData dataUsingEncoding:NSUTF8StringEncoding];
[self.tcpComm write:textData];
}
- (void)readButtonPressed {
NSData *textData = [self.tcpComm read];
NSString *receivedString = [[NSString alloc] initWithData:textData encoding:NSUTF8StringEncoding];
self.resultTextView.text = receivedString;
}
- (void)connectCloseButtonPressed {
NSString *currentTitle = [self.connectCloseButton titleForState:UIControlStateNormal];
if ([currentTitle isEqualToString:@"Connect"]) {
NSString *ipAddress = self.ipTextField.text;
self.tcpComm = [[
TcpComm alloc] initWithIPAddress:ipAddress port:DEFAULT_DATA_PORT];
[self.connectCloseButton setTitle:@"Close" forState:UIControlStateNormal];
} else if ([currentTitle isEqualToString:@"Close"]) {
[self.tcpComm close];
[self.connectCloseButton setTitle:@"Connect" forState:UIControlStateNormal];
}
}
- (void)writeAndWaitForResponseButtonPressed {
NSString *strdata = self.textView.text;
NSData *decodedata = [strdata dataUsingEncoding:NSUTF8StringEncoding];
NSData *textData = [self.tcpComm writeAndWaitForResponse:decodedata responseStartTimeOut:3000 responseEndTimeOut:3000 completionToken:@"\r\n"];
NSString *receivedString = [[NSString alloc] initWithData:textData encoding:NSUTF8StringEncoding];
self.resultTextView.text = receivedString;
}
@end
一个用于 TCP 通信的类,继承自 AComm 并符合 NSStreamDelegate 协议。
Definition TcpComm.h:101
import SwiftUI
import UniPRT
struct ContentView: View {
@State private var ipText = "10.0.10.178"
@State private var macAddressText = "34:81:F4:43:3D:A8"
@State private var resultText = ""
@State private var communicationType = 0 // 0 for TCP
@State private var inputText = ""
@StateObject private var viewModel = CommunicationViewModel()
var body: some View {
NavigationView {
Form {
Section(header: Text("Connection Type")) {
Picker("Select Type", selection: $communicationType) {
Text("TCP").tag(0)
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("IP Address")) {
TextField("Enter IP Address", text: $ipText)
.keyboardType(.decimalPad)
}
Section(header: Text("Input")) {
TextEditor(text: $inputText)
.keyboardType(.asciiCapable)
.frame(height: 100) // 設置高度
.border(Color.secondary, width: 1) // 設置邊框
}
Section(header: Text("Output")) {
ScrollView {
Text(resultText)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(height: 100)
.border(Color.secondary, width: 1)
}
Button("Connect/Close") {
resultText = viewModel.connectCloseAction(ip: ipText)
}
Button("Open") {
resultText = viewModel.openAction()
}
Button("Write") {
resultText = viewModel.writeAction(stringData: inputText)
}
Button("Write and Wait for Response") {
resultText = viewModel.writeAndWaitForResponseAction(stringData: inputText)
}
Button("Read") {
resultText = viewModel.readAction()
}
}
.navigationBarTitle("Communication")
}
}
}
class CommunicationViewModel: ObservableObject {
@Published var resultText = ""
var tcpComm: TcpComm?
func openAction() -> String {
self.resultText = "open error"
tcpComm?.open()
self.resultText = "TCP Connection opened"
return self.resultText
}
func writeAction(stringData: String) -> String {
self.resultText = "write Error"
tcpComm?.write(stringData.data(using: .utf8))
self.resultText = "TCP Data written"
return self.resultText
}
func readAction() -> String {
if let data = tcpComm?.read() {
self.resultText = String(data: data, encoding: .utf8) ?? "Failed to decode data"
} else {
self.resultText = "Error Occured."
}
return self.resultText
}
func connectCloseAction(ip: String) -> String {
self.resultText = "connect error"
print(ip)
if tcpComm != nil {
tcpComm?.close()
tcpComm = nil
self.resultText = "TCP Connection closed"
} else {
// Reconnect logic
tcpComm = TcpComm(ipAddress: ip, port: 9100)
self.resultText = "TCP Reconnected"
}
return self.resultText
}
func writeAndWaitForResponseAction(stringData: String) -> String {
if let response = tcpComm?.writeAndWait(forResponse: stringData.data(using: .utf8), responseStartTimeOut: 3000, responseEndTimeOut: 3000, completionToken: "\r\n") {
self.resultText = String(data: response, encoding: .utf8) ?? "Failed to decode response"
} else {
self.resultText = "Error Occured."
}
return self.resultText
}
}
#Preview {
ContentView()
}