diff --git a/src/FRC.NetworkTables/NetworkConnection.cs b/src/FRC.NetworkTables/NetworkConnection.cs index e7d9cdc..3701fd2 100644 --- a/src/FRC.NetworkTables/NetworkConnection.cs +++ b/src/FRC.NetworkTables/NetworkConnection.cs @@ -16,72 +16,59 @@ namespace NetworkTables { internal class NetworkConnection : IDisposable { - private struct PendingUpdateIds - { - public int First { get; private set; } - public int Second { get; private set; } + // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable + private readonly IClient m_client; - public void SetFirst(int first) - { - First = first; - } + private readonly Message.GetEntryTypeFunc m_getEntryType; - public void SetSecond(int second) - { - Second = second; - } - } + private readonly HandshakeFunc m_handshake; - public int ProtoRev { get; set; } + private readonly Notifier m_notifier; + private readonly BlockingCollection> m_outgoing = new BlockingCollection>(); - public enum State { Created, Init, Handshake, Synchronized, Active, Dead }; + private readonly object m_pendingMutex = new object(); - public delegate bool HandshakeFunc(NetworkConnection conn, Func getMsg, Action> sendMsgs); + private readonly List m_pendingOutgoing = new List(); - public delegate void ProcessIncomingFunc(Message msg, NetworkConnection conn); + private readonly List m_pendingUpdate = new List(); - private static long s_uid; + private readonly object m_remoteIdMutex = new object(); private readonly Stream m_stream; - // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable - private readonly IClient m_client; - - public int PeerPort { get; } - public string PeerIP { get; } - - private readonly Notifier m_notifier; - - private readonly BlockingCollection> m_outgoing = new BlockingCollection>(); - - private readonly HandshakeFunc m_handshake; - - private readonly Message.GetEntryTypeFunc m_getEntryType; + private DateTime m_lastPost = DateTime.UtcNow; private ProcessIncomingFunc m_processIncoming; private Task m_readThread; - private Task m_writeThread; - - private State m_state; private string m_remoteId; - private DateTime m_lastPost = DateTime.UtcNow; + private State m_state; + private Task m_writeThread; - private readonly object m_pendingMutex = new object(); - private readonly object m_remoteIdMutex = new object(); + public enum State + { + Created, + Init, + Handshake, + Synchronized, + Active, + Dead + }; - private readonly List m_pendingOutgoing = new List(); + public delegate bool HandshakeFunc(NetworkConnection conn, Func getMsg, Action> sendMsgs); - private readonly List m_pendingUpdate = new List(); + public delegate void ProcessIncomingFunc(Message msg, NetworkConnection conn); + + private static long s_uid; public NetworkConnection(IClient client, Notifier notifier, HandshakeFunc handshake, Message.GetEntryTypeFunc getEntryType) { - Uid = (uint)Interlocked.Increment(ref s_uid) - 1; + Uid = (uint) Interlocked.Increment(ref s_uid) - 1; m_client = client; m_stream = client.GetStream(); m_notifier = notifier; @@ -109,8 +96,37 @@ public NetworkConnection(IClient client, Notifier notifier, HandshakeFunc handsh m_client.NoDelay = true; } + public int ProtoRev { get; set; } + + public int PeerPort { get; } + public string PeerIP { get; } + public bool Disposed { get; private set; } + public bool Active { get; private set; } + + public uint Uid { get; } + + public string RemoteId + { + get + { + lock (m_remoteIdMutex) + { + return m_remoteId; + } + } + set + { + lock (m_remoteIdMutex) + { + m_remoteId = value; + } + } + } + + public long LastUpdate { get; private set; } + public void Dispose() { Stop(); @@ -130,23 +146,6 @@ public void Start() // clear queue while (m_outgoing.Count != 0) m_outgoing.Take(); - /* - //Start Threads - m_writeThread = new Thread(WriteThreadMain) - { - IsBackground = true, - Name = "Connection Write Thread" - }; - m_writeThread.Start(); - - m_readThread = new Thread(ReadThreadMain) - { - IsBackground = true, - Name = "Connection Read Thread" - }; - - m_readThread.Start(); - */ m_writeThread = Task.Factory.StartNew(WriteThreadMain, TaskCreationOptions.LongRunning); m_readThread = Task.Factory.StartNew(ReadThreadMain, TaskCreationOptions.LongRunning); } @@ -176,8 +175,6 @@ public ConnectionInfo GetConnectionInfo() return new ConnectionInfo(RemoteId, PeerIP, PeerPort, LastUpdate, ProtoRev); } - public bool Active { get; private set; } - public Stream GetStream() { return m_stream; @@ -205,112 +202,111 @@ public void QueueOutgoing(Message msg) { case Message.MsgType.EntryAssign: case Message.MsgType.EntryUpdate: + { + // don't do this for unassigned id's + int id = (int) msg.Id; + if (id == 0xffff) { - // don't do this for unassigned id's - int id = (int)msg.Id; - if (id == 0xffff) - { - m_pendingOutgoing.Add(msg); - break; - } - if (id < m_pendingUpdate.Count && m_pendingUpdate[id].First != 0) + m_pendingOutgoing.Add(msg); + break; + } + if (id < m_pendingUpdate.Count && m_pendingUpdate[id].First != 0) + { + var oldmsg = m_pendingOutgoing[m_pendingUpdate[id].First - 1]; + if (oldmsg != null && oldmsg.Is(Message.MsgType.EntryAssign) && + msg.Is(Message.MsgType.EntryUpdate)) { - var oldmsg = m_pendingOutgoing[m_pendingUpdate[id].First - 1]; - if (oldmsg != null && oldmsg.Is(Message.MsgType.EntryAssign) && - msg.Is(Message.MsgType.EntryUpdate)) - { - // need to update assignement - m_pendingOutgoing[m_pendingUpdate[id].First] = Message.EntryAssign(oldmsg.Str, (uint)id, msg.SeqNumUid, msg.Val, - (EntryFlags)oldmsg.Flags); - - } - else - { - // new but remember it - m_pendingOutgoing[m_pendingUpdate[id].First] = msg; - } + // need to update assignement + m_pendingOutgoing[m_pendingUpdate[id].First] = Message.EntryAssign(oldmsg.Str, (uint) id, + msg.SeqNumUid, msg.Val, + (EntryFlags) oldmsg.Flags); } else { - // new but don't remember it - int pos = m_pendingOutgoing.Count; - m_pendingOutgoing.Add(msg); - if (id >= m_pendingUpdate.Count) ResizePendingUpdate(id + 1); - m_pendingUpdate[id].SetFirst(pos + 1); + // new but remember it + m_pendingOutgoing[m_pendingUpdate[id].First] = msg; } - break; } + else + { + // new but don't remember it + int pos = m_pendingOutgoing.Count; + m_pendingOutgoing.Add(msg); + if (id >= m_pendingUpdate.Count) ResizePendingUpdate(id + 1); + m_pendingUpdate[id].SetFirst(pos + 1); + } + break; + } case Message.MsgType.EntryDelete: + { + //Don't do this for unnasigned uid's + int id = (int) msg.Id; + if (id == 0xffff) { - //Don't do this for unnasigned uid's - int id = (int)msg.Id; - if (id == 0xffff) - { - m_pendingOutgoing.Add(msg); - break; - } - - if (id < m_pendingUpdate.Count) - { - if (m_pendingUpdate[id].First != 0) - { - m_pendingOutgoing[m_pendingUpdate[id].First - 1] = new Message(); - m_pendingUpdate[id].SetFirst(0); - } - if (m_pendingUpdate[id].Second != 0) - { - m_pendingOutgoing[m_pendingUpdate[id].Second - 1] = new Message(); - m_pendingUpdate[id].SetSecond(0); - } - } - //Add deletion m_pendingOutgoing.Add(msg); break; } - case Message.MsgType.FlagsUpdate: - { - //Don't do this for unassigned uids - int id = (int)msg.Id; - if (id == 0xffff) - { - m_pendingOutgoing.Add(msg); - break; - } - if (id < m_pendingUpdate.Count && m_pendingUpdate[id].Second != 0) + if (id < m_pendingUpdate.Count) + { + if (m_pendingUpdate[id].First != 0) { - //Overwrite the previous one for this uid - m_pendingOutgoing[m_pendingUpdate[id].Second - 1] = msg; + m_pendingOutgoing[m_pendingUpdate[id].First - 1] = new Message(); + m_pendingUpdate[id].SetFirst(0); } - else + if (m_pendingUpdate[id].Second != 0) { - int pos = m_pendingOutgoing.Count; - m_pendingOutgoing.Add(msg); - if (id > m_pendingUpdate.Count) ResizePendingUpdate(id + 1); - m_pendingUpdate[id].SetSecond(pos + 1); - + m_pendingOutgoing[m_pendingUpdate[id].Second - 1] = new Message(); + m_pendingUpdate[id].SetSecond(0); } + } + //Add deletion + m_pendingOutgoing.Add(msg); + break; + } + case Message.MsgType.FlagsUpdate: + { + //Don't do this for unassigned uids + int id = (int) msg.Id; + if (id == 0xffff) + { + m_pendingOutgoing.Add(msg); break; } + + if (id < m_pendingUpdate.Count && m_pendingUpdate[id].Second != 0) + { + //Overwrite the previous one for this uid + m_pendingOutgoing[m_pendingUpdate[id].Second - 1] = msg; + } + else + { + int pos = m_pendingOutgoing.Count; + m_pendingOutgoing.Add(msg); + if (id > m_pendingUpdate.Count) ResizePendingUpdate(id + 1); + m_pendingUpdate[id].SetSecond(pos + 1); + } + break; + } case Message.MsgType.ClearEntries: + { + //Knock out all previous assignes/updates + for (int i = 0; i < m_pendingOutgoing.Count; i++) { - //Knock out all previous assignes/updates - for (int i = 0; i < m_pendingOutgoing.Count; i++) + var message = m_pendingOutgoing[i]; + if (message == null) continue; + var t = message.Type; + if (t == Message.MsgType.EntryAssign || t == Message.MsgType.EntryUpdate + || t == Message.MsgType.FlagsUpdate || t == Message.MsgType.EntryDelete + || t == Message.MsgType.ClearEntries) { - var message = m_pendingOutgoing[i]; - if (message == null) continue; - var t = message.Type; - if (t == Message.MsgType.EntryAssign || t == Message.MsgType.EntryUpdate - || t == Message.MsgType.FlagsUpdate || t == Message.MsgType.EntryDelete - || t == Message.MsgType.ClearEntries) - { - m_pendingOutgoing[i] = new Message(); - } + m_pendingOutgoing[i] = new Message(); } - m_pendingUpdate.Clear(); - m_pendingOutgoing.Add(msg); - break; } + m_pendingUpdate.Clear(); + m_pendingOutgoing.Add(msg); + break; + } default: m_pendingOutgoing.Add(msg); break; @@ -328,21 +324,18 @@ public void PostOutgoing(bool keepAlive) if (!keepAlive) return; // send keep-alives once a second (if no other messages have been sent) if ((now - m_lastPost) < TimeSpan.FromSeconds(1)) return; - m_outgoing.Add(new List { Message.KeepAlive() }); + m_outgoing.Add(new List {Message.KeepAlive()}); } else { m_outgoing.Add(new List(m_pendingOutgoing)); m_pendingOutgoing.Clear(); m_pendingUpdate.Clear(); - } m_lastPost = now; } } - public uint Uid { get; } - public State GetState() { return m_state; @@ -353,26 +346,6 @@ public void SetState(State state) m_state = state; } - public string RemoteId - { - get - { - lock (m_remoteIdMutex) - { - return m_remoteId; - } - } - set - { - lock (m_remoteIdMutex) - { - m_remoteId = value; - } - } - } - - public long LastUpdate { get; private set; } - private void ReadThreadMain() { @@ -389,10 +362,7 @@ private void ReadThreadMain() Debug($"error reading in handshake: {decoder.Error}"); } return msg; - }, messages => - { - m_outgoing.Add(messages); - })) + }, messages => { m_outgoing.Add(messages); })) { m_state = State.Dead; Active = false; @@ -442,7 +412,8 @@ private void WriteThreadMain() { if (message != null) { - Debug3($"sending type={message.Type} with str={message.Str} id={message.Id} seqNum={message.SeqNumUid}"); + Debug3( + $"sending type={message.Type} with str={message.Str} id={message.Id} seqNum={message.SeqNumUid}"); message.Write(encoder); } } @@ -457,5 +428,21 @@ private void WriteThreadMain() Active = false; m_stream?.Dispose(); // Also kill read thread } + + private struct PendingUpdateIds + { + public int First { get; private set; } + public int Second { get; private set; } + + public void SetFirst(int first) + { + First = first; + } + + public void SetSecond(int second) + { + Second = second; + } + } } -} +} \ No newline at end of file diff --git a/src/FRC.NetworkTables/Notifier.cs b/src/FRC.NetworkTables/Notifier.cs index 3b1c92c..8359c99 100644 --- a/src/FRC.NetworkTables/Notifier.cs +++ b/src/FRC.NetworkTables/Notifier.cs @@ -8,144 +8,30 @@ namespace NetworkTables { internal class Notifier : IDisposable { - private static Notifier s_instance; - private bool m_destroyed; - private bool m_localNotifiers; - - private Task m_thread; - - // Special class for Entry Listeners - private class UidListEntryListener - { - private readonly List m_list = new List(); - private readonly Queue m_free = new Queue(); - - public int Count => m_list.Count; - - public EntryListener this[int i] => m_list[i]; - - public int Add(string prefix, EntryListenerCallback callback, NotifyFlags flags) - { - int uid; - var listener = new EntryListener(prefix, callback, flags); - if (m_free.Count == 0) - { - uid = m_list.Count; - m_list.Add(listener); - } - else - { - uid = m_free.Dequeue(); - m_list[uid] = listener; - } - return uid + 1; - } - - public void Erase(int uid) - { - --uid; - if (uid >= m_list.Count || m_list[uid].IsNull()) return; - m_free.Enqueue(uid); - m_list[uid].SetNull(); - } - } - - // Special class for Connection Listeners - private class UidListConnectionListenerCallback - { - private readonly List m_list = new List(); - private readonly Queue m_free = new Queue(); - - public int Count => m_list.Count; - - public ConnectionListenerCallback this[int i] => m_list[i]; - - public int Add(ConnectionListenerCallback args) - { - int uid; - if (m_free.Count == 0) - { - uid = m_list.Count; - m_list.Add(args); - } - else - { - uid = m_free.Dequeue(); - m_list[uid] = args; - } - return uid + 1; - } - - public void Erase(int uid) - { - --uid; - if (uid >= m_list.Count || m_list[uid] == null) return; - m_free.Enqueue(uid); - m_list[uid] = null; - } - } - - private struct EntryListener - { - public EntryListener(string prefix, EntryListenerCallback callback, NotifyFlags flags) - { - Prefix = prefix; - Callback = callback; - Flags = flags; - } - - public string Prefix { get; } - public EntryListenerCallback Callback { get; private set; } - public NotifyFlags Flags { get; } - - public void SetNull() - { - Callback = null; - } + private readonly AutoResetEvent m_cond = new AutoResetEvent(false); + private readonly UidListConnectionListenerCallback m_connListeners = new UidListConnectionListenerCallback(); - public bool IsNull() - { - return Callback == null; - } - } + private readonly Queue m_connNotifications = new Queue(); private readonly UidListEntryListener m_entryListeners = new UidListEntryListener(); - private readonly UidListConnectionListenerCallback m_connListeners = new UidListConnectionListenerCallback(); - private struct EntryNotification - { - public EntryNotification(string name, Value value, NotifyFlags flags, - EntryListenerCallback only) - { - Name = name; - Value = value; - Flags = flags; - Only = only; - } + private readonly Queue m_entryNotifications = new Queue(); + private readonly object m_mutex = new object(); - public string Name { get; } - public Value Value { get; } - public NotifyFlags Flags { get; } - public EntryListenerCallback Only { get; } - } + private bool m_active; + private bool m_destroyed; + private bool m_localNotifiers; - private readonly Queue m_entryNotifications = new Queue(); + private Task m_thread; + private static Notifier s_instance; - private struct ConnectionNotification + internal Notifier() { - public ConnectionNotification(bool connected, ConnectionInfo connInfo, ConnectionListenerCallback only) - { - Connected = connected; - ConnInfo = connInfo; - Only = only; - } - public bool Connected { get; } - public ConnectionInfo ConnInfo { get; } - public ConnectionListenerCallback Only { get; } + m_active = false; + m_localNotifiers = false; + m_destroyed = false; } - private readonly Queue m_connNotifications = new Queue(); - public static Notifier Instance { get @@ -159,13 +45,6 @@ public static Notifier Instance } } - internal Notifier() - { - m_active = false; - m_localNotifiers = false; - m_destroyed = false; - } - public void Dispose() { m_destroyed = true; @@ -235,7 +114,6 @@ private void ThreadMain() callback(i + 1, name, item.Value, item.Flags); Monitor.Enter(m_mutex, ref lockEntered); } - } //Connection notifications @@ -274,10 +152,6 @@ private void ThreadMain() } } - private bool m_active; - private readonly object m_mutex = new object(); - private readonly AutoResetEvent m_cond = new AutoResetEvent(false); - public void Start() { lock (m_mutex) @@ -285,14 +159,7 @@ public void Start() if (m_active) return; m_active = true; } - /* - m_thread = new Thread(ThreadMain) - { - IsBackground = true, - Name = "Notifier Thread" - }; - m_thread.Start(); - */ + m_thread = Task.Factory.StartNew(ThreadMain, TaskCreationOptions.LongRunning); } @@ -369,5 +236,131 @@ public void NotifyConnection(bool connected, ConnectionInfo connInfo, Connection } m_cond.Set(); } + + // Special class for Entry Listeners + private class UidListEntryListener + { + private readonly Queue m_free = new Queue(); + private readonly List m_list = new List(); + + public int Count => m_list.Count; + + public EntryListener this[int i] => m_list[i]; + + public int Add(string prefix, EntryListenerCallback callback, NotifyFlags flags) + { + int uid; + var listener = new EntryListener(prefix, callback, flags); + if (m_free.Count == 0) + { + uid = m_list.Count; + m_list.Add(listener); + } + else + { + uid = m_free.Dequeue(); + m_list[uid] = listener; + } + return uid + 1; + } + + public void Erase(int uid) + { + --uid; + if (uid >= m_list.Count || m_list[uid].IsNull()) return; + m_free.Enqueue(uid); + m_list[uid].SetNull(); + } + } + + // Special class for Connection Listeners + private class UidListConnectionListenerCallback + { + private readonly Queue m_free = new Queue(); + private readonly List m_list = new List(); + + public int Count => m_list.Count; + + public ConnectionListenerCallback this[int i] => m_list[i]; + + public int Add(ConnectionListenerCallback args) + { + int uid; + if (m_free.Count == 0) + { + uid = m_list.Count; + m_list.Add(args); + } + else + { + uid = m_free.Dequeue(); + m_list[uid] = args; + } + return uid + 1; + } + + public void Erase(int uid) + { + --uid; + if (uid >= m_list.Count || m_list[uid] == null) return; + m_free.Enqueue(uid); + m_list[uid] = null; + } + } + + private struct EntryListener + { + public EntryListener(string prefix, EntryListenerCallback callback, NotifyFlags flags) + { + Prefix = prefix; + Callback = callback; + Flags = flags; + } + + public string Prefix { get; } + public EntryListenerCallback Callback { get; private set; } + public NotifyFlags Flags { get; } + + public void SetNull() + { + Callback = null; + } + + public bool IsNull() + { + return Callback == null; + } + } + + private struct EntryNotification + { + public EntryNotification(string name, Value value, NotifyFlags flags, + EntryListenerCallback only) + { + Name = name; + Value = value; + Flags = flags; + Only = only; + } + + public string Name { get; } + public Value Value { get; } + public NotifyFlags Flags { get; } + public EntryListenerCallback Only { get; } + } + + private struct ConnectionNotification + { + public ConnectionNotification(bool connected, ConnectionInfo connInfo, ConnectionListenerCallback only) + { + Connected = connected; + ConnInfo = connInfo; + Only = only; + } + + public bool Connected { get; } + public ConnectionInfo ConnInfo { get; } + public ConnectionListenerCallback Only { get; } + } } -} +} \ No newline at end of file diff --git a/src/FRC.NetworkTables/RpcServer.cs b/src/FRC.NetworkTables/RpcServer.cs index 9e7ea1b..111b5d7 100644 --- a/src/FRC.NetworkTables/RpcServer.cs +++ b/src/FRC.NetworkTables/RpcServer.cs @@ -11,10 +11,34 @@ namespace NetworkTables { internal class RpcServer : IDisposable { - private readonly Dictionary, SendMsgFunc> m_responseMap = new Dictionary, SendMsgFunc>(); + private readonly AutoResetEvent m_callCond = new AutoResetEvent(false); + + private readonly Queue m_callQueue = new Queue(); + private readonly CancellationTokenSource m_cancellationTokenSource = new CancellationTokenSource(); + + + private readonly object m_mutex = new object(); + private readonly AutoResetEvent m_pollCond = new AutoResetEvent(false); + private readonly AsyncAutoResetEvent m_pollCondAsync = new AsyncAutoResetEvent(false); + private readonly Queue m_pollQueue = new Queue(); + + private readonly Dictionary, SendMsgFunc> m_responseMap = + new Dictionary, SendMsgFunc>(); + + private bool m_terminating; + + private Task m_thread; + + public delegate void SendMsgFunc(Message msg); private static RpcServer s_instance; + internal RpcServer() + { + Active = false; + m_terminating = false; + } + /// /// Gets the local instance of Dispatcher /// @@ -42,8 +66,6 @@ public void Dispose() m_pollCondAsync.Set(); } - public delegate void SendMsgFunc(Message msg); - public void Start() { lock (m_mutex) @@ -51,14 +73,7 @@ public void Start() if (Active) return; Active = true; } - /* - m_thread = new Thread(ThreadMain) - { - Name = "Rpc Thread", - IsBackground = true - }; - m_thread.Start(); - */ + m_thread = Task.Factory.StartNew(ThreadMain, TaskCreationOptions.LongRunning); } @@ -82,7 +97,7 @@ public void ProcessRpc(string name, Message msg, RpcCallback func, uint connId, if (func != null) m_callQueue.Enqueue(new RpcCall(name, msg, func, connId, sendResponse)); else - // ReSharper disable once ExpressionIsAlwaysNull + // ReSharper disable once ExpressionIsAlwaysNull m_pollQueue.Enqueue(new RpcCall(name, msg, func, connId, sendResponse)); } finally @@ -179,22 +194,16 @@ public bool PollRpc(bool blocking, TimeSpan timeout, out RpcCallInfo callInfo) public void PostRpcResponse(long rpcId, long callId, params byte[] result) { SendMsgFunc func; - var pair = new ImmutablePair((uint)rpcId, (uint)callId); + var pair = new ImmutablePair((uint) rpcId, (uint) callId); if (!m_responseMap.TryGetValue(pair, out func)) { Warning("posting PRC response to nonexistent call (or duplicate response)"); return; } - func(Message.RpcResponse((uint)rpcId, (uint)callId, result)); + func(Message.RpcResponse((uint) rpcId, (uint) callId, result)); m_responseMap.Remove(pair); } - internal RpcServer() - { - Active = false; - m_terminating = false; - } - private void ThreadMain() { bool lockEntered = false; @@ -232,9 +241,6 @@ private void ThreadMain() } } - private bool m_terminating; - private readonly CancellationTokenSource m_cancellationTokenSource = new CancellationTokenSource(); - private struct RpcCall { public RpcCall(string name, Message msg, RpcCallback func, uint connId, SendMsgFunc sendResponse) @@ -251,18 +257,6 @@ public RpcCall(string name, Message msg, RpcCallback func, uint connId, SendMsgF public RpcCallback Func { get; } public uint ConnId { get; } public SendMsgFunc SendResponse { get; } - } - - private readonly Queue m_callQueue = new Queue(); - private readonly Queue m_pollQueue = new Queue(); - - private Task m_thread; - - - private readonly object m_mutex = new object(); - private readonly AutoResetEvent m_callCond = new AutoResetEvent(false); - private readonly AutoResetEvent m_pollCond = new AutoResetEvent(false); - private readonly AsyncAutoResetEvent m_pollCondAsync = new AsyncAutoResetEvent(false); } -} +} \ No newline at end of file diff --git a/src/FRC.NetworkTables/SequenceNumber.cs b/src/FRC.NetworkTables/SequenceNumber.cs index 7734fb8..068635c 100644 --- a/src/FRC.NetworkTables/SequenceNumber.cs +++ b/src/FRC.NetworkTables/SequenceNumber.cs @@ -11,13 +11,14 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (obj.GetType() != GetType()) return false; - return Equals((SequenceNumber)obj); + return Equals((SequenceNumber) obj); } public override int GetHashCode() { - //No good hash code here, so just have to be careful - return 0; + // The has code here needs to be the one for our value + // ReSharper disable once NonReadonlyMemberInGetHashCode + return Value.GetHashCode(); } public SequenceNumber(uint value) @@ -30,10 +31,7 @@ public SequenceNumber(SequenceNumber old) Value = old.Value; } - public uint Value - { - get; private set; - } + public uint Value { get; private set; } public static SequenceNumber operator ++(SequenceNumber input) { @@ -81,6 +79,5 @@ public uint Value { return lhs.Value != rhs.Value; } - } -} +} \ No newline at end of file diff --git a/src/FRC.NetworkTables/Storage.cs b/src/FRC.NetworkTables/Storage.cs index 199f59d..f3e253c 100644 --- a/src/FRC.NetworkTables/Storage.cs +++ b/src/FRC.NetworkTables/Storage.cs @@ -13,25 +13,40 @@ namespace NetworkTables { internal partial class Storage : IDisposable { - internal struct StoragePair : IComparable - { - public string First { get; } - public Value Second { get; } + // Global storage mutex + private readonly object m_mutex = new object(); - public StoragePair(string first, Value second) - { - First = first; - Second = second; - } + private readonly Notifier m_notifier; - public int CompareTo(StoragePair other) - { - return string.Compare(First, other.First, StringComparison.Ordinal); - } - } + // Rpc support fields + private readonly Dictionary, byte[]> m_rpcResults = new Dictionary, byte[]>(); + private readonly AutoResetEvent m_rpcResultsCond = new AutoResetEvent(false); + private readonly AsyncAutoResetEvent m_rpcResultsCondAsync = new AsyncAutoResetEvent(false); + private readonly RpcServer m_rpcServer; + + // True if the persistance state has changed + private bool m_persistentDirty; + + private QueueOutgoingFunc m_queueOutgoing; + + private bool m_server = true; + private bool m_terminating; + + + public delegate void QueueOutgoingFunc(Message msg, NetworkConnection only, NetworkConnection except); private static Storage s_instance; + internal Storage() : this(Notifier.Instance, RpcServer.Instance) + { + } + + internal Storage(Notifier notifier, RpcServer rpcServer) + { + m_notifier = notifier; + m_rpcServer = rpcServer; + } + public static Storage Instance { get @@ -45,14 +60,10 @@ public static Storage Instance } } - internal Dictionary Entries => m_entries; - internal List IdMap => m_idMap; - - - internal Storage() : this(Notifier.Instance, RpcServer.Instance) - { - - } + // Dict of all our entries organized by key + internal Dictionary Entries { get; private set; } = new Dictionary(); + // Map of all our Ids + internal List IdMap { get; } = new List(); public void Dispose() @@ -63,62 +74,6 @@ public void Dispose() m_rpcResultsCondAsync.Set(); } - internal Storage(Notifier notifier, RpcServer rpcServer) - { - m_notifier = notifier; - m_rpcServer = rpcServer; - } - - internal class Entry - { - public Entry(string name) - { - Name = name; - Flags = 0; - Id = 0xffff; - Value = null; - SeqNum = new SequenceNumber(); - RpcCallback = null; - RpcCallUid = 0; - } - - public bool IsPersistent() => (Flags & EntryFlags.Persistent) != 0; - - public readonly string Name; - public Value Value; - public EntryFlags Flags; - public uint Id; - - public SequenceNumber SeqNum; - - public RpcCallback RpcCallback; - public uint RpcCallUid; - - } - - private Dictionary m_entries = new Dictionary(); - private readonly List m_idMap = new List(); - internal readonly Dictionary, byte[]> m_rpcResults = new Dictionary, byte[]>(); - - private bool m_terminating; - private readonly AutoResetEvent m_rpcResultsCond = new AutoResetEvent(false); - private readonly AsyncAutoResetEvent m_rpcResultsCondAsync = new AsyncAutoResetEvent(false); - - private readonly object m_mutex = new object(); - - QueueOutgoingFunc m_queueOutgoing; - bool m_server = true; - - bool m_persistentDirty; - - private readonly Notifier m_notifier; - private readonly RpcServer m_rpcServer; - - - - - public delegate void QueueOutgoingFunc(Message msg, NetworkConnection only, NetworkConnection except); - public void SetOutgoing(QueueOutgoingFunc queueOutgoing, bool server) { lock (m_mutex) @@ -137,8 +92,8 @@ public NtType GetEntryType(uint id) { lock (m_mutex) { - if (id >= m_idMap.Count) return NtType.Unassigned; - Entry entry = m_idMap[(int)id]; + if (id >= IdMap.Count) return NtType.Unassigned; + Entry entry = IdMap[(int)id]; if (entry?.Value == null) return NtType.Unassigned; return entry.Value.Type; } @@ -174,18 +129,18 @@ public void ProcessIncoming(Message msg, NetworkConnection conn, WeakReference= m_idMap.Count || m_idMap[(int)id] == null) + if (id >= IdMap.Count || IdMap[(int)id] == null) { Monitor.Exit(m_mutex); lockEntered = false; Debug("server: received assignment to unknown entry"); return; } - entry = m_idMap[(int)id]; + entry = IdMap[(int)id]; } else { @@ -220,12 +175,12 @@ public void ProcessIncoming(Message msg, NetworkConnection conn, WeakReference= m_idMap.Count) ResizeIdMap(id + 1); - entry = m_idMap[(int)id]; + if (id >= IdMap.Count) ResizeIdMap(id + 1); + entry = IdMap[(int)id]; if (entry == null) { Entry newEntry; - if (!m_entries.ContainsKey(name)) + if (!Entries.ContainsKey(name)) { //Entry didn't exist at all. newEntry = new Entry(name) @@ -234,20 +189,20 @@ public void ProcessIncoming(Message msg, NetworkConnection conn, WeakReference= m_idMap.Count || m_idMap[(int)id] == null) + if (id >= IdMap.Count || IdMap[(int)id] == null) { Monitor.Exit(m_mutex); lockEntered = false; @@ -328,7 +283,7 @@ public void ProcessIncoming(Message msg, NetworkConnection conn, WeakReference= m_idMap.Count || m_idMap[(int)id] == null) + if (id >= IdMap.Count || IdMap[(int)id] == null) { Monitor.Exit(m_mutex); lockEntered = false; @@ -359,7 +314,7 @@ public void ProcessIncoming(Message msg, NetworkConnection conn, WeakReference= m_idMap.Count || m_idMap[(int)id] == null) + if (id >= IdMap.Count || IdMap[(int)id] == null) { Monitor.Exit(m_mutex); lockEntered = false; @@ -391,15 +346,15 @@ public void ProcessIncoming(Message msg, NetworkConnection conn, WeakReference= m_idMap.Count || m_idMap[(int)id] == null) + if (id >= IdMap.Count || IdMap[(int)id] == null) { Monitor.Exit(m_mutex); lockEntered = false; Debug("received RPC call to unknown entry"); return; } - entry = m_idMap[(int)id]; + entry = IdMap[(int)id]; if (!entry.Value.IsRpc()) { Monitor.Exit(m_mutex); @@ -472,7 +427,7 @@ public void GetInitialAssignments(NetworkConnection conn, List msgs) lock (m_mutex) { conn.SetState(NetworkConnection.State.Synchronized); - foreach (var i in m_entries) + foreach (var i in Entries) { Entry entry = i.Value; msgs.Add(Message.EntryAssign(i.Key, entry.Id, entry.SeqNum.Value, entry.Value, entry.Flags)); @@ -482,13 +437,13 @@ public void GetInitialAssignments(NetworkConnection conn, List msgs) private void ResizeIdMap(uint newSize) { - int currentSize = m_idMap.Count; + int currentSize = IdMap.Count; if (newSize > currentSize) { - if (newSize > m_idMap.Capacity) - m_idMap.Capacity = (int)newSize; - m_idMap.AddRange(Enumerable.Repeat(null, (int)newSize - currentSize)); + if (newSize > IdMap.Capacity) + IdMap.Capacity = (int)newSize; + IdMap.AddRange(Enumerable.Repeat(null, (int)newSize - currentSize)); } } @@ -504,9 +459,9 @@ public void ApplyInitialAssignments(NetworkConnection conn, Message[] msgs, bool List updateMsgs = new List(); - foreach (var i in m_entries) i.Value.Id = 0xffff; + foreach (var i in Entries) i.Value.Id = 0xffff; - m_idMap.Clear(); + IdMap.Clear(); foreach (var msg in msgs) { @@ -529,7 +484,7 @@ public void ApplyInitialAssignments(NetworkConnection conn, Message[] msgs, bool Entry entry; - if (!m_entries.TryGetValue(name, out entry)) + if (!Entries.TryGetValue(name, out entry)) { entry = new Entry(name) { @@ -538,7 +493,7 @@ public void ApplyInitialAssignments(NetworkConnection conn, Message[] msgs, bool SeqNum = seqNum }; m_notifier.NotifyEntry(name, entry.Value, NotifyFlags.NotifyNew); - m_entries.Add(name, entry); + Entries.Add(name, entry); } else { @@ -563,11 +518,11 @@ public void ApplyInitialAssignments(NetworkConnection conn, Message[] msgs, bool } entry.Id = id; - if (id >= m_idMap.Count) ResizeIdMap(id + 1); - m_idMap[(int)id] = entry; + if (id >= IdMap.Count) ResizeIdMap(id + 1); + IdMap[(int)id] = entry; } - foreach (var i in m_entries) + foreach (var i in Entries) { Entry entry = i.Value; if (entry.Id != 0xffff) continue; @@ -590,7 +545,7 @@ public Value GetEntryValue(string name) lock (m_mutex) { Entry entry; - if (m_entries.TryGetValue(name, out entry)) + if (Entries.TryGetValue(name, out entry)) { //Grabbed return entry.Value; @@ -611,7 +566,7 @@ public bool SetDefaultEntryValue(string name, Value value) { Monitor.Enter(m_mutex, ref lockEntered); Entry newEntry; - if (m_entries.TryGetValue(name, out newEntry)) // entry already exists + if (Entries.TryGetValue(name, out newEntry)) // entry already exists { var oldValue = newEntry.Value; if (oldValue != null && oldValue.Type == value.Type) return true; @@ -620,7 +575,7 @@ public bool SetDefaultEntryValue(string name, Value value) // if we've gotten here, entry does not exist, and we can write it. newEntry = new Entry(name); - m_entries.Add(name, newEntry); + Entries.Add(name, newEntry); var entry = newEntry; @@ -629,9 +584,9 @@ public bool SetDefaultEntryValue(string name, Value value) // if we're the server, assign an id if it doesn't have one if (m_server && entry.Id == 0xffff) { - int id = m_idMap.Count; + int id = IdMap.Count; entry.Id = (uint)id; - m_idMap.Add(entry); + IdMap.Add(entry); } // notify (for local listeners) @@ -666,10 +621,10 @@ public bool SetEntryValue(string name, Value value) { Monitor.Enter(m_mutex, ref lockEntered); Entry entry; - if (!m_entries.TryGetValue(name, out entry)) + if (!Entries.TryGetValue(name, out entry)) { entry = new Entry(name); - m_entries.Add(name, entry); + Entries.Add(name, entry); } var oldValue = entry.Value; if (oldValue != null && oldValue.Type != value.Type) @@ -680,9 +635,9 @@ public bool SetEntryValue(string name, Value value) if (m_server && entry.Id == 0xffff) { - uint id = (uint)m_idMap.Count; + uint id = (uint)IdMap.Count; entry.Id = id; - m_idMap.Add(entry); + IdMap.Add(entry); } if (entry.IsPersistent() && oldValue != value) m_persistentDirty = true; @@ -736,10 +691,10 @@ public void SetEntryTypeValue(string name, Value value) { Monitor.Enter(m_mutex, ref lockEntered); Entry entry; - if (!m_entries.TryGetValue(name, out entry)) + if (!Entries.TryGetValue(name, out entry)) { entry = new Entry(name); - m_entries.Add(name, entry); + Entries.Add(name, entry); } var oldValue = entry.Value; entry.Value = value; @@ -747,9 +702,9 @@ public void SetEntryTypeValue(string name, Value value) if (m_server && entry.Id == 0xffff) { - int id = m_idMap.Count; + int id = IdMap.Count; entry.Id = (uint)id; - m_idMap.Add(entry); + IdMap.Add(entry); } if (entry.IsPersistent()) m_persistentDirty = true; @@ -802,7 +757,7 @@ public void SetEntryFlags(string name, EntryFlags flags) { Monitor.Enter(m_mutex, ref lockEntered); Entry entry; - if (!m_entries.TryGetValue(name, out entry)) + if (!Entries.TryGetValue(name, out entry)) { //Key does not exist. Return return; @@ -837,7 +792,7 @@ public EntryFlags GetEntryFlags(string name) lock (m_mutex) { Entry entry; - if (m_entries.TryGetValue(name, out entry)) + if (Entries.TryGetValue(name, out entry)) { //Grabbed return entry.Flags; @@ -856,14 +811,14 @@ public void DeleteEntry(string name) { Monitor.Enter(m_mutex, ref lockEntered); Entry entry; - if (!m_entries.TryGetValue(name, out entry)) return; + if (!Entries.TryGetValue(name, out entry)) return; uint id = entry.Id; if (entry.IsPersistent()) m_persistentDirty = true; - m_entries.Remove(name); + Entries.Remove(name); - if (id < m_idMap.Count) m_idMap[(int)id] = null; + if (id < IdMap.Count) IdMap[(int)id] = null; if (entry.Value == null) return; m_notifier.NotifyEntry(name, entry.Value, (NotifyFlags.NotifyDelete | NotifyFlags.NotifyLocal)); @@ -885,14 +840,14 @@ public void DeleteEntry(string name) private void DeleteAllEntriesImpl() { - if (m_entries.Count == 0) return; + if (Entries.Count == 0) return; // only delete non-persistent values // can't erase without invalidating iterators, so build // a new dictionary Dictionary entries = new Dictionary(); - foreach (var i in m_entries) + foreach (var i in Entries) { var entry = i.Value; if (!entry.IsPersistent()) @@ -903,7 +858,7 @@ private void DeleteAllEntriesImpl() m_notifier.NotifyEntry(i.Key, i.Value.Value, NotifyFlags.NotifyDelete | NotifyFlags.NotifyLocal); } // remove it from idmap - if (entry.Id != 0xffff) m_idMap[(int)entry.Id] = null; + if (entry.Id != 0xffff) IdMap[(int)entry.Id] = null; } else { @@ -911,7 +866,7 @@ private void DeleteAllEntriesImpl() entries.Add(i.Key, i.Value); } } - m_entries = entries; + Entries = entries; } public void DeleteAllEntries() @@ -920,7 +875,7 @@ public void DeleteAllEntries() try { Monitor.Enter(m_mutex, ref lockEntered); - if (m_entries.Count == 0) return; + if (Entries.Count == 0) return; DeleteAllEntriesImpl(); @@ -942,7 +897,7 @@ public List GetEntryInfo(string prefix, NtType types) lock (m_mutex) { List infos = new List(); - foreach (var i in m_entries) + foreach (var i in Entries) { if (!i.Key.StartsWith(prefix)) continue; Entry entry = i.Value; @@ -960,7 +915,7 @@ public void NotifyEntries(string prefix, EntryListenerCallback only = null) { lock (m_mutex) { - foreach (var i in m_entries) + foreach (var i in Entries) { if (!i.Key.StartsWith(prefix)) continue; m_notifier.NotifyEntry(i.Key, i.Value.Value, NotifyFlags.NotifyImmediate, only); @@ -969,7 +924,6 @@ public void NotifyEntries(string prefix, EntryListenerCallback only = null) } - public void CreateRpc(string name, byte[] def, RpcCallback callback) { if (string.IsNullOrEmpty(name) || def == null || def.Length == 0 || callback == null) return; @@ -980,10 +934,10 @@ public void CreateRpc(string name, byte[] def, RpcCallback callback) if (!m_server) return; Entry entry; - if (!m_entries.TryGetValue(name, out entry)) + if (!Entries.TryGetValue(name, out entry)) { entry = new Entry(name); - m_entries.Add(name, entry); + Entries.Add(name, entry); } var oldValue = entry.Value; @@ -996,9 +950,9 @@ public void CreateRpc(string name, byte[] def, RpcCallback callback) if (entry.Id == 0xffff) { - int id = m_idMap.Count; + int id = IdMap.Count; entry.Id = (uint)id; - m_idMap.Add(entry); + IdMap.Add(entry); } if (m_queueOutgoing == null) return; @@ -1037,10 +991,10 @@ public void CreatePolledRpc(string name, byte[] def) if (!m_server) return; Entry entry; - if (!m_entries.TryGetValue(name, out entry)) + if (!Entries.TryGetValue(name, out entry)) { entry = new Entry(name); - m_entries.Add(name, entry); + Entries.Add(name, entry); } var oldValue = entry.Value; @@ -1052,9 +1006,9 @@ public void CreatePolledRpc(string name, byte[] def) if (entry.Id == 0xffff) { - int id = m_idMap.Count; + int id = IdMap.Count; entry.Id = (uint)id; - m_idMap.Add(entry); + IdMap.Add(entry); } if (m_queueOutgoing == null) return; @@ -1090,7 +1044,7 @@ public long CallRpc(string name, byte[] param) { Monitor.Enter(m_mutex, ref lockEntered); Entry entry; - if (!m_entries.TryGetValue(name, out entry)) + if (!Entries.TryGetValue(name, out entry)) { return 0; } @@ -1209,5 +1163,48 @@ public bool GetRpcResult(bool blocking, long callUid, TimeSpan timeout, out byte if (lockEntered) Monitor.Exit(m_mutex); } } + + internal struct StoragePair : IComparable + { + public string First { get; } + public Value Second { get; } + + public StoragePair(string first, Value second) + { + First = first; + Second = second; + } + + public int CompareTo(StoragePair other) + { + return string.Compare(First, other.First, StringComparison.Ordinal); + } + } + + internal class Entry + { + public readonly string Name; + public EntryFlags Flags; + public uint Id; + + public RpcCallback RpcCallback; + public uint RpcCallUid; + + public SequenceNumber SeqNum; + public Value Value; + + public Entry(string name) + { + Name = name; + Flags = 0; + Id = 0xffff; + Value = null; + SeqNum = new SequenceNumber(); + RpcCallback = null; + RpcCallUid = 0; + } + + public bool IsPersistent() => (Flags & EntryFlags.Persistent) != 0; + } } } diff --git a/src/FRC.NetworkTables/StorageSaving.cs b/src/FRC.NetworkTables/StorageSaving.cs index ff7dc95..af4163d 100644 --- a/src/FRC.NetworkTables/StorageSaving.cs +++ b/src/FRC.NetworkTables/StorageSaving.cs @@ -113,8 +113,8 @@ private static void SavePersistentImpl(StreamWriter stream, IEnumerable warn) continue; } - string[] split = line.Split(new[] { ' ' }, 2); + string[] split = line.Split(new[] {' '}, 2); var typeTok = split[0]; line = split[1]; NtType type = NtType.Unassigned; @@ -393,7 +393,7 @@ public bool LoadPersistent(Stream stream, Action warn) else if (typeTok == "raw") type = NtType.Raw; else if (typeTok == "array") { - split = line.Split(new[] { ' ' }, 2); + split = line.Split(new[] {' '}, 2); var arrayTok = split[0]; line = split[1]; if (arrayTok == "boolean") type = NtType.BooleanArray; @@ -475,7 +475,7 @@ public bool LoadPersistent(Stream stream, Action warn) boolArray.Clear(); while (!string.IsNullOrEmpty(line)) { - spl = line.Split(new[] { ',' }, 2); + spl = line.Split(new[] {','}, 2); line = spl.Length < 2 ? string.Empty : spl[1]; strTok = spl[0].Trim(' ', '\t'); if (strTok == "true") @@ -494,7 +494,7 @@ public bool LoadPersistent(Stream stream, Action warn) doubleArray.Clear(); while (!string.IsNullOrEmpty(line)) { - spl = line.Split(new[] { ',' }, 2); + spl = line.Split(new[] {','}, 2); line = spl.Length == 1 ? string.Empty : spl[1]; strTok = spl[0].Trim(' ', '\t'); tmpBoolean = double.TryParse(strTok, out tmpDouble); @@ -568,7 +568,7 @@ public bool LoadPersistent(Stream stream, Action warn) if (m_server && entry.Id == 0xffff) { - uint id = (uint)m_idMap.Count; + uint id = (uint) m_idMap.Count; entry.Id = id; m_idMap.Add(entry); } @@ -577,7 +577,8 @@ public bool LoadPersistent(Stream stream, Action warn) { if (oldValue != null) { - m_notifier.NotifyEntry(i.First, i.Second, (NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal)); + m_notifier.NotifyEntry(i.First, i.Second, + (NotifyFlags.NotifyNew | NotifyFlags.NotifyLocal)); } else if (oldValue != i.Second) { @@ -621,4 +622,4 @@ public bool LoadPersistent(Stream stream, Action warn) return true; } } -} +} \ No newline at end of file