Esempio n. 1
0
        public static void Send_ResetWave()
        {
            // If in a reset wave already, return.
            if (RoutingGlobal._color == Color.Red)
            {
                return;
            }

            // Refresh children table
            _children.CleanseChildrenTable();

            if (!_children.IsEmpty())
            {
                RoutingGlobal._color = Color.Red;
                var msgBytes = new byte[3];
                var size     = ComposeMessages.CreateResetMessage(msgBytes, (ushort)_resetMsgNum);
                MulticastToChildren(msgBytes, size);
                _distResetTimer.Change(120000, Timeout.Infinite); // 2 min timer. TODO: Make timeout interval contingent on distance from the reset wave origin
            }
            else
            {
                // Create status query to existing candidates
                var msgBytes = new byte[3];
                var size     = ComposeMessages.CreateStatusQueryMessage(msgBytes, (ushort)_statusMsgNum);

                // Multicast query to candidates
                if (MulticastToCandidates(msgBytes, size)) // If there are candidates
                {
                    // Wait for response
                    _statusResponseTimer.Change(10000, Timeout.Infinite); // 10 second timer

                    // Reset candidate table
                    ushort[] neighbors = MACBase.NeighborListArray();
                    CandidateTable.Initialize((byte)neighbors.Length);
                }
                else //Empty candidate table; set parent immediately
                {
                    // Set best node in candidate table as parent
                    RoutingGlobal.SetParent(false);

                    // Reset params
                    RoutingGlobal._color = Color.Green;
                    // Send "Add Parent" message to new parent
                    DistributedReset.Send_AddParent();
                    _statusMsgNum++;
                    _resetMsgNum++;
                }
            }
        }
Esempio n. 2
0
        public static void SetParent(bool refresh)
        {
            // Add current parent as ex parent
            _ex_parent = _parent;

            if (IsParent && refresh)
            {
                //Update path EWRNP
                SetPathEWRNP();
            }

            if (!CandidateTable.IsEmpty())
            {
                Candidate p = CandidateTable.GetBestCandidateRelativeToParent(refresh); // Includes path EWRNP updation and comparison with present parent

                // If a parent existed previously, add it to the candidate table
                if (Parent != p.GetMacID())
                {
                    if (IsParent)
                    {
#if !DBG_LOGIC
                        Debug.Print("Adding current parent" + RoutingGlobal.Parent + " to the candidate table");
#endif
                        CandidateTable.AddCandidate(RoutingGlobal.Parent, RoutingGlobal._parentLinkRSSI, RoutingGlobal.BestEtx, RoutingGlobal.path_ewrnp_Parent, RoutingGlobal.path_ewrnp);
                    }

                    Parent            = p.GetMacID();
                    BestEtx           = p.GetEtx();
                    _parentLinkRSSI   = (int)p.GetRSSI();
                    path_ewrnp_Parent = p.GetPathEWRNP_Base_to_Candidate();
                    path_ewrnp        = p.GetPathEWRNP();

                    // Drop parent from candidate table
                    CandidateTable.DropCandidate(Parent);
                }
#if DBG_VERBOSE
                Debug.Print("*** NEW PARENT: " + p.GetMacID() + "; path length (new): " + BestEtx + "; link RSSI: " + _parentLinkRSSI + " ***");
#elif DBG_SIMPLE
                Debug.Print("Set Parent " + p.GetMacID() + ":[" + path_ewrnp + "," + BestEtx + "," + _parentLinkRSSI + "]");
#endif
                Debug.Print("Set Parent " + p.GetMacID() + ":[" + path_ewrnp + "," + BestEtx + "," + _parentLinkRSSI + "]");
            }
            else
            {
#if !DBG_LOGIC
                Debug.Print("Empty candidate table. Parent " + RoutingGlobal.Parent + " unchanged: [" + path_ewrnp + "," + BestEtx + "," + _parentLinkRSSI + "]");
#endif
            }
        }
