NDEVR
API Documentation
Connection.h
1/*--------------------------------------------------------------------------------------------
2Copyright (c) 2019, NDEVR LLC
3tyler.parke@ndevr.org
4 __ __ ____ _____ __ __ _______
5 | \ | | | __ \ | ___|\ \ / / | __ \
6 | \ | | | | \ \ | |___ \ \ / / | |__) |
7 | . \| | | |__/ / | |___ \ V / | _ /
8 | |\ |_|_____/__|_____|___\_/____| | \ \
9 |__| \__________________________________| \__\
10
11Subject to the terms of the Enterprise+ Agreement, NDEVR hereby grants
12Licensee a limited, non-exclusive, non-transferable, royalty-free license
13(without the right to sublicense) to use the API solely for the purpose of
14Licensee's internal development efforts to develop applications for which
15the API was provided.
16
17The above copyright notice and this permission notice shall be included in all
18copies or substantial portions of the Software.
19
20THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
21INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
22PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
23FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25DEALINGS IN THE SOFTWARE.
26
27Library: Hardware
28File: Connection
29Included in API: True
30Author(s): Tyler Parke
31 *-----------------------------------------------------------------------------------------**/
32#pragma once
33#include "DLLInfo.h"
34#include <NDEVR/SoftwareService.h>
35#include <NDEVR/Device.h>
36#include <NDEVR/String.h>
37#include <NDEVR/TimeSpan.h>
38#include <QObject>
39namespace NDEVR
40{
60
64 {
65 e_not_open = 0x0000,
66 e_read_only = 0x0001,
67 e_write_only = 0x0002,
69 e_append = 0x0004,
70 e_truncate = 0x0008,
71 e_text = 0x0010,
72 e_unbuffered = 0x0020,
73 e_new_only = 0x0040,
75 };
76
86
89 struct ConnectionInfo
90 {
91 ConnectionInfo() = default;
97 {
98 setID(id);
99 }
105 mutable LogPtr log;
107
112 String id() const
113 {
114 return type + "|" + address;
115 }
116
120 {
122 }
123
127 HARDWARE_API void setID(const StringView& id);
133 HARDWARE_API bool operator!=(const ConnectionInfo& other) const;
134 };
135
144
164
168 class HARDWARE_API ConnectionBackend : public QObject
169 {
170 Q_OBJECT
171 public:
183 virtual uint04 peek(char* s, uint04 size = Constant<uint04>::Max) const = 0;
190 virtual uint04 rx(char* s, uint04 max_size = Constant<uint04>::Max) = 0;
195 virtual void tx(const StringView& command) = 0;
201 virtual bool open(const ConnectionInfo& request) = 0;
205 virtual void close() = 0;
210 virtual bool isOpen() const = 0;
216 virtual bool waitForReadyRead(const TimeSpan& span) = 0;
221 virtual TranslatedString lastError() const = 0;
226 virtual uint04 bytesAvailable() const = 0;
231 virtual String threadID() const { return String(); };
232 signals:
242 protected:
244 };
245
307
315 class HARDWARE_API Connection : public Device
316 {
317 Q_OBJECT
318 public:
326 Connection(const Model& model, LogPtr raw_network_log = nullptr, LogPtr command_log = nullptr, QObject* parent = nullptr);
335 Connection(const ConnectionInfo& connection, const Model& model, LogPtr raw_network_log = nullptr, LogPtr command_log = nullptr, QObject* parent = nullptr);
336 virtual ~Connection();
342 const String& peek(uint04 size = Constant<uint04>::Invalid) const;
349 [[nodiscard]] Buffer<String> rx(char deliminator, uint04 size = Constant<uint04>::Invalid);
357 [[nodiscard]] Buffer<String> rx(char deliminator, const StringView& end_sequence, uint04 size = Constant<uint04>::Invalid);
363 const String& rx(uint04 size = Constant<uint04>::Invalid);
370 const String& rx(TimeSpan wait_time, uint04 size = Constant<uint04>::Invalid);
378 [[nodiscard]] const String& rxLine(TimeSpan wait_time, char delimeter = '\n', uint04 size = Constant<uint04>::Invalid);
383 virtual void tx(const StringView& data);
389 virtual void tx(const uint01* data, uint04 size);
394 virtual bool open();
400 virtual bool open(const ConnectionInfo& request);
404 virtual void close();
409 virtual void setConnectionInfo(const ConnectionInfo& request);
413 virtual void clearConnectionInfo();
418 [[nodiscard]] virtual bool isOpen() const;
423 [[nodiscard]] virtual const String& address() const { return m_connection_info.address; }
428 [[nodiscard]] virtual const String& type() const { return m_connection_info.type; }
433 void setRawDataLog(LogPtr raw_network_log);
442 [[nodiscard]] virtual String threadID() const;
448 [[nodiscard]] virtual bool canReadLine(char deliminator = '\n') const;
453 virtual void setTXDelay(const TimeSpan& tx_delay) { m_tx_delay = tx_delay; }
458 [[nodiscard]] LogPtr rawNetworkLog() { return m_raw_data_log; }
463 [[nodiscard]] Time lastRxTime() const { return m_last_rx; }
468 [[nodiscard]] Time lastTxTime() const { return m_last_tx; }
473 [[nodiscard]] const LogPtr rawNetworkLog() const { return m_raw_data_log; }
478 [[nodiscard]] const ConnectionInfo& connectionInfo() const { return m_connection_info; }
483 [[nodiscard]] ConnectionState connectionState() const;
488 [[nodiscard]] ConnectionBackend* ioDevice() const;
494 virtual bool waitForReadyRead(const TimeSpan& span);
499 virtual void setDefaultRxBufferSize(uint04 default_rx_buffer_size);
509 [[nodiscard]] virtual bool ping() const;
510 public:
517 [[nodiscard]] static bool Ping(const StringView& address, LogPtr log = nullptr);
525 [[nodiscard]] static bool Ping(const StringView& address, TimeSpan timeout, LogPtr log = nullptr);
534 [[nodiscard]] static bool Ping(const StringView& address, TimeSpan timeout, String& response, LogPtr log = nullptr);
540 static bool LogNetworkInfo(LogPtr log);
546 static bool LogIPInfo(LogPtr log);
547 protected:
552 virtual void setBackend(ConnectionBackend* device);
568 bool openBackend(ConnectionBackend* io_device, const ConnectionInfo& request);
569 public slots:
580 signals:
598 protected:
600 Buffer<std::function<void(const StringView&)>> m_tx_callback;
601 Buffer<std::function<void(const StringView&)>> m_rx_callback;
613 bool m_log_tx = true;
614 bool m_log_rx = true;
615 bool m_show_errors = false;
616 };
617}
The equivelent of std::vector but with a bit more control.
Definition Buffer.hpp:58
Provides the unseen backend logic for setting up, tearing down, and sending data over a specific type...
Definition Connection.h:169
virtual void tx(const StringView &command)=0
Transmits a string command over the connection.
virtual bool waitForReadyRead(const TimeSpan &span)=0
Blocks until data is available to read or the timeout expires.
ConnectionBackend(LogPtr log)
Constructs a ConnectionBackend with the given log.
void connectionStateChangedSignal(ConnectionState state)
Emitted when the connection state changes.
virtual void close()=0
Closes the connection.
void dataAvailableSignal()
Emitted when data is available to be read from the connection.
virtual bool open(const ConnectionInfo &request)=0
Opens the connection using the provided connection info.
virtual bool isOpen() const =0
Checks whether the connection is currently open.
virtual TranslatedString lastError() const =0
Returns the last error message from this backend.
virtual uint04 bytesAvailable() const =0
Returns the number of bytes available to read.
LogPtr m_log
Log for diagnostic messages.
Definition Connection.h:243
virtual uint04 rx(char *s, uint04 max_size=Constant< uint04 >::Max)=0
Reads and consumes data from the receive buffer.
virtual uint04 peek(char *s, uint04 size=Constant< uint04 >::Max) const =0
Reads data from the receive buffer without consuming it.
virtual String threadID() const
Returns the thread ID this backend must execute on, if any.
Definition Connection.h:231
Stores factories that can be registered for creating Connections of various types by instantiating a ...
Definition Connection.h:250
static Buffer< ConnectionCategory > AvailableConnectionCategories()
Returns all connection categories from all registered factories.
virtual bool handlesType(const StringView &request) const =0
Checks whether this factory handles the given connection type.
static void RegisterConnectionFactory(ConnectionFactory *factory)
Registers a ConnectionFactory so it can be used to create connections.
static Buffer< ConnectionInfo > AvailableConnections(const ConnectionSearchParameters &params)
Discovers available connections across all registered factories.
virtual bool canConnectTo(const ConnectionInfo &request) const
Checks whether this factory can establish a connection with the given info.
virtual Buffer< ConnectionCategory > availableConnectionCategories()=0
Returns the connection categories this factory supports.
virtual Buffer< ConnectionInfo > availableConnections(const ConnectionSearchParameters &params)=0
Discovers available connections matching the given search parameters.
virtual ConnectionBackend * createConnection(const ConnectionInfo &request)=0
Creates a new ConnectionBackend for the given connection info.
static ConnectionBackend * CreateConnection(const ConnectionInfo &request)
Creates a ConnectionBackend by searching all registered factories for one that handles the request.
static Buffer< ConnectionFactory * > s_registered_factories
All registered connection factories.
Definition Connection.h:305
virtual void setConnectionState(ConnectionState state)
Sets the connection state and emits the state changed signal.
virtual void close()
Closes the connection.
Buffer< std::function< void(const StringView &)> > m_tx_callback
Callbacks invoked on each transmit operation.
Definition Connection.h:600
ConnectionState connectionState() const
Returns the current connection state.
Time lastRxTime() const
Returns the timestamp of the last received data.
Definition Connection.h:463
static bool Ping(const StringView &address, TimeSpan timeout, String &response, LogPtr log=nullptr)
Pings an address with a custom timeout and captures the response.
ConnectionState m_connection_state
Current state of the connection.
Definition Connection.h:611
const ConnectionInfo & connectionInfo() const
Returns the current connection info.
Definition Connection.h:478
virtual bool waitForReadyRead(const TimeSpan &span)
Blocks until data is available to read or the timeout expires.
virtual bool canReadLine(char deliminator='\n') const
Checks whether a complete line is available in the receive buffer.
virtual const String & address() const
Returns the address of the current connection.
Definition Connection.h:423
virtual bool open(const ConnectionInfo &request)
Opens the connection using the provided connection info.
void setRawDataLog(LogPtr raw_network_log)
Sets the log used for raw network data.
bool m_show_errors
Whether to display errors to the user.
Definition Connection.h:615
Time m_last_tx
Timestamp of the last transmit operation.
Definition Connection.h:604
uint04 m_total_tx
Total number of bytes transmitted.
Definition Connection.h:608
ConnectionBackend * m_io_device
The underlying backend IO device.
Definition Connection.h:606
Connection(const Model &model, LogPtr raw_network_log=nullptr, LogPtr command_log=nullptr, QObject *parent=nullptr)
Constructs a Connection with the given model and optional logs.
bool m_log_rx
Whether to log received data.
Definition Connection.h:614
virtual void tx(const uint01 *data, uint04 size)
Transmits raw binary data over the connection.
virtual void clearConnectionInfo()
Clears the stored connection info.
virtual void setTXDelay(const TimeSpan &tx_delay)
Sets the delay to insert between successive transmit operations.
Definition Connection.h:453
Buffer< std::function< void(const StringView &)> > m_rx_callback
Callbacks invoked on each receive operation.
Definition Connection.h:601
void dataAvailableSignal()
Emitted when data is available to be read.
static bool LogIPInfo(LogPtr log)
Logs IP address information to the given log.
String m_connection_rx_buffer
Internal buffer for received data.
Definition Connection.h:602
void initConnection()
Initializes internal connection state and signal/slot wiring.
Connection(const ConnectionInfo &connection, const Model &model, LogPtr raw_network_log=nullptr, LogPtr command_log=nullptr, QObject *parent=nullptr)
Constructs a Connection with pre-configured connection info.
bool m_log_tx
Whether to log transmitted data.
Definition Connection.h:613
ConnectionBackend * ioDevice() const
Returns the underlying backend IO device.
virtual String threadID() const
Returns the thread ID this connection must execute on, if any.
const LogPtr rawNetworkLog() const
Returns the raw data log (const version).
Definition Connection.h:473
uint04 m_total_rx
Total number of bytes received.
Definition Connection.h:609
static bool Ping(const StringView &address, TimeSpan timeout, LogPtr log=nullptr)
Pings an address with a custom timeout.
virtual void setConnectionInfo(const ConnectionInfo &request)
Sets the connection info for this connection.
LogPtr m_raw_data_log
Log for raw network data.
Definition Connection.h:607
void connectSignal()
Emitted when the connection is opened.
Time m_last_rx
Timestamp of the last receive operation.
Definition Connection.h:603
void disconnectSignal()
Emitted when the connection is closed.
RawConnectionLoggingMode m_raw_logging_mode
Current raw data logging mode.
Definition Connection.h:612
ConnectionInfo m_connection_info
Stored connection parameters.
Definition Connection.h:599
const String & rx(TimeSpan wait_time, uint04 size=Constant< uint04 >::Invalid)
Receives data, waiting up to the specified time for data to arrive.
virtual bool ping() const
Sends a ping to the remote endpoint to check connectivity.
virtual void setBackend(ConnectionBackend *device)
Sets the backend IO device for this connection.
virtual const String & type() const
Returns the type of the current connection.
Definition Connection.h:428
virtual bool isOpen() const
Checks whether the connection is currently open.
Buffer< String > rx(char deliminator, uint04 size=Constant< uint04 >::Invalid)
Receives data split by a delimiter character.
Buffer< String > rx(char deliminator, const StringView &end_sequence, uint04 size=Constant< uint04 >::Invalid)
Receives data split by a delimiter, stopping at an end sequence.
const String & rx(uint04 size=Constant< uint04 >::Invalid)
Receives raw data up to the specified size.
void handleError()
Handles the last error from the backend by logging and updating state.
const String & rxLine(TimeSpan wait_time, char delimeter='\n', uint04 size=Constant< uint04 >::Invalid)
Receives a single line of data, delimited by the given character.
void connectionStateChangedSignal(ConnectionState state)
Emitted when the connection state changes.
virtual bool open()
Opens the connection using the currently stored connection info.
virtual void setDefaultRxBufferSize(uint04 default_rx_buffer_size)
Sets the default receive buffer size used when no explicit size is given.
const String & peek(uint04 size=Constant< uint04 >::Invalid) const
Reads data from the receive buffer without consuming it.
void setRawLoggingMode(RawConnectionLoggingMode mode)
Sets the logging mode for raw connection data.
Definition Connection.h:504
static bool LogNetworkInfo(LogPtr log)
Logs network interface information to the given log.
TimeSpan m_tx_delay
Delay inserted between successive transmissions.
Definition Connection.h:605
uint04 m_default_rx_buffer_size
Default receive buffer size in bytes.
Definition Connection.h:610
void writeConnectionLogMessage(const TranslatedString &message)
Writes a message to the connection log.
LogPtr rawNetworkLog()
Returns the raw data log.
Definition Connection.h:458
bool openBackend(ConnectionBackend *io_device, const ConnectionInfo &request)
Opens a backend connection with the given parameters.
static bool Ping(const StringView &address, LogPtr log=nullptr)
Pings an address with default timeout to check reachability.
Time lastTxTime() const
Returns the timestamp of the last transmitted data.
Definition Connection.h:468
virtual void tx(const StringView &data)
Transmits a string over the connection.
void handleErrorString(const TranslatedString &error)
Handles an error string by logging it and updating the connection state.
Device(const Model &model, LogPtr log, QObject *parent=nullptr)
Constructs a Device from a Model with the given log and optional Qt parent.
A light-weight wrapper that will be a no-op if there is not a valid log reference,...
A core class that represents a node on model hierarchy.
Definition Model.h:292
Vector< 3, fltp08 > size() const
Returns the size (extents) of the model's bounding box.
Software Service Managers take a Software service to modify the behavior of the software.
Base interface for services that extend or modify software behavior through modules.
The core String View class for the NDEVR API.
Definition StringView.h:58
The core String class for the NDEVR API.
Definition String.h:95
Stores a time span, or difference between two times, with an optional start time.
Definition TimeSpan.h:46
Represents a timestamp with utilities for manipulation and conversion.
Definition Time.h:62
Any text displayed to the user should be defined as a TranslatedString which allows the program to lo...
static TranslatedString DirectString(const StringView &sub_string)
If a string does not have a translation (EG: reading from an already translated string) this operatio...
The primary namespace for the NDEVR SDK.
uint32_t uint04
-Defines an alias representing a 4 byte, unsigned integer -Can represent exact integer values 0 throu...
RawConnectionLoggingMode
Connection can write to the log either as raw ascii bytes, or by converting those bytes into a binary...
Definition Connection.h:81
@ e_binary_logging
Raw data is converted to hex for logging.
Definition Connection.h:83
@ e_no_logging
Logging is disabled.
Definition Connection.h:82
@ e_ascii_logging
Raw data is logged as ASCII text.
Definition Connection.h:84
@ e_append
Appends the specified value(s) to a multiString registry key.
uint8_t uint01
-Defines an alias representing a 1 byte, unsigned integer -Can represent exact integer values 0 throu...
ConnectionState
Describes the state of the connection.
Definition Connection.h:45
@ e_attempting_connection
Currently attempting to establish a connection.
Definition Connection.h:49
@ e_network_error
A general network error occurred.
Definition Connection.h:54
@ e_no_response
No response was received within the expected time.
Definition Connection.h:51
@ e_invalid_connection
The connection is in an invalid state.
Definition Connection.h:58
@ e_connection_timeout
The connection attempt timed out.
Definition Connection.h:57
@ e_invalid_response
A response was received but was not valid.
Definition Connection.h:50
@ e_access_to_port_denied
Access to the requested port was denied.
Definition Connection.h:53
@ e_resetting
The connection is being reset.
Definition Connection.h:55
@ e_valid_connection
A valid, active connection is established.
Definition Connection.h:47
@ e_awaiting_response
Waiting for a response from the remote endpoint.
Definition Connection.h:48
@ e_no_services
No services are available on the remote endpoint.
Definition Connection.h:52
@ e_no_connection
No connection has been established.
Definition Connection.h:46
@ e_initializing
The gyroscope is currently initializing.
ConnectionOpenType
Describes how to open a connection.
Definition Connection.h:64
@ e_write_only
Open for writing only.
Definition Connection.h:67
@ e_text
Open in text mode.
Definition Connection.h:71
@ e_new_only
Only open if the connection is new.
Definition Connection.h:73
@ e_truncate
Truncate existing data on open.
Definition Connection.h:70
@ e_existing_only
Only open if the connection already exists.
Definition Connection.h:74
@ e_unbuffered
Disable buffering.
Definition Connection.h:72
@ e_read_only
Open for reading only.
Definition Connection.h:66
@ e_read_write
Open for both reading and writing.
Definition Connection.h:68
@ e_not_open
Connection is not open.
Definition Connection.h:65
A category represents the type of connection.
Definition Connection.h:139
String icon
Icon resource name associated with this category.
Definition Connection.h:142
TranslatedString name
Human-readable display name of the connection category.
Definition Connection.h:140
String id
Unique identifier for this connection category.
Definition Connection.h:141
A structure designed to store information about a specific Connection.
Definition Connection.h:90
ConnectionInfo(const StringView &id)
Constructs a ConnectionInfo by parsing a combined type|address identifier.
Definition Connection.h:96
LogPtr log
Log used for connection diagnostics.
Definition Connection.h:105
TranslatedString name
Human-readable display name for the connection.
Definition Connection.h:100
String thread_id
If set, connection must be executed on a specific thread.
Definition Connection.h:106
bool operator!=(const ConnectionInfo &other) const
Inequality comparison operator.
void setID(const StringView &id)
Parses a combined "type|address" string and sets the type and address fields.
TimeSpan max_timeout
Maximum time to wait for a connection before timing out.
Definition Connection.h:104
void autoSetName()
Automatically sets the display name from the connection identifier.
Definition Connection.h:119
String id() const
Returns a unique identifier string combining the type and address.
Definition Connection.h:112
ConnectionOpenType connect_mode
The mode in which to open the connection.
Definition Connection.h:103
String type
The connection type (e.g., "serial", "tcp", "bluetooth").
Definition Connection.h:101
String address
The address or port of the connection.
Definition Connection.h:102
Describes settings for performing a Connection search.
Definition Connection.h:149
LogPtr log
Log for search diagnostics.
Definition Connection.h:161
TimeSpan timeout
Maximum duration to search before stopping.
Definition Connection.h:162
SearchReturn
The return value from a search callback, indicating whether to continue or stop.
Definition Connection.h:154
@ e_stop_searching
Stop the search immediately.
Definition Connection.h:156
@ e_continue_searching
Continue scanning for more connections.
Definition Connection.h:155
Buffer< ConnectionCategory > allowed_categories
Categories to include in the search. Empty means all categories.
Definition Connection.h:158
std::function< SearchReturn(const ConnectionInfo &)> on_service_found
Callback invoked when a service is discovered.
Definition Connection.h:160
std::function< SearchReturn(const ConnectionInfo &)> on_device_found
Callback invoked when a device is discovered.
Definition Connection.h:159