WPILibC++ 2025.2.1
Loading...
Searching...
No Matches
NetworkTableInstance.h
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#pragma once
6
7#include <memory>
8#include <optional>
9#include <span>
10#include <string_view>
11#include <utility>
12#include <vector>
13
15#include <wpi/struct/Struct.h>
16
19#include "ntcore_c.h"
20#include "ntcore_cpp.h"
21
22namespace nt {
23
24class BooleanArrayTopic;
25class BooleanTopic;
26class DoubleArrayTopic;
27class DoubleTopic;
28class FloatArrayTopic;
29class FloatTopic;
30class IntegerArrayTopic;
31class IntegerTopic;
32class MultiSubscriber;
33template <wpi::ProtobufSerializable T>
34class ProtobufTopic;
35class RawTopic;
36class StringArrayTopic;
37class StringTopic;
38template <typename T, typename... I>
39 requires wpi::StructSerializable<T, I...>
40class StructArrayTopic;
41template <typename T, typename... I>
42 requires wpi::StructSerializable<T, I...>
43class StructTopic;
44class Subscriber;
45class Topic;
46
47/**
48 * NetworkTables Instance.
49 *
50 * Instances are completely independent from each other. Table operations on
51 * one instance will not be visible to other instances unless the instances are
52 * connected via the network. The main limitation on instances is that you
53 * cannot have two servers on the same network port. The main utility of
54 * instances is for unit testing, but they can also enable one program to
55 * connect to two different NetworkTables networks.
56 *
57 * The global "default" instance (as returned by GetDefault()) is
58 * always available, and is intended for the common case when there is only
59 * a single NetworkTables instance being used in the program. The
60 * default instance cannot be destroyed.
61 *
62 * Additional instances can be created with the Create() function.
63 * Instances are not reference counted or RAII. Instead, they must be
64 * explicitly destroyed (with Destroy()).
65 *
66 * @ingroup ntcore_cpp_api
67 */
69 public:
70 /**
71 * Client/server mode flag values (as returned by GetNetworkMode()).
72 * This is a bitmask.
73 */
81
82 /**
83 * Logging levels (as used by SetLogger()).
84 */
96
97 /**
98 * The default port that network tables operates on for NT3.
99 */
100 static constexpr unsigned int kDefaultPort3 = NT_DEFAULT_PORT3;
101
102 /**
103 * The default port that network tables operates on for NT4.
104 */
105 static constexpr unsigned int kDefaultPort4 = NT_DEFAULT_PORT4;
106
107 /**
108 * Construct invalid instance.
109 */
110 NetworkTableInstance() noexcept = default;
111
112 /**
113 * Construct from native handle.
114 *
115 * @param handle Native handle
116 */
117 explicit NetworkTableInstance(NT_Inst handle) noexcept : m_handle{handle} {}
118
119 /**
120 * Determines if the native handle is valid.
121 *
122 * @return True if the native handle is valid, false otherwise.
123 */
124 explicit operator bool() const { return m_handle != 0; }
125
126 /**
127 * Get global default instance.
128 *
129 * @return Global default instance
130 */
134
135 /**
136 * Create an instance.
137 *
138 * @return Newly created instance
139 */
143
144 /**
145 * Destroys an instance (note: this has global effect).
146 *
147 * @param inst Instance
148 */
149 static void Destroy(NetworkTableInstance& inst) {
150 if (inst.m_handle != 0) {
151 DestroyInstance(inst.m_handle);
152 inst.m_handle = 0;
153 }
154 }
155
156 /**
157 * Gets the native handle for the entry.
158 *
159 * @return Native handle
160 */
161 NT_Inst GetHandle() const { return m_handle; }
162
163 /**
164 * Gets a "generic" (untyped) topic.
165 *
166 * @param name topic name
167 * @return Topic
168 */
169 Topic GetTopic(std::string_view name) const;
170
171 /**
172 * Gets a boolean topic.
173 *
174 * @param name topic name
175 * @return Topic
176 */
177 BooleanTopic GetBooleanTopic(std::string_view name) const;
178
179 /**
180 * Gets an integer topic.
181 *
182 * @param name topic name
183 * @return Topic
184 */
185 IntegerTopic GetIntegerTopic(std::string_view name) const;
186
187 /**
188 * Gets a float topic.
189 *
190 * @param name topic name
191 * @return Topic
192 */
193 FloatTopic GetFloatTopic(std::string_view name) const;
194
195 /**
196 * Gets a double topic.
197 *
198 * @param name topic name
199 * @return Topic
200 */
201 DoubleTopic GetDoubleTopic(std::string_view name) const;
202
203 /**
204 * Gets a string topic.
205 *
206 * @param name topic name
207 * @return Topic
208 */
209 StringTopic GetStringTopic(std::string_view name) const;
210
211 /**
212 * Gets a raw topic.
213 *
214 * @param name topic name
215 * @return Topic
216 */
217 RawTopic GetRawTopic(std::string_view name) const;
218
219 /**
220 * Gets a boolean array topic.
221 *
222 * @param name topic name
223 * @return Topic
224 */
225 BooleanArrayTopic GetBooleanArrayTopic(std::string_view name) const;
226
227 /**
228 * Gets an integer array topic.
229 *
230 * @param name topic name
231 * @return Topic
232 */
233 IntegerArrayTopic GetIntegerArrayTopic(std::string_view name) const;
234
235 /**
236 * Gets a float array topic.
237 *
238 * @param name topic name
239 * @return Topic
240 */
241 FloatArrayTopic GetFloatArrayTopic(std::string_view name) const;
242
243 /**
244 * Gets a double array topic.
245 *
246 * @param name topic name
247 * @return Topic
248 */
249 DoubleArrayTopic GetDoubleArrayTopic(std::string_view name) const;
250
251 /**
252 * Gets a string array topic.
253 *
254 * @param name topic name
255 * @return Topic
256 */
257 StringArrayTopic GetStringArrayTopic(std::string_view name) const;
258
259 /**
260 * Gets a protobuf serialized value topic.
261 *
262 * @param name topic name
263 * @return Topic
264 */
265 template <wpi::ProtobufSerializable T>
266 ProtobufTopic<T> GetProtobufTopic(std::string_view name) const {
267 return ProtobufTopic<T>{GetTopic(name)};
268 }
269
270 /**
271 * Gets a raw struct serialized value topic.
272 *
273 * @param name topic name
274 * @param info optional struct type info
275 * @return Topic
276 */
277 template <typename T, typename... I>
278 requires wpi::StructSerializable<T, I...>
279 StructTopic<T, I...> GetStructTopic(std::string_view name, I... info) const {
280 return StructTopic<T, I...>{GetTopic(name), std::move(info)...};
281 }
282
283 /**
284 * Gets a raw struct serialized array topic.
285 *
286 * @param name topic name
287 * @param info optional struct type info
288 * @return Topic
289 */
290 template <typename T, typename... I>
291 requires wpi::StructSerializable<T, I...>
292 StructArrayTopic<T, I...> GetStructArrayTopic(std::string_view name,
293 I... info) const {
294 return StructArrayTopic<T, I...>{GetTopic(name), std::move(info)...};
295 }
296
297 /**
298 * Get Published Topics.
299 *
300 * Returns an array of topics.
301 *
302 * @return Array of topics.
303 */
304 std::vector<Topic> GetTopics() {
305 auto handles = ::nt::GetTopics(m_handle, "", 0);
306 return {handles.begin(), handles.end()};
307 }
308
309 /**
310 * Get Published Topics.
311 *
312 * Returns an array of topics. The results are filtered by
313 * string prefix to only return a subset of all topics.
314 *
315 * @param prefix name required prefix; only topics whose name
316 * starts with this string are returned
317 * @return Array of topics.
318 */
319 std::vector<Topic> GetTopics(std::string_view prefix) {
320 auto handles = ::nt::GetTopics(m_handle, prefix, 0);
321 return {handles.begin(), handles.end()};
322 }
323
324 /**
325 * Get Published Topics.
326 *
327 * Returns an array of topics. The results are filtered by
328 * string prefix and type to only return a subset of all topics.
329 *
330 * @param prefix name required prefix; only topics whose name
331 * starts with this string are returned
332 * @param types bitmask of NT_Type values; 0 is treated specially
333 * as a "don't care"
334 * @return Array of topics.
335 */
336 std::vector<Topic> GetTopics(std::string_view prefix, unsigned int types) {
337 auto handles = ::nt::GetTopics(m_handle, prefix, types);
338 return {handles.begin(), handles.end()};
339 }
340
341 /**
342 * Get Published Topics.
343 *
344 * Returns an array of topics. The results are filtered by
345 * string prefix and type to only return a subset of all topics.
346 *
347 * @param prefix name required prefix; only topics whose name
348 * starts with this string are returned
349 * @param types array of type strings
350 * @return Array of topic handles.
351 */
352 std::vector<Topic> GetTopics(std::string_view prefix,
353 std::span<std::string_view> types) {
354 auto handles = ::nt::GetTopics(m_handle, prefix, types);
355 return {handles.begin(), handles.end()};
356 }
357
358 /**
359 * Get Topic Information about multiple topics.
360 *
361 * Returns an array of topic information (handle, name, type, and properties).
362 *
363 * @return Array of topic information.
364 */
365 std::vector<TopicInfo> GetTopicInfo() {
366 return ::nt::GetTopicInfo(m_handle, "", 0);
367 }
368
369 /**
370 * Get Topic Information about multiple topics.
371 *
372 * Returns an array of topic information (handle, name, type, and properties).
373 * The results are filtered by string prefix to only
374 * return a subset of all topics.
375 *
376 * @param prefix name required prefix; only topics whose name
377 * starts with this string are returned
378 * @return Array of topic information.
379 */
380 std::vector<TopicInfo> GetTopicInfo(std::string_view prefix) {
381 return ::nt::GetTopicInfo(m_handle, prefix, 0);
382 }
383
384 /**
385 * Get Topic Information about multiple topics.
386 *
387 * Returns an array of topic information (handle, name, type, and properties).
388 * The results are filtered by string prefix and type to only
389 * return a subset of all topics.
390 *
391 * @param prefix name required prefix; only topics whose name
392 * starts with this string are returned
393 * @param types bitmask of NT_Type values; 0 is treated specially
394 * as a "don't care"
395 * @return Array of topic information.
396 */
397 std::vector<TopicInfo> GetTopicInfo(std::string_view prefix,
398 unsigned int types) {
399 return ::nt::GetTopicInfo(m_handle, prefix, types);
400 }
401
402 /**
403 * Get Topic Information about multiple topics.
404 *
405 * Returns an array of topic information (handle, name, type, and properties).
406 * The results are filtered by string prefix and type to only
407 * return a subset of all topics.
408 *
409 * @param prefix name required prefix; only topics whose name
410 * starts with this string are returned
411 * @param types array of type strings
412 * @return Array of topic information.
413 */
414 std::vector<TopicInfo> GetTopicInfo(std::string_view prefix,
415 std::span<std::string_view> types) {
416 return ::nt::GetTopicInfo(m_handle, prefix, types);
417 }
418
419 /**
420 * Gets the entry for a key.
421 *
422 * @param name Key
423 * @return Network table entry.
424 */
425 NetworkTableEntry GetEntry(std::string_view name) {
426 return NetworkTableEntry{::nt::GetEntry(m_handle, name)};
427 }
428
429 /**
430 * Gets the table with the specified key.
431 *
432 * @param key the key name
433 * @return The network table
434 */
435 std::shared_ptr<NetworkTable> GetTable(std::string_view key) const;
436
437 /**
438 * @{
439 * @name Listener Functions
440 */
441
442 /**
443 * Remove a listener.
444 *
445 * @param listener Listener handle to remove
446 */
447 static void RemoveListener(NT_Listener listener) {
448 ::nt::RemoveListener(listener);
449 }
450
451 /**
452 * Wait for the listener queue to be empty. This is primarily
453 * useful for deterministic testing. This blocks until either the
454 * listener queue is empty (e.g. there are no more events that need to be
455 * passed along to callbacks or poll queues) or the timeout expires.
456 *
457 * @param timeout timeout, in seconds. Set to 0 for non-blocking behavior, or
458 * a negative value to block indefinitely
459 * @return False if timed out, otherwise true.
460 */
461 bool WaitForListenerQueue(double timeout) {
462 return ::nt::WaitForListenerQueue(m_handle, timeout);
463 }
464
465 /**
466 * Add a connection listener. The callback function is called asynchronously
467 * on a separate thread, so it's important to use synchronization or atomics
468 * when accessing any shared state from the callback function.
469 *
470 * @param immediate_notify notify listener of all existing connections
471 * @param callback listener to add
472 * @return Listener handle
473 */
474 NT_Listener AddConnectionListener(bool immediate_notify,
475 ListenerCallback callback) const {
476 return ::nt::AddListener(
477 m_handle,
478 NT_EVENT_CONNECTION | (immediate_notify ? NT_EVENT_IMMEDIATE : 0),
479 std::move(callback));
480 }
481
482 /**
483 * Add a time synchronization listener. The callback function is called
484 * asynchronously on a separate thread, so it's important to use
485 * synchronization or atomics when accessing any shared state from the
486 * callback function.
487 *
488 * @param immediate_notify notify listener of current time synchronization
489 * value
490 * @param callback listener to add
491 * @return Listener handle
492 */
493 NT_Listener AddTimeSyncListener(bool immediate_notify,
494 ListenerCallback callback) const {
495 return ::nt::AddListener(
496 m_handle,
497 NT_EVENT_TIMESYNC | (immediate_notify ? NT_EVENT_IMMEDIATE : 0),
498 std::move(callback));
499 }
500
501 /**
502 * Add a listener for changes on a particular topic. The callback
503 * function is called asynchronously on a separate thread, so it's important
504 * to use synchronization or atomics when accessing any shared state from the
505 * callback function.
506 *
507 * This creates a corresponding internal subscriber with the lifetime of the
508 * listener.
509 *
510 * @param topic Topic
511 * @param eventMask Bitmask of EventFlags values
512 * @param listener Listener function
513 * @return Listener handle
514 */
515 NT_Listener AddListener(Topic topic, unsigned int eventMask,
516 ListenerCallback listener);
517
518 /**
519 * Add a listener for changes on a subscriber. The callback
520 * function is called asynchronously on a separate thread, so it's important
521 * to use synchronization or atomics when accessing any shared state from the
522 * callback function. This does NOT keep the subscriber active.
523 *
524 * @param subscriber Subscriber
525 * @param eventMask Bitmask of EventFlags values
526 * @param listener Listener function
527 * @return Listener handle
528 */
529 NT_Listener AddListener(Subscriber& subscriber, unsigned int eventMask,
530 ListenerCallback listener);
531
532 /**
533 * Add a listener for changes on a subscriber. The callback
534 * function is called asynchronously on a separate thread, so it's important
535 * to use synchronization or atomics when accessing any shared state from the
536 * callback function. This does NOT keep the subscriber active.
537 *
538 * @param subscriber Subscriber
539 * @param eventMask Bitmask of EventFlags values
540 * @param listener Listener function
541 * @return Listener handle
542 */
543 NT_Listener AddListener(MultiSubscriber& subscriber, int eventMask,
544 ListenerCallback listener);
545
546 /**
547 * Add a listener for changes on an entry. The callback function
548 * is called asynchronously on a separate thread, so it's important to use
549 * synchronization or atomics when accessing any shared state from the
550 * callback function.
551 *
552 * @param entry Entry
553 * @param eventMask Bitmask of EventFlags values
554 * @param listener Listener function
555 * @return Listener handle
556 */
557 NT_Listener AddListener(const NetworkTableEntry& entry, int eventMask,
558 ListenerCallback listener);
559
560 /**
561 * Add a listener for changes to topics with names that start with any
562 * of the given prefixes. The callback function is called asynchronously on a
563 * separate thread, so it's important to use synchronization or atomics when
564 * accessing any shared state from the callback function.
565 *
566 * This creates a corresponding internal subscriber with the lifetime of the
567 * listener.
568 *
569 * @param prefixes Topic name string prefixes
570 * @param eventMask Bitmask of EventFlags values
571 * @param listener Listener function
572 * @return Listener handle
573 */
574 NT_Listener AddListener(std::span<const std::string_view> prefixes,
575 int eventMask, ListenerCallback listener) {
576 return ::nt::AddListener(m_handle, prefixes, eventMask,
577 std::move(listener));
578 }
579
580 /** @} */
581
582 /**
583 * @{
584 * @name Client/Server Functions
585 */
586
587 /**
588 * Get the current network mode.
589 *
590 * @return Bitmask of NetworkMode.
591 */
592 unsigned int GetNetworkMode() const { return ::nt::GetNetworkMode(m_handle); }
593
594 /**
595 * Starts local-only operation. Prevents calls to StartServer or StartClient
596 * from taking effect. Has no effect if StartServer or StartClient
597 * has already been called.
598 */
599 void StartLocal() { ::nt::StartLocal(m_handle); }
600
601 /**
602 * Stops local-only operation. StartServer or StartClient can be called after
603 * this call to start a server or client.
604 */
605 void StopLocal() { ::nt::StopLocal(m_handle); }
606
607 /**
608 * Starts a server using the specified filename, listening address, and port.
609 *
610 * @param persist_filename the name of the persist file to use (UTF-8 string,
611 * null terminated)
612 * @param listen_address the address to listen on, or null to listen on any
613 * address (UTF-8 string, null terminated)
614 * @param port3 port to communicate over (NT3)
615 * @param port4 port to communicate over (NT4)
616 */
617 void StartServer(std::string_view persist_filename = "networktables.json",
618 const char* listen_address = "",
619 unsigned int port3 = kDefaultPort3,
620 unsigned int port4 = kDefaultPort4) {
621 ::nt::StartServer(m_handle, persist_filename, listen_address, port3, port4);
622 }
623
624 /**
625 * Stops the server if it is running.
626 */
627 void StopServer() { ::nt::StopServer(m_handle); }
628
629 /**
630 * Starts a NT3 client. Use SetServer or SetServerTeam to set the server name
631 * and port.
632 *
633 * @param identity network identity to advertise (cannot be empty string)
634 */
635 void StartClient3(std::string_view identity) {
636 ::nt::StartClient3(m_handle, identity);
637 }
638
639 /**
640 * Starts a NT4 client. Use SetServer or SetServerTeam to set the server name
641 * and port.
642 *
643 * @param identity network identity to advertise (cannot be empty string)
644 */
645 void StartClient4(std::string_view identity) {
646 ::nt::StartClient4(m_handle, identity);
647 }
648
649 /**
650 * Stops the client if it is running.
651 */
652 void StopClient() { ::nt::StopClient(m_handle); }
653
654 /**
655 * Sets server address and port for client (without restarting client).
656 *
657 * @param server_name server name (UTF-8 string)
658 * @param port port to communicate over (0 = default)
659 */
660 void SetServer(std::string_view server_name, unsigned int port = 0) {
661 ::nt::SetServer(m_handle, server_name, port);
662 }
663
664 /**
665 * Sets server addresses and ports for client (without restarting client).
666 * The client will attempt to connect to each server in round robin fashion.
667 *
668 * @param servers array of server address and port pairs
669 */
671 std::span<const std::pair<std::string_view, unsigned int>> servers) {
672 ::nt::SetServer(m_handle, servers);
673 }
674
675 /**
676 * Sets server addresses and port for client (without restarting client).
677 * The client will attempt to connect to each server in round robin fashion.
678 *
679 * @param servers array of server names
680 * @param port port to communicate over (0 = default)
681 */
682 void SetServer(std::span<const std::string_view> servers,
683 unsigned int port = 0);
684
685 /**
686 * Sets server addresses and port for client (without restarting client).
687 * Connects using commonly known robot addresses for the specified team.
688 *
689 * @param team team number
690 * @param port port to communicate over (0 = default)
691 */
692 void SetServerTeam(unsigned int team, unsigned int port = 0) {
693 ::nt::SetServerTeam(m_handle, team, port);
694 }
695
696 /**
697 * Disconnects the client if it's running and connected. This will
698 * automatically start reconnection attempts to the current server list.
699 */
700 void Disconnect() { ::nt::Disconnect(m_handle); }
701
702 /**
703 * Starts requesting server address from Driver Station.
704 * This connects to the Driver Station running on localhost to obtain the
705 * server IP address.
706 *
707 * @param port server port to use in combination with IP from DS (0 = default)
708 */
709 void StartDSClient(unsigned int port = 0) {
710 ::nt::StartDSClient(m_handle, port);
711 }
712
713 /**
714 * Stops requesting server address from Driver Station.
715 */
716 void StopDSClient() { ::nt::StopDSClient(m_handle); }
717
718 /**
719 * Flushes all updated values immediately to the local client/server. This
720 * does not flush to the network.
721 */
722 void FlushLocal() const { ::nt::FlushLocal(m_handle); }
723
724 /**
725 * Flushes all updated values immediately to the network.
726 * @note This is rate-limited to protect the network from flooding.
727 * This is primarily useful for synchronizing network updates with
728 * user code.
729 */
730 void Flush() const { ::nt::Flush(m_handle); }
731
732 /**
733 * Get information on the currently established network connections.
734 * If operating as a client, this will return either zero or one values.
735 *
736 * @return array of connection information
737 */
738 std::vector<ConnectionInfo> GetConnections() const {
739 return ::nt::GetConnections(m_handle);
740 }
741
742 /**
743 * Return whether or not the instance is connected to another node.
744 *
745 * @return True if connected.
746 */
747 bool IsConnected() const { return ::nt::IsConnected(m_handle); }
748
749 /**
750 * Get the time offset between server time and local time. Add this value to
751 * local time to get the estimated equivalent server time. In server mode,
752 * this always returns 0. In client mode, this returns the time offset only if
753 * the client and server are connected and have exchanged synchronization
754 * messages. Note the time offset may change over time as it is periodically
755 * updated; to receive updates as events, add a listener to the "time sync"
756 * event.
757 *
758 * @return Time offset in microseconds (optional)
759 */
760 std::optional<int64_t> GetServerTimeOffset() const {
761 return ::nt::GetServerTimeOffset(m_handle);
762 }
763
764 /** @} */
765
766 /**
767 * @{
768 * @name Data Logger Functions
769 */
770
771 /**
772 * Starts logging entry changes to a DataLog.
773 *
774 * @param log data log object; lifetime must extend until StopEntryDataLog is
775 * called or the instance is destroyed
776 * @param prefix only store entries with names that start with this prefix;
777 * the prefix is not included in the data log entry name
778 * @param logPrefix prefix to add to data log entry names
779 * @return Data logger handle
780 */
782 std::string_view prefix,
783 std::string_view logPrefix) {
784 return ::nt::StartEntryDataLog(m_handle, log, prefix, logPrefix);
785 }
786
787 /**
788 * Stops logging entry changes to a DataLog.
789 *
790 * @param logger data logger handle
791 */
792 static void StopEntryDataLog(NT_DataLogger logger) {
794 }
795
796 /**
797 * Starts logging connection changes to a DataLog.
798 *
799 * @param log data log object; lifetime must extend until
800 * StopConnectionDataLog is called or the instance is destroyed
801 * @param name data log entry name
802 * @return Data logger handle
803 */
805 std::string_view name) {
806 return ::nt::StartConnectionDataLog(m_handle, log, name);
807 }
808
809 /**
810 * Stops logging connection changes to a DataLog.
811 *
812 * @param logger data logger handle
813 */
817
818 /** @} */
819
820 /**
821 * @{
822 * @name Logger Functions
823 */
824
825 /**
826 * Add logger callback function. By default, log messages are sent to stderr;
827 * this function sends log messages with the specified levels to the provided
828 * callback function instead. The callback function will only be called for
829 * log messages with level greater than or equal to minLevel and less than or
830 * equal to maxLevel; messages outside this range will be silently ignored.
831 *
832 * @param minLevel minimum log level
833 * @param maxLevel maximum log level
834 * @param func callback function
835 * @return Listener handle
836 */
837 NT_Listener AddLogger(unsigned int minLevel, unsigned int maxLevel,
838 ListenerCallback func) {
839 return ::nt::AddLogger(m_handle, minLevel, maxLevel, std::move(func));
840 }
841
842 /** @} */
843
844 /**
845 * @{
846 * @name Schema Functions
847 */
848
849 /**
850 * Returns whether there is a data schema already registered with the given
851 * name. This does NOT perform a check as to whether the schema has already
852 * been published by another node on the network.
853 *
854 * @param name Name (the string passed as the data type for topics using this
855 * schema)
856 * @return True if schema already registered
857 */
858 bool HasSchema(std::string_view name) const {
859 return ::nt::HasSchema(m_handle, name);
860 }
861
862 /**
863 * Registers a data schema. Data schemas provide information for how a
864 * certain data type string can be decoded. The type string of a data schema
865 * indicates the type of the schema itself (e.g. "protobuf" for protobuf
866 * schemas, "struct" for struct schemas, etc). In NetworkTables, schemas are
867 * published just like normal topics, with the name being generated from the
868 * provided name: "/.schema/<name>". Duplicate calls to this function with
869 * the same name are silently ignored.
870 *
871 * @param name Name (the string passed as the data type for topics using this
872 * schema)
873 * @param type Type of schema (e.g. "protobuf", "struct", etc)
874 * @param schema Schema data
875 */
876 void AddSchema(std::string_view name, std::string_view type,
877 std::span<const uint8_t> schema) {
878 ::nt::AddSchema(m_handle, name, type, schema);
879 }
880
881 /**
882 * Registers a data schema. Data schemas provide information for how a
883 * certain data type string can be decoded. The type string of a data schema
884 * indicates the type of the schema itself (e.g. "protobuf" for protobuf
885 * schemas, "struct" for struct schemas, etc). In NetworkTables, schemas are
886 * published just like normal topics, with the name being generated from the
887 * provided name: "/.schema/<name>". Duplicate calls to this function with
888 * the same name are silently ignored.
889 *
890 * @param name Name (the string passed as the data type for topics using this
891 * schema)
892 * @param type Type of schema (e.g. "protobuf", "struct", etc)
893 * @param schema Schema data
894 */
895 void AddSchema(std::string_view name, std::string_view type,
896 std::string_view schema) {
897 ::nt::AddSchema(m_handle, name, type, schema);
898 }
899
900// Suppress unused-lambda-capture warning on AddSchema() call
901#ifdef __clang__
902#pragma clang diagnostic push
903#pragma clang diagnostic ignored "-Wunused-lambda-capture"
904#endif
905
906 /**
907 * Registers a protobuf schema. Duplicate calls to this function with the same
908 * name are silently ignored.
909 *
910 * @tparam T protobuf serializable type
911 * @param msg protobuf message
912 */
913 template <wpi::ProtobufSerializable T>
916 [this](auto typeString) { return HasSchema(typeString); },
917 [this](auto typeString, auto schema) {
918 AddSchema(typeString, "proto:FileDescriptorProto", schema);
919 });
920 }
921
922 /**
923 * Registers a struct schema. Duplicate calls to this function with the same
924 * name are silently ignored.
925 *
926 * @tparam T struct serializable type
927 * @param info optional struct type info
928 */
929 template <typename T, typename... I>
930 requires wpi::StructSerializable<T, I...>
931 void AddStructSchema(const I&... info) {
933 [this](auto typeString, auto schema) {
934 AddSchema(typeString, "structschema", schema);
935 },
936 info...);
937 }
938
939#ifdef __clang__
940#pragma clang diagnostic pop
941#endif
942
943 /**
944 * Equality operator. Returns true if both instances refer to the same
945 * native handle.
946 */
947 bool operator==(const NetworkTableInstance&) const = default;
948
949 private:
950 /* Native handle */
951 NT_Inst m_handle{0};
952};
953
954} // namespace nt
NetworkTables BooleanArray topic.
Definition BooleanArrayTopic.h:296
NetworkTables Boolean topic.
Definition BooleanTopic.h:235
NetworkTables DoubleArray topic.
Definition DoubleArrayTopic.h:296
NetworkTables Double topic.
Definition DoubleTopic.h:235
NetworkTables FloatArray topic.
Definition FloatArrayTopic.h:296
NetworkTables Float topic.
Definition FloatTopic.h:235
NetworkTables IntegerArray topic.
Definition IntegerArrayTopic.h:296
NetworkTables Integer topic.
Definition IntegerTopic.h:235
Subscribe to multiple topics based on one or more topic name prefixes.
Definition MultiSubscriber.h:20
NetworkTables Entry.
Definition NetworkTableEntry.h:31
NetworkTables Instance.
Definition NetworkTableInstance.h:68
void StartClient4(std::string_view identity)
Starts a NT4 client.
Definition NetworkTableInstance.h:645
static NetworkTableInstance Create()
Create an instance.
Definition NetworkTableInstance.h:140
IntegerArrayTopic GetIntegerArrayTopic(std::string_view name) const
Gets an integer array topic.
NetworkMode
Client/server mode flag values (as returned by GetNetworkMode()).
Definition NetworkTableInstance.h:74
@ kNetModeClient4
Definition NetworkTableInstance.h:78
@ kNetModeServer
Definition NetworkTableInstance.h:76
@ kNetModeLocal
Definition NetworkTableInstance.h:79
@ kNetModeClient3
Definition NetworkTableInstance.h:77
@ kNetModeNone
Definition NetworkTableInstance.h:75
BooleanTopic GetBooleanTopic(std::string_view name) const
Gets a boolean topic.
std::vector< TopicInfo > GetTopicInfo(std::string_view prefix, std::span< std::string_view > types)
Get Topic Information about multiple topics.
Definition NetworkTableInstance.h:414
FloatTopic GetFloatTopic(std::string_view name) const
Gets a float topic.
std::vector< Topic > GetTopics(std::string_view prefix, unsigned int types)
Get Published Topics.
Definition NetworkTableInstance.h:336
bool IsConnected() const
Return whether or not the instance is connected to another node.
Definition NetworkTableInstance.h:747
NT_Listener AddListener(const NetworkTableEntry &entry, int eventMask, ListenerCallback listener)
Add a listener for changes on an entry.
NT_Listener AddConnectionListener(bool immediate_notify, ListenerCallback callback) const
Add a connection listener.
Definition NetworkTableInstance.h:474
void StartLocal()
Starts local-only operation.
Definition NetworkTableInstance.h:599
StructTopic< T, I... > GetStructTopic(std::string_view name, I... info) const
Gets a raw struct serialized value topic.
Definition NetworkTableInstance.h:279
bool WaitForListenerQueue(double timeout)
Wait for the listener queue to be empty.
Definition NetworkTableInstance.h:461
DoubleArrayTopic GetDoubleArrayTopic(std::string_view name) const
Gets a double array topic.
StructArrayTopic< T, I... > GetStructArrayTopic(std::string_view name, I... info) const
Gets a raw struct serialized array topic.
Definition NetworkTableInstance.h:292
NT_Listener AddListener(std::span< const std::string_view > prefixes, int eventMask, ListenerCallback listener)
Add a listener for changes to topics with names that start with any of the given prefixes.
Definition NetworkTableInstance.h:574
NT_Listener AddLogger(unsigned int minLevel, unsigned int maxLevel, ListenerCallback func)
Add logger callback function.
Definition NetworkTableInstance.h:837
void StartDSClient(unsigned int port=0)
Starts requesting server address from Driver Station.
Definition NetworkTableInstance.h:709
std::vector< TopicInfo > GetTopicInfo(std::string_view prefix)
Get Topic Information about multiple topics.
Definition NetworkTableInstance.h:380
NT_Listener AddListener(MultiSubscriber &subscriber, int eventMask, ListenerCallback listener)
Add a listener for changes on a subscriber.
void FlushLocal() const
Flushes all updated values immediately to the local client/server.
Definition NetworkTableInstance.h:722
StringArrayTopic GetStringArrayTopic(std::string_view name) const
Gets a string array topic.
FloatArrayTopic GetFloatArrayTopic(std::string_view name) const
Gets a float array topic.
NT_ConnectionDataLogger StartConnectionDataLog(wpi::log::DataLog &log, std::string_view name)
Starts logging connection changes to a DataLog.
Definition NetworkTableInstance.h:804
ProtobufTopic< T > GetProtobufTopic(std::string_view name) const
Gets a protobuf serialized value topic.
Definition NetworkTableInstance.h:266
unsigned int GetNetworkMode() const
Get the current network mode.
Definition NetworkTableInstance.h:592
NT_Inst GetHandle() const
Gets the native handle for the entry.
Definition NetworkTableInstance.h:161
static constexpr unsigned int kDefaultPort4
The default port that network tables operates on for NT4.
Definition NetworkTableInstance.h:105
NT_DataLogger StartEntryDataLog(wpi::log::DataLog &log, std::string_view prefix, std::string_view logPrefix)
Starts logging entry changes to a DataLog.
Definition NetworkTableInstance.h:781
bool HasSchema(std::string_view name) const
Returns whether there is a data schema already registered with the given name.
Definition NetworkTableInstance.h:858
NetworkTableEntry GetEntry(std::string_view name)
Gets the entry for a key.
Definition NetworkTableInstance.h:425
NT_Listener AddListener(Subscriber &subscriber, unsigned int eventMask, ListenerCallback listener)
Add a listener for changes on a subscriber.
BooleanArrayTopic GetBooleanArrayTopic(std::string_view name) const
Gets a boolean array topic.
StringTopic GetStringTopic(std::string_view name) const
Gets a string topic.
void SetServer(std::string_view server_name, unsigned int port=0)
Sets server address and port for client (without restarting client).
Definition NetworkTableInstance.h:660
static constexpr unsigned int kDefaultPort3
The default port that network tables operates on for NT3.
Definition NetworkTableInstance.h:100
static void RemoveListener(NT_Listener listener)
Remove a listener.
Definition NetworkTableInstance.h:447
NetworkTableInstance() noexcept=default
Construct invalid instance.
void StopServer()
Stops the server if it is running.
Definition NetworkTableInstance.h:627
void AddStructSchema(const I &... info)
Registers a struct schema.
Definition NetworkTableInstance.h:931
std::vector< TopicInfo > GetTopicInfo(std::string_view prefix, unsigned int types)
Get Topic Information about multiple topics.
Definition NetworkTableInstance.h:397
void SetServerTeam(unsigned int team, unsigned int port=0)
Sets server addresses and port for client (without restarting client).
Definition NetworkTableInstance.h:692
bool operator==(const NetworkTableInstance &) const =default
Equality operator.
void StopDSClient()
Stops requesting server address from Driver Station.
Definition NetworkTableInstance.h:716
static void StopConnectionDataLog(NT_ConnectionDataLogger logger)
Stops logging connection changes to a DataLog.
Definition NetworkTableInstance.h:814
LogLevel
Logging levels (as used by SetLogger()).
Definition NetworkTableInstance.h:85
@ kLogInfo
Definition NetworkTableInstance.h:89
@ kLogError
Definition NetworkTableInstance.h:87
@ kLogWarning
Definition NetworkTableInstance.h:88
@ kLogDebug4
Definition NetworkTableInstance.h:94
@ kLogDebug3
Definition NetworkTableInstance.h:93
@ kLogCritical
Definition NetworkTableInstance.h:86
@ kLogDebug
Definition NetworkTableInstance.h:90
@ kLogDebug1
Definition NetworkTableInstance.h:91
@ kLogDebug2
Definition NetworkTableInstance.h:92
void AddSchema(std::string_view name, std::string_view type, std::span< const uint8_t > schema)
Registers a data schema.
Definition NetworkTableInstance.h:876
void Disconnect()
Disconnects the client if it's running and connected.
Definition NetworkTableInstance.h:700
void Flush() const
Flushes all updated values immediately to the network.
Definition NetworkTableInstance.h:730
void AddProtobufSchema(wpi::ProtobufMessage< T > &msg)
Registers a protobuf schema.
Definition NetworkTableInstance.h:914
NT_Listener AddListener(Topic topic, unsigned int eventMask, ListenerCallback listener)
Add a listener for changes on a particular topic.
std::shared_ptr< NetworkTable > GetTable(std::string_view key) const
Gets the table with the specified key.
NT_Listener AddTimeSyncListener(bool immediate_notify, ListenerCallback callback) const
Add a time synchronization listener.
Definition NetworkTableInstance.h:493
RawTopic GetRawTopic(std::string_view name) const
Gets a raw topic.
static void Destroy(NetworkTableInstance &inst)
Destroys an instance (note: this has global effect).
Definition NetworkTableInstance.h:149
std::vector< TopicInfo > GetTopicInfo()
Get Topic Information about multiple topics.
Definition NetworkTableInstance.h:365
DoubleTopic GetDoubleTopic(std::string_view name) const
Gets a double topic.
Topic GetTopic(std::string_view name) const
Gets a "generic" (untyped) topic.
void StartServer(std::string_view persist_filename="networktables.json", const char *listen_address="", unsigned int port3=kDefaultPort3, unsigned int port4=kDefaultPort4)
Starts a server using the specified filename, listening address, and port.
Definition NetworkTableInstance.h:617
void StopLocal()
Stops local-only operation.
Definition NetworkTableInstance.h:605
std::vector< ConnectionInfo > GetConnections() const
Get information on the currently established network connections.
Definition NetworkTableInstance.h:738
std::vector< Topic > GetTopics(std::string_view prefix)
Get Published Topics.
Definition NetworkTableInstance.h:319
void StopClient()
Stops the client if it is running.
Definition NetworkTableInstance.h:652
std::optional< int64_t > GetServerTimeOffset() const
Get the time offset between server time and local time.
Definition NetworkTableInstance.h:760
void SetServer(std::span< const std::pair< std::string_view, unsigned int > > servers)
Sets server addresses and ports for client (without restarting client).
Definition NetworkTableInstance.h:670
IntegerTopic GetIntegerTopic(std::string_view name) const
Gets an integer topic.
std::vector< Topic > GetTopics()
Get Published Topics.
Definition NetworkTableInstance.h:304
std::vector< Topic > GetTopics(std::string_view prefix, std::span< std::string_view > types)
Get Published Topics.
Definition NetworkTableInstance.h:352
void SetServer(std::span< const std::string_view > servers, unsigned int port=0)
Sets server addresses and port for client (without restarting client).
static NetworkTableInstance GetDefault()
Get global default instance.
Definition NetworkTableInstance.h:131
static void StopEntryDataLog(NT_DataLogger logger)
Stops logging entry changes to a DataLog.
Definition NetworkTableInstance.h:792
void StartClient3(std::string_view identity)
Starts a NT3 client.
Definition NetworkTableInstance.h:635
void AddSchema(std::string_view name, std::string_view type, std::string_view schema)
Registers a data schema.
Definition NetworkTableInstance.h:895
NetworkTables protobuf-encoded value topic.
Definition NetworkTable.h:36
NetworkTables Raw topic.
Definition RawTopic.h:296
NetworkTables StringArray topic.
Definition StringArrayTopic.h:235
NetworkTables String topic.
Definition StringTopic.h:298
NetworkTables struct-encoded value array topic.
Definition NetworkTable.h:42
NetworkTables struct-encoded value topic.
Definition NetworkTable.h:45
NetworkTables subscriber.
Definition Topic.h:321
NetworkTables Topic.
Definition Topic.h:28
Ease of use wrapper to make nanopb streams more opaque to the user.
Definition Protobuf.h:307
void ForEachProtobufDescriptor(function_ref< bool(std::string_view filename)> exists, function_ref< void(std::string_view filename, std::span< const uint8_t > descriptor)> fn)
Loops over all protobuf descriptors including nested/referenced descriptors.
Definition Protobuf.h:383
A data log for high-speed writing of data values.
Definition DataLog.h:70
Specifies that a type is capable of raw struct serialization and deserialization.
Definition Struct.h:69
NT_Handle NT_ConnectionDataLogger
Definition ntcore_c.h:35
NT_Handle NT_Listener
Definition ntcore_c.h:39
#define NT_DEFAULT_PORT3
Default network tables port number (NT3)
Definition ntcore_c.h:47
NT_Handle NT_Inst
Definition ntcore_c.h:38
#define NT_DEFAULT_PORT4
Default network tables port number (NT4)
Definition ntcore_c.h:50
NT_Handle NT_DataLogger
Definition ntcore_c.h:36
@ NT_LOG_DEBUG4
Definition ntcore_c.h:86
@ NT_LOG_WARNING
Definition ntcore_c.h:80
@ NT_LOG_INFO
Definition ntcore_c.h:81
@ NT_LOG_DEBUG2
Definition ntcore_c.h:84
@ NT_LOG_DEBUG
Definition ntcore_c.h:82
@ NT_LOG_CRITICAL
Definition ntcore_c.h:78
@ NT_LOG_ERROR
Definition ntcore_c.h:79
@ NT_LOG_DEBUG3
Definition ntcore_c.h:85
@ NT_LOG_DEBUG1
Definition ntcore_c.h:83
@ NT_NET_MODE_LOCAL
Definition ntcore_c.h:96
@ NT_NET_MODE_CLIENT4
Definition ntcore_c.h:94
@ NT_NET_MODE_CLIENT3
Definition ntcore_c.h:93
@ NT_NET_MODE_SERVER
Definition ntcore_c.h:92
@ NT_NET_MODE_NONE
Definition ntcore_c.h:91
@ NT_EVENT_TIMESYNC
Time synchronized with server.
Definition ntcore_c.h:127
@ NT_EVENT_CONNECTION
Any connection event (connect or disconnect).
Definition ntcore_c.h:109
@ NT_EVENT_IMMEDIATE
Initial listener addition.
Definition ntcore_c.h:103
void StopConnectionDataLog(NT_ConnectionDataLogger logger)
Stops logging connection changes to a DataLog.
void StopEntryDataLog(NT_DataLogger logger)
Stops logging entry changes to a DataLog.
NT_Inst CreateInstance()
Create an instance.
NT_Inst GetDefaultInstance()
Get default instance.
void DestroyInstance(NT_Inst inst)
Destroy an instance.
std::function< void(const Event &)> ListenerCallback
Definition ntcore_cpp.h:899
void RemoveListener(NT_Listener listener)
Removes a listener.
void StartClient4(NT_Inst inst, std::string_view identity)
Starts a NT4 client.
void Disconnect(NT_Inst inst)
Disconnects the client if it's running and connected.
void StopLocal(NT_Inst inst)
Stops local-only operation.
void StopDSClient(NT_Inst inst)
Stops requesting server address from Driver Station.
void StopServer(NT_Inst inst)
Stops the server if it is running.
void StartLocal(NT_Inst inst)
Starts local-only operation.
void Flush(NT_Inst inst)
Flush to network.
void StartClient3(NT_Inst inst, std::string_view identity)
Starts a NT3 client.
void SetServer(NT_Inst inst, std::string_view server_name, unsigned int port)
Sets server address and port for client (without restarting client).
void StartDSClient(NT_Inst inst, unsigned int port)
Starts requesting server address from Driver Station.
void StopClient(NT_Inst inst)
Stops the client if it is running.
void SetServerTeam(NT_Inst inst, unsigned int team, unsigned int port)
Sets server addresses and port for client (without restarting client).
void FlushLocal(NT_Inst inst)
Flush local updates.
void StartServer(NT_Inst inst, std::string_view persist_filename, std::string_view listen_address, unsigned int port3, unsigned int port4)
Starts a server using the specified filename, listening address, and port.
void AddSchema(NT_Inst inst, std::string_view name, std::string_view type, std::span< const uint8_t > schema)
Registers a data schema.
NT_Entry GetEntry(NT_Inst inst, std::string_view name)
Get Entry Handle.
std::vector< NT_Topic > GetTopics(NT_Inst inst, std::string_view prefix, unsigned int types)
Get Published Topics.
NetworkTables (ntcore) namespace.
Definition ntcore_cpp.h:36
void ForEachStructSchema(std::invocable< std::string_view, std::string_view > auto fn, const I &... info)
Definition Struct.h:424