Esempio n. 3
0
        private static bool MulticastToCandidates(byte[] message, int messageLength)
        {
            ushort[] candidates = CandidateTable.GetCandidateNames();

            if (candidates != null)
            {
#if DBG_VERBOSE
                SystemGlobal.PrintNumericVals("Candidate List [for " + _distResetPipe.MACRadioObj.RadioAddress + "] ", candidates);
#endif
            }
            else
            {
                return(false);
            }

#if DBG_VERBOSE
            if (_distResetPipe != null)
            {
                SystemGlobal.PrintNumericVals("Multicast (on MACPipe " + _distResetPipe.PayloadType + "): ", message, messageLength);
            }
            else
            {
                SystemGlobal.PrintNumericVals("Multicast: ", message, messageLength);
            }
#endif
            foreach (var theNeighbor in candidates)
            {
                if (theNeighbor == 0)
                {
                    continue;
                }
                var status = _distResetPipe.Send(theNeighbor, message, 0, (ushort)messageLength);
#if DBG_VERBOSE
                if (status != NetOpStatus.S_Success)
                {
                    Debug.Print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Send status: " + status);
                }

                Debug.Print("\tSent to " + theNeighbor);
#elif DBG_SIMPLE
                Debug.Print("\tSent to " + theNeighbor + ", status: " + status);
#endif
            }
            return(true);
        }
Esempio n. 4
0
        public static void CleanseCandidateTable(MACPipe pipe)
        {
            ushort[] _neighborList = MACBase.NeighborListArray();
            pipe.NeighborList(_neighborList); // Get current neighborlist
            foreach (Candidate c in CandidateTable._candidateList)
            {
                ushort macID = c.GetMacID();
                if (Array.IndexOf(_neighborList, macID) == -1)
                {
#if DBG_VERBOSE
                    Debug.Print("--- CANDIDATE LIST CLEANUP: Removing stale candidate: " + macID + " ---");
#elif DBG_SIMPLE
                    Debug.Print("Removing stale candidate: " + macID);
#endif
                    CandidateTable.DropCandidate(macID);
                }
            }
        }
Esempio n. 5
0
        private static void Reset_State(object state)
        {
#if DBG_VERBOSE
            Debug.Print("*** RESET WAVE TIMEOUT FIRED: Initiating completion wave# " + _resetMsgNum + " ***");
#elif DBG_SIMPLE
            Debug.Print("Initiating completion wave " + _resetMsgNum + "");
#endif
            Send_CompletionWave(_resetMsgNum);

            // Purge children table
            _children       = new ChildrenList();
            _completionMsgs = null;

            // Create status query to existing candidates
            var msgBytes = new byte[3];
            var size     = ComposeMessages.CreateStatusQueryMessage(msgBytes, (ushort)_statusMsgNum);

            // Multicast query to candidates
            if (MulticastToCandidates(msgBytes, size)) // If there are candidates
            {
                // Wait for response
                _statusResponseTimer.Change(10000, Timeout.Infinite); // 10 second timer

                // Reset candidate table
                ushort[] neighbors = MACBase.NeighborListArray();
                CandidateTable.Initialize((byte)neighbors.Length);
            }
            else //Empty candidate table; set parent immediately
            {
                // Set best node in candidate table as parent
                RoutingGlobal.SetParent(false);

                // Reset params
                RoutingGlobal._color = Color.Green;
                // Send "Add Parent" message to new parent
                DistributedReset.Send_AddParent();
                _statusMsgNum++;
            }

            _resetMsgNum++; // No more completion messages to be accepted beyond this point
        }
Esempio n. 6
0
        /// <summary>
        /// Send a message to all neighbors - moved here from SystemGlobal
        /// </summary>
        /// <param name="mac"></param>
        /// <param name="message"></param>
        /// <param name="messageLength"></param>
        public static void BroadcastBeacon(IMAC mac, byte[] message, int messageLength)
        {
            var neighbors = MACBase.NeighborListArray();

            mac.NeighborList(neighbors);
#if !DBG_LOGIC
            SystemGlobal.PrintNeighborList(mac);
#endif

            var pipe = mac as MACPipe;

#if DBG_VERBOSE
            if (pipe != null)
            {
                PrintNumericVals("Broadcast (on MACPipe " + pipe.PayloadType + "): ", message, messageLength);
            }
            else
            {
                PrintNumericVals("Broadcast: ", message, messageLength);
            }
#endif
            foreach (var theNeighbor in neighbors)
            {
                if (theNeighbor == 0)
                {
                    continue;
                }
                var status = pipe.EnqueueToSend(theNeighbor, message, 0, (ushort)messageLength);

                if (pipe.IsMsgIDValid(status))
                {
                    // Update link metrics
                    if (theNeighbor == Parent)
                    {
                        UpdateNumTriesInCurrentWindow_Parent(1);
#if !DBG_LOGIC
                        Debug.Print("Updated numTriesInCurrentWindow for parent " + theNeighbor + "; new value = " + GetNumTriesInCurrentWindow_Parent());
#endif
                    }
                    else
                    {
                        byte cindex = CandidateTable.findIndex(theNeighbor);
                        if (cindex < byte.MaxValue)
                        {
                            CandidateTable._candidateList[cindex].UpdateNumTriesInCurrentWindow(1);
#if !DBG_LOGIC
                            Debug.Print("Updated numTriesInCurrentWindow for candidate " + theNeighbor + "; new value = " + CandidateTable._candidateList[cindex].GetNumTriesInCurrentWindow());
#endif
                        }
                    }


#if DBG_VERBOSE
                    if (status != NetOpStatus.S_Success)
                    {
                        Debug.Print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Send status: " + status);
                    }

                    Debug.Print("\tSent to " + theNeighbor);
#elif DBG_SIMPLE
                    Debug.Print("\tSent to " + theNeighbor + ", status: " + status);
#endif
                }
            }
        }
