UniPRT SDK v1.0.0.0
 
Loading...
Searching...
No Matches
Comm

Classes and methods related to Comm. More...

Classes

class  AComm
 A base class for communication interfaces, conforming to the IComm protocol. More...
 
protocol  <IComm>
 A protocol defining the interface for communication classes. More...
 
class  TcpComm
 A class for TCP communication, inheriting from AComm and conforming to the NSStreamDelegate protocol. More...
 

Detailed Description

Classes and methods related to Comm.

For the Objective-C example, see here.

For the Swift example, see here.

Example

Objective-C:

#import "AppDelegate.h"
@import UniPRT;
@interface AppDelegate ()
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// create window
NSRect frame = NSMakeRect(0, 0, 600, 700);
self.window = [[NSWindow alloc] initWithContentRect:frame
styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable)
backing:NSBackingStoreBuffered
defer:NO];
[self.window setTitle:@"Comm Example"];
[self.window makeKeyAndOrderFront:nil];
// initialize the check box.
self.tcpCheckBox = [self createCheckBoxWithTitle:@"TCP/IP" action:@selector(checkBoxChanged:) frame:NSMakeRect(self.window.frame.size.width - 100, self.window.frame.size.height - 90, 80, 20)];
[self.window.contentView addSubview:self.tcpCheckBox];
// create tcp input field.
self.tcpIpInputField = [[NSTextField alloc] initWithFrame:NSMakeRect(20, self.window.frame.size.height - 150, 200, 22)];
[self.tcpIpInputField setPlaceholderString:@"Enter TCP/IP Address"];
[self.window.contentView addSubview:self.tcpIpInputField];
self.tcpIpInputField.stringValue = @"10.0.10.180";
// create label
self.label = [[NSTextField alloc] initWithFrame:NSMakeRect(20, 60, 200, 80)];
[self.label setStringValue:@"received message"];
[self.label setEditable:NO];
[self.label setBezeled:NO];
[self.label setDrawsBackground:NO];
[self.window.contentView addSubview:self.label];
// create NSTextView
self.textView = [[NSTextView alloc] initWithFrame:NSMakeRect(20, 150, 400, 80)];
self.textView.minSize = NSMakeSize(0.0, self.textView.frame.size.height);
self.textView.maxSize = NSMakeSize(FLT_MAX, FLT_MAX);
self.textView.verticallyResizable = YES;
self.textView.horizontallyResizable = NO;
self.textView.autoresizingMask = NSViewWidthSizable;
[[self.textView textContainer] setContainerSize:NSMakeSize(self.textView.frame.size.width, FLT_MAX)];
[[self.textView textContainer] setWidthTracksTextView:YES];
[self.window.contentView addSubview:self.textView];
// create button
NSButton *button1 = [[NSButton alloc] initWithFrame:NSMakeRect(450, 200, 90, 30)];
[button1 setTitle:@"send"];
[button1 setTarget:self];
[button1 setAction:@selector(writeTcp:)];
[self.window.contentView addSubview:button1];
// create button
NSButton *button2 = [[NSButton alloc] initWithFrame:NSMakeRect(450, 500, 90, 30)];
[button2 setTitle:@"connect"];
[button2 setTarget:self];
[button2 setAction:@selector(toggleTcpConnection:)];
[self.window.contentView addSubview:button2];
self.openButton = button2;
// create button
NSButton *buttonCloseTcp = [[NSButton alloc] initWithFrame:NSMakeRect(450, 110, 90, 30)];
[buttonCloseTcp setTitle:@"close"];
[buttonCloseTcp setTarget:self];
[buttonCloseTcp setAction:@selector(closeTcp:)];
[self.window.contentView addSubview:buttonCloseTcp];
// create button
NSButton *readButton = [[NSButton alloc] initWithFrame:NSMakeRect(450, 140, 90, 30)];
[readButton setTitle:@"Read"];
[readButton setTarget:self];
[readButton setAction:@selector(readTcp:)];
[self.window.contentView addSubview:readButton];
// create button
NSButton *writeAndWaitButtonTcp = [[NSButton alloc] initWithFrame:NSMakeRect(450, 170, 90, 30)];
[writeAndWaitButtonTcp setTitle:@"writeandwait"];
[writeAndWaitButtonTcp setTarget:self];
[writeAndWaitButtonTcp setAction:@selector(writeAndWaitForResponseTcp:)];
[self.window.contentView addSubview:writeAndWaitButtonTcp];
// initialize the reference button
self.openButton = button2;
self.readButton = readButton;
self.writeButton = button1;
self.closeButton = buttonCloseTcp;
self.writeAndWaitButton = writeAndWaitButtonTcp;
}
- (NSButton *)createCheckBoxWithTitle:(NSString *)title action:(SEL)action frame:(NSRect)frame {
NSButton *checkBox = [[NSButton alloc] initWithFrame:frame];
[checkBox setButtonType:NSButtonTypeSwitch];
[checkBox setTitle:title];
[checkBox setTarget:self];
[checkBox setAction:action];
return checkBox;
}
- (void)checkBoxChanged:(id)sender {
NSLog(@"checkBoxChanged triggered");
// Reset the states of the checkbox
[self.openButton setTitle:@"Connect"];
if (self.tcpCheckBox.state == NSControlStateValueOn) {
NSLog(@"TCP checkbox changed");
self.openButton.action = @selector(toggleTcpConnection:);
self.readButton.action = @selector(readTcp:);
self.writeButton.action = @selector(writeTcp:);
self.closeButton.action = @selector(closeTcp:);
self.writeAndWaitButton.action = @selector(writeAndWaitForResponseTcp:);
}
}
// Define toggle methods for TCP
- (void)toggleTcpConnection:(NSButton *)sender {
if ([sender.title isEqualToString:@"Connect"]) {
[self openTcp:sender];
[sender setTitle:@"Close"];
} else {
[self closeTcp:sender];
[sender setTitle:@"Connect"];
}
}
// TCP Methods
- (void)openTcp:(id)sender {
NSString *ipAddress = self.tcpIpInputField.stringValue;
if (ipAddress.length > 0) {
self.tcpComm = [[TcpComm alloc] initWithIPAddress:ipAddress port:DEFAULT_DATA_PORT];
[self.tcpComm open];
} else {
NSLog(@"TCP/IP address is empty.");
}
}
- (void)closeTcp:(id)sender {
[self.tcpComm close];
}
- (void)writeTcp:(id)sender {
NSString *text = [self.textView string];
NSData *textData = [text dataUsingEncoding:NSUTF8StringEncoding];
[self.tcpComm write:textData];
}
- (IBAction)readTcp:(id)sender {
NSData *receivedData = [self.tcpComm read];
NSString *receivedString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
[self.label setStringValue:receivedString];
}
- (IBAction)writeAndWaitForResponseTcp:(id)sender {
NSString *text = [self.textView string];
NSData *textData = [text dataUsingEncoding:NSUTF8StringEncoding];
NSString *token = @"\r\n";
NSData *result = [self.tcpComm writeAndWaitForResponse:textData responseStartTimeOut:5000 responseEndTimeOut:5000 completionToken:token];
NSString *receivedString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
[self.label setStringValue:receivedString];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app {
return YES;
}
- (void)openT:(id)sender {
}
- (void)openUsb:(id)sender {
}
- (void)readT:(id)sender __attribute__((ibaction)) {
}
- (void)readUsb:(id)sender __attribute__((ibaction)) {
}
- (void)writeAndWaitForResponseUsb:(id)sender __attribute__((ibaction)) {
}
- (void)writeT:(id)sender {
}
- (void)writeUsb:(id)sender {
}
@end
A class for TCP communication, inheriting from AComm and conforming to the NSStreamDelegate protocol.
Definition TcpComm.h:101

Swift:

import SwiftUI
import UniPRT
struct ContentView: View {
@State private var ipText = "10.0.10.178"
@State private var resultText = ""
@State private var communicationType = 0
@State private var inputText = ""
@StateObject private var viewModel = CommunicationViewModel()
var body: some View {
NavigationSplitView {
// Sidebar section
VStack {
Text("Communication Type")
.font(.title)
.padding()
Picker("Select Type", selection: $communicationType) {
Text("TCP").tag(0)
}
.pickerStyle(SegmentedPickerStyle())
.padding()
TextField("Enter IP Address", text: $ipText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}
.font(.title)
.padding()
.background(Color.blue)
.cornerRadius(10)
} detail: {
// Detail section
ScrollView {
VStack(alignment: .leading) {
TextEditor(text: $inputText)
.frame(height: 100)
.border(Color.secondary, width: 1)
ScrollView {
Text(resultText)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(height: 100)
.border(Color.secondary, width: 1)
HStack {
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()
}
}
.buttonStyle(BorderlessButtonStyle())
}
.padding()
}
}
.frame(minWidth: 800, minHeight: 600)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
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"
return self.resultText
}
return "Error Occured."
}
func connectCloseAction(ip: String) -> String {
self.resultText = "connect error"
if tcpComm != nil {
tcpComm?.close()
tcpComm = nil
self.resultText = "TCP Connection closed"
} else {
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"
return self.resultText
}
return "Error Occured."
}
}
#Preview {
ContentView()
}