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