Esempio n. 7
0
        private static void DistResetStreamReceive(IMAC macBase, DateTime time, Packet packet)
        {
#if DBG_VERBOSE
            DebuggingSupport.PrintMessageReceived(macBase, "Distributed Reset");
#endif

            if (packet == null)
            {
                return;
            }
#if !DBG_LOGIC
            Debug.Print("\tRSSI: " + packet.RSSI + ", from " + packet.Src);
#endif

            var rcvPayloadBytes = packet.Payload;

            //var payload = new string(Encoding.UTF8.GetChars(rcvPayloadBytes));
#if DBG_VERBOSE
            SystemGlobal.PrintNumericVals("\tDistributed reset Rcv: ", rcvPayloadBytes);
#endif
            try
            {
                ushort[] neighbors = MACBase.NeighborListArray();


                var neighborStatus = _distResetPipe.NeighborStatus(packet.Src);
                if (neighborStatus == null)
                {
#if DBG_VERBOSE
                    Debug.Print("\t\t!!!!!!!!!!!!!!!!! Node " + packet.Src + " is not a Neighbor (MACBase.NeighborStatus returned null)");
#elif DBG_SIMPLE
                    Debug.Print("Sender not a neighbor.");
#endif
                    // If node in children table, drop it
                    if (Array.IndexOf(_children._childrenList, packet.Src) < -1)
                    {
                        _children.DropChild(packet.Src);
                    }

                    return;
                }
                //Debug.Print("\t\tFwd avg RSSI: " + neighborStatus.ReceiveLink.AverageRSSI + ", Rev avg RSSI: " + neighborStatus.SendLink.AverageRSSI);

                switch ((MessageIds)rcvPayloadBytes[0])
                {
                case MessageIds.AddParent:
#if !DBG_LOGIC
                    Debug.Print("\t>>> AddParent");
#endif
                    if (_children.AddChild(packet.Src))
                    {
#if DBG_VERBOSE
                        Debug.Print("+++ Added new child: " + packet.Src + " +++");
#elif DBG_SIMPLE
                        Debug.Print("Added new child: " + packet.Src);
#endif
                    }
                    else
                    {
#if DBG_VERBOSE
                        Debug.Print("@@@ Child already exists: " + packet.Src + " @@@");
#endif
                    }

                    return;

                case MessageIds.DropParent:
#if !DBG_LOGIC
                    Debug.Print("\t>>> DropParent");
#endif

                    if (_children.DropChild(packet.Src))
                    {
#if DBG_VERBOSE
                        Debug.Print("--- Dropped child: " + packet.Src + " ---");
#elif DBG_SIMPLE
                        Debug.Print("Dropped child: " + packet.Src);
#endif
                    }
                    else
                    {
#if DBG_VERBOSE
                        Debug.Print("@@@ Child does not exist: " + packet.Src + " @@@");
#endif
                    }

                    return;

                case MessageIds.Reset:
#if !DBG_LOGIC
                    Debug.Print("\t>>> ResetWave");
#endif
                    // Decode round number
                    ushort round_num;
                    ParseMessages.ParseResetMessage(rcvPayloadBytes, out round_num);

                    // Is this a legit reset wave?
                    if (RoutingGlobal._color == Color.Red || packet.Src != RoutingGlobal.Parent || round_num != _resetMsgNum)
                    {
#if DBG_VERBOSE
                        Debug.Print("!!! ILLEGAL RESET WAVE# " + round_num + ": Received from: " + packet.Src + " !!!");
#elif DBG_SIMPLE
                        Debug.Print("Illegal reset wave " + round_num + " from " + packet.Src);
#endif
                        return;
                    }

                    // Refresh children table
                    _children.CleanseChildrenTable();

                    if (_children.IsEmpty())     // Start completion wave if leaf node
                    {
#if DBG_VERBOSE
                        Debug.Print("*** LEAF NODE REACHED: Initiating completion wave# " + round_num + " ***");
#elif DBG_SIMPLE
                        Debug.Print("At leaf; initiating completion wave " + round_num);
#endif
                        Send_CompletionWave(round_num);

                        // Create status query to existing candidates
                        var msgBytes = new byte[3];
                        var size     = ComposeMessages.CreateStatusQueryMessage(msgBytes, (ushort)_statusMsgNum);

                        // Multicast query to candidates
                        if (MulticastToCandidates(msgBytes, size))     // If there are candidates
                        {
                            // Wait for response
                            _statusResponseTimer.Change(10000, Timeout.Infinite);     // 10 second timer

                            // Reset candidate table
                            CandidateTable.Initialize((byte)neighbors.Length);
                        }
                        else     //Empty candidate table; set parent immediately
                        {
                            // Set best node in candidate table as parent
                            RoutingGlobal.SetParent(false);

                            // Reset params
                            RoutingGlobal._color = Color.Green;
                            // Send "Add Parent" message to new parent
                            DistributedReset.Send_AddParent();
                            _statusMsgNum++;
                        }

                        _resetMsgNum++;
                    }
                    else
                    {
                        // Forward reset wave to own children
                        Send_ResetWave(rcvPayloadBytes);
                    }
                    return;

                case MessageIds.Completion:
#if !DBG_LOGIC
                    Debug.Print("\t>>> CompletionWave");
#endif
                    // Decode round number
                    ushort round;
                    ParseMessages.ParseCompletionMessage(rcvPayloadBytes, out round);

                    // Is this a legit completion wave?
                    int pos = Array.IndexOf(_children._childrenList, packet.Src);
                    if (RoutingGlobal._color != Color.Red || pos == -1 || round != _resetMsgNum)
                    {
#if DBG_VERBOSE
                        Debug.Print("!!! ILLEGAL COMPLETION WAVE# " + round + ": Received from: " + packet.Src + " !!!");
#elif DBG_SIMPLE
                        Debug.Print("Illegal completion wave " + round + " from " + packet.Src);
#endif
                        return;
                    }

                    _completionMsgs[pos] = true;

                    // Forward completion wave if received from all children
                    for (int i = 0; i < _completionMsgs.Length; i++)
                    {
                        if (!_completionMsgs[i])     // If not received from any child, return
                        {
                            return;
                        }
                    }

                    // Else, forward completion wave to parent
#if DBG_VERBOSE
                    Debug.Print("*** RECEIVED COMPLETION MESSAGES FROM ALL CHILDREN: initiating completion wave# " + round + " ***");
#elif DBG_SIMPLE
                    Debug.Print("All children responded; initiating completion wave " + round);
#endif
                    Send_CompletionWave(round);

                    // Purge children table
                    _children       = new ChildrenList();
                    _completionMsgs = null;
                    _distResetTimer.Change(Timeout.Infinite, Timeout.Infinite);

                    // Create status query to existing candidates
                    var msgBytes1 = new byte[3];
                    var size1     = ComposeMessages.CreateStatusQueryMessage(msgBytes1, (ushort)_statusMsgNum);

                    // Multicast query to candidates
                    if (MulticastToCandidates(msgBytes1, size1))     // If there are candidates
                    {
                        // Wait for response
                        _statusResponseTimer.Change(10000, Timeout.Infinite);     // 10 second timer

                        // Reset candidate table
                        CandidateTable.Initialize((byte)neighbors.Length);
                    }
                    else     //Empty candidate table; set parent immediately
                    {
                        // Set best node in candidate table as parent
                        RoutingGlobal.SetParent(false);

                        // Reset params
                        RoutingGlobal._color = Color.Green;
                        // Send "Add Parent" message to new parent
                        DistributedReset.Send_AddParent();
                        _statusMsgNum++;
                    }

                    _resetMsgNum++;
                    return;

                case MessageIds.StatusQuery:
#if !DBG_LOGIC
                    Debug.Print("\t>>> StatusQuery");
#endif
                    //If in a reset wave or no valid path, don't bother responding
                    if (RoutingGlobal._color == Color.Red || RoutingGlobal.BestEtx >= RoutingGlobal.Infinity)
                    {
#if DBG_VERBOSE
                        Debug.Print("!!! Not responding. Color: " + RoutingGlobal._color + ", BestEtx: " + RoutingGlobal.BestEtx + " !!!");
#elif DBG_SIMPLE
                        Debug.Print("Not responding. Color: " + RoutingGlobal._color + ", BestEtx: " + RoutingGlobal.BestEtx);
#endif
                        return;
                    }

                    // Decode round number
                    ushort status_msgnum;
                    ParseMessages.ParseStatusQueryMessage(rcvPayloadBytes, out status_msgnum);

                    // Send status response
                    var         msgBytes2 = new byte[5];
                    var         size2     = ComposeMessages.CreateStatusResponseMessage(msgBytes2, status_msgnum);
                    NetOpStatus status    = _distResetPipe.Send(RoutingGlobal.Parent, msgBytes2, 0, (ushort)size2);

                    return;

                case MessageIds.StatusResponse:
#if !DBG_LOGIC
                    Debug.Print("\t>>> StatusResponse");
#endif
                    ushort status_respnum;
                    Color  col;
                    byte   etx;
                    byte   pathEWRNP_B2N;

                    // Decode message
                    ParseMessages.ParseStatusResponseMessage(rcvPayloadBytes, out col, out etx, out status_respnum, out pathEWRNP_B2N);

                    // Is this a valid response?
                    if (status_respnum != _statusMsgNum)
                    {
#if DBG_VERBOSE
                        Debug.Print("!!! ILLEGAL STATUS RESPONSE# " + status_respnum + ": Received from: " + packet.Src + " !!!");
#elif DBG_SIMPLE
                        Debug.Print("Illegal status response " + status_respnum + " from " + packet.Src);
#endif
                        return;
                    }

                    byte tempEtx = (byte)(etx + 1);

                    // Add candidate if its offered etx exceeds _minEtx
                    if (tempEtx >= RoutingGlobal._minEtx)
                    {
                        CandidateTable.AddCandidate(packet.Src, 0, tempEtx, pathEWRNP_B2N, RoutingGlobal.MaxEtx);     // TODO: Add RSSI later
#if DBG_VERBOSE
                        Debug.Print("+++ Added new candidate: " + packet.Src + "; path length: " + tempEtx + " +++");
#elif DBG_SIMPLE
                        Debug.Print("New candidate " + packet.Src + ":[" + tempEtx + "]");
#endif
                    }
                    else
                    {
#if DBG_VERBOSE
                        Debug.Print("--- Not a candidate: " + packet.Src + "; path length: " + tempEtx + " ---");
#elif DBG_SIMPLE
                        Debug.Print("Not a candidate " + packet.Src + ":[" + tempEtx + "]");
#endif
                    }

                    return;

                default:
#if !DBG_LOGIC
                    Debug.Print("\tUnknown message received <" + rcvPayloadBytes[0] + ">");
#endif
                    break;
                }
            }
            catch (Exception e) { Debug.Print(e.StackTrace); }
        }
Esempio n. 8
0
        public static void SerialCallback_client_node(byte[] readBytes)
        {
            if (readBytes.Length < 1)
            {
                return;
            }

            var    readChars = System.Text.Encoding.UTF8.GetChars(readBytes); // Decode the input bytes as char using UTF8
            string tempStr   = new string(readChars);

            //Debug.Print("Client serial input: " + tempStr);
            // If 1, note that PC wants to get switch data

            if (readBytes.Length == 8 && tempStr.Substring(0, 7).Equals("fffffff"))
            {
                // byte payloadValue = (byte)_rand.Next(11);
                // Change both for different payload sizes
                // byte payloadValue = (byte)_rand.Next(11);
                // Change both for different payload sizes
                int payloadLength = readBytes.Length;

                int sendSize  = AppGlobal.SendMessageSize;
                var routedMsg = new byte[sendSize];

                ushort originator = AppGlobal.AppPipe.MACRadioObj.RadioAddress;
                AppGlobal.ClassificationType classificationType = AppGlobal.ClassificationType.Send;
                byte TTL        = Byte.MaxValue;
                var  headerSize = AppGlobal.MoteMessages.Compose.SendPacket(routedMsg, originator, classificationType, _sendMsgNum, TTL, (ushort)payloadLength);
                // add payload
                AppGlobal.MoteMessages.AddPayload.SendPacket(routedMsg, headerSize, readBytes, payloadLength);
                if (RoutingGlobal.IsParent)
                {
#if DBG_VERBOSE
                    Debug.Print("Sending Packet #" + _sendMsgNum + " to Parent");
                    Debug.Print("   Classification: " + (char)classificationType);
                    Debug.Print("   Originator: " + originator);
                    Debug.Print("   payload Length: " + payloadLength + "\n");
#endif
                    var status = RoutingGlobal.SendToParent(AppGlobal.AppPipe, routedMsg, sendSize);
                    if (status != 999)
                    {
                        Debug.Print("Send Successful");


                        _sendMsgNum++;
                        RoutingGlobal.UpdateNumTriesInCurrentWindow_Parent(1);
#if !DBG_LOGIC
                        Debug.Print("Updated numTriesInCurrentWindow for Parent " + RoutingGlobal.Parent + "; new value = " + RoutingGlobal.GetNumTriesInCurrentWindow_Parent());
#endif
                    }
                    else //Retry once
                    {
#if !DBG_LOGIC
                        Debug.Print("Retrying packet");
#endif
                        RoutingGlobal.CleanseCandidateTable(AppGlobal.AppPipe);
                        Candidate tmpBest = CandidateTable.GetBestCandidate(false);
                        AppGlobal.TempParent = tmpBest.GetMacID();
                        status = AppGlobal.SendToTempParent(AppGlobal.AppPipe, routedMsg, sendSize);
                        if (status != 999)
                        {
                            Debug.Print("Send Successful");
                            _sendMsgNum++;
                            tmpBest.UpdateNumTriesInCurrentWindow(1);
#if !DBG_LOGIC
                            Debug.Print("Updated numTriesInCurrentWindow for TempParent " + AppGlobal.TempParent + "; new value = " + tmpBest.GetNumTriesInCurrentWindow());
#endif
                        }
                    }
                }
                //Debug.Print("I know something you don't+ debug print from mote ");
                //temComm.Write("helloToYouToo: from Mote \r\n");
                //Random random = new Random();
                //int newReturnNum = random.Next(9);
                //String tempNewStr = "fffffff" + newReturnNum;
                //temComm.Write(tempNewStr);
                //_tempTimer = new Timer(temp_timer, null, 0, 1 * 10000);


                //send readBytes to parent.

                return;
            }
        }
Esempio n. 9
0
        public static void SendDetectionMessage(AppGlobal.ClassificationType classification, int detectNum)
        {
            var msgBytes   = new byte[AppGlobal.DetectionMessageSize];
            var actualSize = AppGlobal.MoteMessages.Compose.Detection(msgBytes,
                                                                      AppGlobal.AppPipe.MACRadioObj.RadioAddress, classification, detectNum, RoutingGlobal.Infinity);

            #region Uncomment when not using scheduler
#if DBG_VERBOSE
            //Debug.Print("\nAttempting send of detection message " + detectNum + " on pipe " + AppGlobal.AppPipe.PayloadType + " with classification " + (char)classification + ", size " + actualSize + " to parent " + RoutingGlobal.Parent);
#elif DBG_SIMPLE
            Debug.Print("\nSending to " + RoutingGlobal.Parent);
#endif

#if DBG_VERBOSE
            var msgS = new System.Text.StringBuilder();
            for (var i = 0; i < actualSize; i++)
            {
                msgS.Append(msgBytes[i]);
                msgS.Append(' ');
            }
            Debug.Print("\t" + msgS);
#endif
            // If in a reset, do not forward TODO: Change this to "spray"
            if (RoutingGlobal._color == Color.Red)
            {
#if DBG_VERBOSE || DBG_SIMPLE
                Debug.Print("\tIn a Reset wave... not forwarded");
#endif
                return;
            }
            // If parent is available, pass it on
            if (RoutingGlobal.IsParent)
            {
                Debug.Print("routed message len: " + msgBytes.Length);


                var status = RoutingGlobal.SendToParent(AppGlobal.AppPipe, msgBytes, actualSize);
                Debug.Print("status " + status);
                if (status != 999)
                {
                    RoutingGlobal.UpdateNumTriesInCurrentWindow_Parent(1);
#if !DBG_LOGIC
                    Debug.Print("Updated numTriesInCurrentWindow for Parent " + RoutingGlobal.Parent + "; new value = " + RoutingGlobal.GetNumTriesInCurrentWindow_Parent());
#endif
                }
                else //Retry once
                {
#if !DBG_LOGIC
                    Debug.Print("Retrying packet");
#endif
                    RoutingGlobal.CleanseCandidateTable(AppGlobal.AppPipe);
                    Candidate tmpBest = CandidateTable.GetBestCandidate(false);
                    AppGlobal.TempParent = tmpBest.GetMacID();
                    status = AppGlobal.SendToTempParent(AppGlobal.AppPipe, msgBytes, actualSize);
                    if (status != 999)
                    {
                        tmpBest.UpdateNumTriesInCurrentWindow(1);
#if !DBG_LOGIC
                        Debug.Print("Updated numTriesInCurrentWindow for TempParent " + AppGlobal.TempParent + "; new value = " + tmpBest.GetNumTriesInCurrentWindow());
#endif
                    }
                }
            }
            #endregion
        }
Esempio n. 10
0
        public static void SendPacketMessage(Object state)
        {
            Debug.Print("Timer Trigger");
            _lcd.Write("Send");
            ushort pathLength   = 1;
            int    payloadValue = 25000;

            // byte payloadValue = (byte)_rand.Next(11);
            // Change both for different payload sizes
            byte[] payload       = BitConverter.GetBytes(payloadValue);
            int    payloadLength = payload.Length;

            int sendSize  = AppGlobal.SendMessageSize;
            var routedMsg = new byte[sendSize];

            ushort originator = AppGlobal.AppPipe.MACRadioObj.RadioAddress;

            AppGlobal.ClassificationType classificationType = AppGlobal.ClassificationType.Send;
            byte TTL = Byte.MaxValue;

            ushort[] path       = { originator };
            var      headerSize = AppGlobal.MoteMessages.Compose.SendPacket(routedMsg, originator, classificationType, _sendMsgNum, TTL, (ushort)payloadLength);

            // add payload
            AppGlobal.MoteMessages.AddPayload.SendPacket(routedMsg, headerSize, payload, payloadLength);

#if DBG_SIMPLE
            Debug.Print("\nSending to " + RoutingGlobal.Parent);
#endif
            // If in a reset, do not forward TODO: Change this to "spray"
            if (RoutingGlobal._color == Color.Red)
            {
#if DBG_VERBOSE || DBG_SIMPLE
                Debug.Print("\tIn a Reset wave... not forwarded");
#endif
                return;
            }
            // If parent is available, pass it on
            if (RoutingGlobal.IsParent)
            {
                Debug.Print("routed message len: " + routedMsg.Length);


                var status = RoutingGlobal.SendToParent(AppGlobal.AppPipe, routedMsg, sendSize);
                Debug.Print("status " + status);
                if (status != 999)
                {
                    _sendMsgNum++;
                    RoutingGlobal.UpdateNumTriesInCurrentWindow_Parent(1);
#if !DBG_LOGIC
                    Debug.Print("Updated numTriesInCurrentWindow for Parent " + RoutingGlobal.Parent + "; new value = " + RoutingGlobal.GetNumTriesInCurrentWindow_Parent());
#endif
                }
                else //Retry once
                {
#if !DBG_LOGIC
                    Debug.Print("Retrying packet");
#endif
                    RoutingGlobal.CleanseCandidateTable(AppGlobal.AppPipe);
                    Candidate tmpBest = CandidateTable.GetBestCandidate(false);
                    AppGlobal.TempParent = tmpBest.GetMacID();
                    status = AppGlobal.SendToTempParent(AppGlobal.AppPipe, routedMsg, sendSize);
                    if (status != 999)
                    {
                        _sendMsgNum++;
                        tmpBest.UpdateNumTriesInCurrentWindow(1);
#if !DBG_LOGIC
                        Debug.Print("Updated numTriesInCurrentWindow for TempParent " + AppGlobal.TempParent + "; new value = " + tmpBest.GetNumTriesInCurrentWindow());
#endif
                    }
                }
            }
        }
Esempio n. 11
0
        private static void OnSendStatus(IMAC macInstance, DateTime time, SendPacketStatus ACKStatus, uint transmitDestination, ushort index)
        {
            var pipe = macInstance as MACPipe;

            switch (ACKStatus)
            {
            case SendPacketStatus.SendACKed:
#if DBG_DIAGNOSTIC
                Debug.Print("\t\tApp Message Handler: Retry queue length = " + _retriedPackets.Count);
#endif
#if !DBG_LOGIC
                Debug.Print("Detect to " + transmitDestination.ToString() + " ACKed");
#endif
                // Update link metrics
                if ((ushort)transmitDestination == RoutingGlobal.Parent)
                {
                    RoutingGlobal.UpdateNumReceivedInCurrentWindow_Parent(1);
#if !DBG_LOGIC
                    Debug.Print("Updated numReceivedInCurrentWindow for parent " + transmitDestination + "; new value = " + RoutingGlobal.GetNumReceivedInCurrentWindow_Parent());
#endif
                }
                else
                {
                    byte cindex = CandidateTable.findIndex((ushort)transmitDestination);
                    if (cindex < byte.MaxValue)
                    {
                        CandidateTable._candidateList[cindex].UpdateNumReceivedInCurrentWindow(1);
#if !DBG_LOGIC
                        Debug.Print("Updated numReceivedInCurrentWindow for candidate " + transmitDestination + "; new value = " + CandidateTable._candidateList[cindex].GetNumReceivedInCurrentWindow());
#endif
                    }
                }

                if (_retriedPackets.Contains(index))     // If this was a re-try, remove packet from queue
                {
                    _retriedPackets.Remove(index);
                }
                break;

            case SendPacketStatus.SendNACKed:
#if !DBG_LOGIC
                Debug.Print("Detect to " + transmitDestination.ToString() + " NACKed");
#endif
                // Update link metrics
                if ((ushort)transmitDestination == RoutingGlobal.Parent)
                {
                    RoutingGlobal.UpdateNumTriesInCurrentWindow_Parent(1);
#if !DBG_LOGIC
                    Debug.Print("Updated numTriesInCurrentWindow for parent " + transmitDestination + "; new value = " + RoutingGlobal.GetNumTriesInCurrentWindow_Parent());
#endif
                }
                else
                {
                    byte cindex = CandidateTable.findIndex((ushort)transmitDestination);
                    if (cindex < byte.MaxValue)
                    {
                        CandidateTable._candidateList[cindex].UpdateNumTriesInCurrentWindow(1);
#if !DBG_LOGIC
                        Debug.Print("Updated numTriesInCurrentWindow for candidate " + transmitDestination + "; new value = " + CandidateTable._candidateList[cindex].GetNumTriesInCurrentWindow());
#endif
                    }
                }
                break;

            case SendPacketStatus.SendFailed:
#if DBG_DIAGNOSTIC
                Debug.Print("\t\tApp Message Handler: Retry queue length = " + _retriedPackets.Count);
#endif
                // Update link metrics
                if ((ushort)transmitDestination == RoutingGlobal.Parent)
                {
                    RoutingGlobal.UpdateNumTriesInCurrentWindow_Parent(1);
#if !DBG_LOGIC
                    Debug.Print("Updated numTriesInCurrentWindow for parent " + transmitDestination + "; new value = " + RoutingGlobal.GetNumTriesInCurrentWindow_Parent());
#endif
                }
                else
                {
                    byte cindex = CandidateTable.findIndex((ushort)transmitDestination);
                    if (cindex < byte.MaxValue)
                    {
                        CandidateTable._candidateList[cindex].UpdateNumTriesInCurrentWindow(1);
#if !DBG_LOGIC
                        Debug.Print("Updated numTriesInCurrentWindow for candidate " + transmitDestination + "; new value = " + CandidateTable._candidateList[cindex].GetNumTriesInCurrentWindow());
#endif
                    }
                }

                // Retry
                if (!_retriedPackets.Contains(index) && RoutingGlobal._color == Color.Green)     // If packet not there, enqueue it and retry it once
                {
                    RoutingGlobal.CleanseCandidateTable(pipe);
                    Candidate tmpBst = CandidateTable.GetBestCandidate(false);
                    AppGlobal.TempParent = tmpBst.GetMacID();
                    byte[] msg = new byte[AppGlobal.DetectionMessageSize];
                    if (pipe.GetMsgWithMsgID(ref msg, index) == DeviceStatus.Success)
                    {
                        AppGlobal.SendToTempParent(pipe, msg, msg.Length);
                        tmpBst.UpdateNumTriesInCurrentWindow(1);
#if !DBG_LOGIC
                        Debug.Print("Updated numTriesInCurrentWindow for TempParent " + transmitDestination + "; new value = " + tmpBst.GetNumTriesInCurrentWindow());
#endif
                        _retriedPackets.Add(index);
                    }
                }
                else     // Retried once; drop packet
                {
                    _retriedPackets.Remove(index);
                }
                break;

            default:
                break;
            }
        }