Example #1
0
        /// <summary>
        /// makes robot move into specified direction; enter stops process
        /// </summary>
        /// <param name="walkMode">specifies speed and backwards/forwards</param>
        /// <param name="turnMode">specifies intensity of lateral movement</param>
        /// <param name="reverseMode">true for driving backwards</param>
        /// <returns>returns always true</returns>
        public bool MoveByMode(WalkMode walkMode, TurnMode turnMode, bool reverseMode = false)
        {
            CurrentWalkMode = walkMode;
            CurrentTurnMode = turnMode;

            //velocity for left wheel
            double vel1 = (int)walkMode;
            //velocity for right wheel
            double vel2 = (int)walkMode;

            //if driving backwards
            if (reverseMode)
            {
                //both wheels get same velocity first; if driving to right side, right wheel should turn faster, left one slower
                vel1 = vel1 - (((double)turnMode) / 2);
                vel2 = vel2 + (((double)turnMode) / 2);
            }
            //if driving forwards
            else
            {
                //both wheels get same velocity first; if driving to right side, left wheel should turn faster, right one slower
                vel1 = vel1 + (((double)turnMode) / 2);
                vel2 = vel2 - (((double)turnMode) / 2);
            }

            //call Move() with calculated values
            Move(vel1, vel2);

            return(true);
        }
Example #2
0
    // Use this for initialization
    void Start()
    {
        currentWalkMode = WalkMode.STOP;
        currentTurnMode = TurnMode.STRAIGHT;

        count = 0;
        SetCountText();
        winText.text = "";
    }
Example #3
0
 public CharaAnimCtrl(InputMode inputMode, WalkMode walkmode)
 {
     this.inputMode     = inputMode;
     this.walkmode      = walkmode;
     waitForBoringDelay = 800;
     animCtrl           = (RuntimeAnimatorController)Resources.Load("CharacterLowPo/CharacterAnimation");
     if (animCtrl == null)
     {
         Debug.Log(string.Format("Faild to load Animation Controller"));
     }
 }
Example #4
0
 public NPCData(string name, string job, Vector3 initialPos, Quaternion initialRot, bool willMove, WalkMode walkmode, bool canDie)
 {
     this.name     = name;
     this.job      = job;
     this.position = initialPos;
     this.rotation = initialRot;
     this.willMove = willMove;
     this.walkmode = walkmode;
     this.canDie   = canDie;
     //Debug.Log("craft NPCData");
 }
Example #5
0
    public NPCAnimCtrl(NPCData data)
    {
        this.data = data;
        //Debug.Log("New NPCAnimCtrl Created");
        this.walkmode        = data.walkmode;
        waitForBoringDelay   = Toolbox.optimizedRand(10, 800);;
        awaitThisUpdate      = false;
        waitForActionDelay   = 1.0f;
        waitForActionCounter = WaitForActionDelay;

        waitForBoringDelay = 800;
        walkSpeed          = 5f;
    }
Example #6
0
        public static object Walk(Action <object> action, ILinkedUnits unit,
                                  WalkDirection walkDirection, int index = 0, int count = -1,
                                  WalkMode walkMode = WalkMode.InvokeAll)
        {
            int step = 0;

            object next = unit;

            while (step < index + count)
            {
                if (walkDirection == WalkDirection.Left)
                {
                    next = ((ILinkedUnits)next).GetPrev();
                }
                else
                {
                    next = ((ILinkedUnits)next).GetNext();
                }

                if (next == null)
                {
                    break;
                }

                if (step < index)
                {
                    continue;
                }


                if (walkMode == WalkMode.InvokeAll)
                {
                    action?.Invoke(next);
                }

                if (walkMode == WalkMode.EndOnly)
                {
                    if (step == count - 1)
                    {
                        action?.Invoke(next);
                    }
                }

                step++;
            }

            return(next);
        }
Example #7
0
    public void SetWalkMode(WalkMode newWalkMode)
    {
        if (newWalkMode == currentWalkMode)
        {
            return;
        }

        SetWalkModeVRLookWalk(false);
        SetWalkModeFootprints(false);

        switch (newWalkMode)
        {
        case WalkMode.Footprints:
            SetWalkModeFootprints(true);
            break;

        case WalkMode.VRLookWalk:
            SetWalkModeVRLookWalk(true);
            break;
        }
        currentWalkMode = newWalkMode;
    }
Example #8
0
        public void Walkv3Async(IPAddress ipAddress, string oid, SNMPv3Security security, string username, SNMPv3AuthenticationProvider authProvider, string auth, SNMPv3PrivacyProvider privProvider, string priv, WalkMode walkMode, SNMPOptions options)
        {
            Task.Run(() =>
            {
                try
                {
                    IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, options.Port);

                    // Discovery
                    Discovery discovery  = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
                    ReportMessage report = discovery.GetResponse(options.Timeout, ipEndpoint);

                    IPrivacyProvider privacy;

                    if (security == SNMPv3Security.authPriv)
                    {
                        privacy = GetPrivacy(authProvider, auth, privProvider, priv);
                    }
                    else if (security == SNMPv3Security.authNoPriv)
                    {
                        privacy = GetPrivacy(authProvider, auth);
                    }
                    else // noAuthNoPriv
                    {
                        privacy = GetPrivacy();
                    }

                    List <Variable> results = new List <Variable>();

                    Messenger.BulkWalk(VersionCode.V3, ipEndpoint, new OctetString(username), new ObjectIdentifier(oid), results, options.Timeout, 10, walkMode, privacy, report);

                    foreach (Variable result in results)
                    {
                        OnReceived(new SNMPReceivedArgs(result.Id, result.Data));
                    }

                    OnComplete();
                }
                catch (Lextm.SharpSnmpLib.Messaging.TimeoutException)
                {
                    OnTimeout();
                }
                catch (ErrorException)
                {
                    OnError();
                }
            });
        }
Example #9
0
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="mode">Walk mode.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns></returns>
        public static async Task <int> BulkWalkAsync(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList <Variable> list, int maxRepetitions, WalkMode mode, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }

            var tableV  = new Variable(table);
            var seed    = tableV;
            var result  = 0;
            var message = report;
            var data    = await BulkHasNextAsync(version, endpoint, community, seed, maxRepetitions, privacy, message).ConfigureAwait(false);

            var next = data.Item2;

            message = data.Item3;
            while (data.Item1)
            {
                var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
                var rowMask     = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
                foreach (var v in next)
                {
                    var id = v.Id.ToString();
                    if (v.Data.TypeCode == SnmpType.EndOfMibView)
                    {
                        goto end;
                    }

                    if (mode == WalkMode.WithinSubtree && !id.StartsWith(subTreeMask, StringComparison.Ordinal))
                    {
                        // not in sub tree
                        goto end;
                    }

                    list.Add(v);
                    if (id.StartsWith(rowMask, StringComparison.Ordinal))
                    {
                        result++;
                    }
                }

                seed = next[next.Count - 1];
                data = await BulkHasNextAsync(version, endpoint, community, seed, maxRepetitions, privacy, message).ConfigureAwait(false);

                next    = data.Item2;
                message = data.Item3;
            }

end:
            return(result);
        }
Example #10
0
        private async Task <List <Variable> > SnmpWalkAsync(VersionCode snmpVersion, string oid, WalkMode walkMode)
        {
            List <Variable> snmpWalkResult = new List <Variable>();

            try
            {
                Task <int> taskWalk = Messenger.WalkAsync(snmpVersion,
                                                          new IPEndPoint(SnmpIPAddress, SnmpPort),
                                                          new OctetString(SnmpCommunity),
                                                          new ObjectIdentifier(oid),
                                                          snmpWalkResult,
                                                          walkMode);

                await taskWalk;
                return(snmpWalkResult);
            }
            catch (Exception exception)
            {
                throw new SnmpConnectionException(_localizer["SNMP request error: "] + exception.Message);
            }
        }
Example #11
0
 public CharaAnimCtrl GetAnimCtrl(WalkMode walkmode)
 {
     return(new CharaAnimCtrl(InputMode.byTransform, walkmode));
 }
Example #12
0
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="mode">Walk mode.</param>
        /// <returns>
        /// Returns row count if the OID is a table. Otherwise this value is meaningless.
        /// </returns>
        public static int Walk(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList<Variable> list, int timeout, WalkMode mode)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            var result = 0;
            var tableV = new Variable(table);
            Variable seed;
            var next = tableV;
            var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
            var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
            do
            {
                seed = next;
                if (seed == tableV)
                {
                    continue;
                }

                if (mode == WalkMode.WithinSubtree && !seed.Id.ToString().StartsWith(subTreeMask, StringComparison.Ordinal))
                {
                    // not in sub tree
                    break;
                }

                list.Add(seed);
                if (seed.Id.ToString().StartsWith(rowMask, StringComparison.Ordinal))
                {
                    result++;
                }
            }
            while (HasNext(version, endpoint, community, seed, timeout, out next));
            return result;
        }
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="mode">Walk mode.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns></returns>
        public static int BulkWalk(
            VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList <Variable> list, int timeout, int maxRepetitions, WalkMode mode,
            IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            var tableV = new Variable(table);
            var seed   = tableV;
            IList <Variable> next;
            var result  = 0;
            var message = report;

            while (BulkHasNext(version, endpoint, community, seed, timeout, maxRepetitions, out next, privacy, ref message))
            {
                var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
                var rowMask     = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
                foreach (var v in next)
                {
                    var id = v.Id.ToString();
                    if (v.Data.TypeCode == SnmpType.EndOfMibView)
                    {
                        goto end;
                    }

                    if (mode == WalkMode.WithinSubtree && !id.StartsWith(subTreeMask, StringComparison.Ordinal))
                    {
                        // not in sub tree
                        goto end;
                    }

                    list.Add(v);
                    if (id.StartsWith(rowMask, StringComparison.Ordinal))
                    {
                        result++;
                    }
                }

                seed = next[next.Count - 1];
            }

end:
            return(result);
        }
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="mode">Walk mode.</param>
        /// <returns>
        /// Returns row count if the OID is a table. Otherwise this value is meaningless.
        /// </returns>
        public static async Task <int> WalkAsync(
            VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList <Variable> list, WalkMode mode)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            var      result = 0;
            var      tableV = new Variable(table);
            Variable seed;
            var      next               = tableV;
            var      rowMask            = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
            var      subTreeMask        = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
            Tuple <bool, Variable> data = new Tuple <bool, Variable> (false, next);

            do
            {
                seed = data.Item2;
                if (seed == tableV)
                {
                    data = await HasNextAsync(version, endpoint, community, seed).ConfigureAwait(false);

                    continue;
                }

                if (mode == WalkMode.WithinSubtree && !seed.Id.ToString().StartsWith(subTreeMask, StringComparison.Ordinal))
                {
                    // not in sub tree
                    break;
                }

                list.Add(seed);
                if (seed.Id.ToString().StartsWith(rowMask, StringComparison.Ordinal))
                {
                    result++;
                }

                data = await HasNextAsync(version, endpoint, community, seed).ConfigureAwait(false);
            }while (data.Item1);
            return(result);
        }
Example #15
0
        private void WalkTree( WalkMode mode, Node node, Walker walker, int x, int y )
        {
            if ( node == null ) return;
            int size = ((1 << node.Level) >> 1);

            if ( node.Flag && node.Level >= 1 ) {
                WalkTree( mode, node.BottomRightChild, walker, x+size, y+size );
                WalkTree( mode, node.BottomLeftChild, walker, x, y+size );
                WalkTree( mode, node.TopRightChild, walker, x+size, y );
                WalkTree( mode, node.TopLeftChild, walker, x, y );
            }
            else {
                walker( node, x, y );
            }
        }
Example #16
0
 public void WalkTree( WalkMode mode, Walker walker, int x, int y )
 {
     switch ( mode ) {
         case WalkMode.Full:
             WalkTreeFull( root, walker, x, y ); break;
         case WalkMode.LeftOnly:
             WalkTreeLeft( root, walker, x, y ); break;
         case WalkMode.TopLeftOnly:
             WalkTreeTopLeft( root, walker, x, y ); break;
         case WalkMode.TopOnly:
             WalkTreeTop( root, walker, x, y ); break;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
    private async Task Receive()
    {
        while (webSocket.State == WebSocketState.Open)
        {
            var buffer   = new byte[receiveChunkSize];
            var response = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            if (response.MessageType == WebSocketMessageType.Close)
            {
                await
                webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close response received",
                                     CancellationToken.None);
            }
            else
            {
                var result = Encoding.UTF8.GetString(buffer).TrimEnd((char)0).Split('/');

                var key    = result[0];
                var action = result[1];

                if (key.Equals(Key))
                {
                    if (action.Equals("forward") && currentWalkMode < WalkMode.FORWARDS_FAST)
                    {
                        currentWalkMode++;
                    }
                    if (action.Equals("backward") && currentWalkMode > WalkMode.BACKWARDS)
                    {
                        currentWalkMode--;
                    }
                    if (action.Equals("left") && currentTurnMode > TurnMode.LEFT_HARD)
                    {
                        currentTurnMode--;
                    }
                    if (action.Equals("right") && currentTurnMode < TurnMode.RIGHT_HARD)
                    {
                        currentTurnMode++;
                    }
                    if (action.Equals("toggle"))
                    {
                        sensor.ToggleSensorRays();
                    }
                    if (action.Equals("walk"))
                    {
                        var walk = int.Parse(result[2]);
                        if (walk >= -1 && walk <= 3)
                        {
                            currentWalkMode = (WalkMode)walk;
                        }
                    }
                    if (action.Equals("turn"))
                    {
                        var turn = int.Parse(result[2]);
                        if (turn >= -2 && turn <= 2)
                        {
                            currentTurnMode = (TurnMode)turn;
                        }
                    }
                }


                Debug.Log("\"" + action + "\"");
            }
        }
    }
Example #18
0
    // Update is called once per frame
    void Update()
    {
        transform.Translate((int)currentWalkMode * Vector3.forward * Speed * Time.deltaTime);
        transform.Rotate(Vector3.up, (int)currentTurnMode * Time.deltaTime * 25);


        //pressing up key switches from BACKWARDS to STOP to FORWARDS_SLOW to FORWARDS_MEDIUM to FORWARDS_FAST
        //once reached FORWARDS_FAST, pressing up key again will not have any effect
        if (Input.GetKeyDown(KeyCode.W))
        {
            switch (currentWalkMode)
            {
            case WalkMode.BACKWARDS:
                currentWalkMode = WalkMode.STOP;
                break;

            case WalkMode.STOP:
                currentWalkMode = WalkMode.FORWARDS_SLOW;
                break;

            case WalkMode.FORWARDS_SLOW:
                currentWalkMode = WalkMode.FORWARDS_MEDIUM;
                break;

            case WalkMode.FORWARDS_MEDIUM:
                currentWalkMode = WalkMode.FORWARDS_FAST;
                break;
            }
        }


        //pressing down key switches from FORWARDS_FAST to FORWARDS_MEDIUM to FORWARDS_SLOW to STOP to BACKWARDS
        //once reached BACKWARDS, pressing down key again will not have any effect
        if (Input.GetKeyDown(KeyCode.S))
        {
            switch (currentWalkMode)
            {
            case WalkMode.FORWARDS_FAST:
                currentWalkMode = WalkMode.FORWARDS_MEDIUM;
                break;

            case WalkMode.FORWARDS_MEDIUM:
                currentWalkMode = WalkMode.FORWARDS_SLOW;
                break;

            case WalkMode.FORWARDS_SLOW:
                currentWalkMode = WalkMode.STOP;
                break;

            case WalkMode.STOP:
                currentWalkMode = WalkMode.BACKWARDS;
                break;
            }
        }
        //pressing left key switches from RIGHT_HARD to RIGHT_SMOOTH to STRAIGHT to LEFT_SMOOTH to LEFT_HARD
        //once reached LEFT_HARD, pressing left key again will not have any effect
        if (Input.GetKeyDown(KeyCode.A))
        {
            switch (currentTurnMode)
            {
            case TurnMode.RIGHT_HARD:
                currentTurnMode = TurnMode.RIGHT_SMOOTH;
                break;

            case TurnMode.RIGHT_SMOOTH:
                currentTurnMode = TurnMode.STRAIGHT;
                break;

            case TurnMode.STRAIGHT:
                currentTurnMode = TurnMode.LEFT_SMOOTH;
                break;

            case TurnMode.LEFT_SMOOTH:
                currentTurnMode = TurnMode.LEFT_HARD;
                break;
            }
        }

        //pressing right key switches from LEFT_HARD to LEFT_SMOOTH to STRAIGHT to RIGHT_SMOOTH to RIGHT_HARD
        //once reached RIGHT_HARD, pressing right key again will not have any effect
        if (Input.GetKeyDown(KeyCode.D))
        {
            switch (currentTurnMode)
            {
            case TurnMode.LEFT_HARD:
                currentTurnMode = TurnMode.LEFT_SMOOTH;
                break;

            case TurnMode.LEFT_SMOOTH:
                currentTurnMode = TurnMode.STRAIGHT;
                break;

            case TurnMode.STRAIGHT:
                currentTurnMode = TurnMode.RIGHT_SMOOTH;
                break;

            case TurnMode.RIGHT_SMOOTH:
                currentTurnMode = TurnMode.RIGHT_HARD;
                break;
            }
        }
    }
Example #19
0
        private void PrepareForNewWalkBehaviour(WorldCoordinate pFinalTargetPosition, Ting pFinalTargetTing, WalkMode pWalkMode)
        {
            #if LOG
            logger.Log(name + " is preparing new walk behaviour with final target position " + pFinalTargetPosition);
            #endif

            if (pFinalTargetTing is Computer) {
                var tile = pFinalTargetTing.room.GetTile(pFinalTargetTing.interactionPoints[0]);
                if(tile != null) {
                    var chairInFrontOfComputer = tile.GetOccupantOfType<Seat>();
                    if(chairInFrontOfComputer != null) {
                        pFinalTargetTing = chairInFrontOfComputer;
                        pWalkMode = WalkMode.WALK_TO_TING_AND_INTERACT; // changes the intent of the player
                    }
                } else {
                    D.Log("Tile at interaction point for computer " + pFinalTargetTing + " is null, " + name + " can't walk there.");
                }
            }
            else if (pFinalTargetTing is Tram) {
                var tram = pFinalTargetTing as Tram;
                if(tram.movingDoor != null) {
                    //pFinalTargetTing = tram.movingDoor;
                    WalkToTingAndInteract (tram.movingDoor);
                    D.Log("Switched target for " + name + " from " + tram + " to " + tram.movingDoor);
                    return;
                }
            }

            if (pFinalTargetTing is Seat && pFinalTargetTing == this.seat) {
                #if LOG
                logger.Log(name + " can't sit on seat " + pFinalTargetTing + " since she/he is already doing that.");
                #endif
                return;
            }

            if (pFinalTargetTing is Bed && pFinalTargetTing == this.bed) {
                #if LOG
                logger.Log(name + " can't lay in bed " + pFinalTargetTing + " since she/he is already doing that.");
                #endif
                return;
            }

            finalTargetPosition = pFinalTargetPosition;
            finalTargetTing = pFinalTargetTing;
            walkMode = pWalkMode;
            walkIterator = 0;

            //			if (actionName == "GettingUpFromSeat" || actionName == "GettingUpFromBed") {
            //				return;
            //			} else if (actionName == "PickingUp" || actionName == "Dropping" || actionName == "DroppingFar") {
            //				return;
            //			}
            if (busy) {
                return;
            }
            else if (sitting) {
                if (seat != null) {
                    GetUpFromSeat ();
                    return;
                } else {
                    //D.Log("Just start walking (from sitting)");
                    sitting = false;
                }
            } else if (laying) {
                if (bed != null) {
                    GetUpFromBed ();
                    return;
                } else {
                    //D.Log ("Just start walking (from laying down)");
                    laying = false;
                }
            }

            _walkBehaviour = null;

            ClearConversationTarget();
            seat = null;
            bed = null;
        }
Example #20
0
        public static void Main(string[] args)
        {
            string      community      = "public";
            bool        dump           = true;
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            int         maxRepetitions = 10;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            WalkMode    mode           = WalkMode.WithinSubtree;

            OptionSet p = new OptionSet()
                          .Add("c:", "-c for community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                        {
                                                                                                            community = v;
                                                                                                        }
                               })
                          .Add("l:", "-l for security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "-a for authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "-A for authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "-x for privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "-X for privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "-u for security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "-h, -?, -help for help.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "-V to display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("d", "-d to display message dump", delegate(string v) { dump = true; })
                          .Add("t:", "-t for timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "-r for retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v|version:", "-v for SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            })
                          .Add("m|mode:", "-m for WALK mode (subtree, all are supported)", delegate(string v)
            {
                if (v == "subtree")
                {
                    mode = WalkMode.WithinSubtree;
                }
                else if (v == "all")
                {
                    mode = WalkMode.Default;
                }
                else
                {
                    throw new ArgumentException("unknown argument: " + v);
                }
            })
                          .Add("Cr:", "-Cr for max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(v); });

            List <string> extra = p.Parse(args);

            if (showHelp)
            {
                ShowHelp();
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            if (extra.Count < 1 || extra.Count > 2)
            {
                ShowHelp();
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                foreach (IPAddress address in Dns.GetHostAddresses(extra[0]))
                {
                    if (address.AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                ObjectIdentifier test     = extra.Count == 1 ? new ObjectIdentifier("1.3.6.1.2.1") : new ObjectIdentifier(extra[1]);
                IList <Variable> result   = new List <Variable>();
                IPEndPoint       receiver = new IPEndPoint(ip, 161);
                if (version == VersionCode.V1)
                {
                    Messenger.Walk(version, receiver, new OctetString(community), test, result, timeout, mode);
                }
                else if (version == VersionCode.V2)
                {
                    Messenger.BulkWalk(version, receiver, new OctetString(community), test, result, timeout, maxRepetitions, mode, null, null);
                }
                else
                {
                    if (string.IsNullOrEmpty(user))
                    {
                        Console.WriteLine("User name need to be specified for v3.");
                        return;
                    }

                    IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication ? GetAuthenticationProviderByName(authentication, authPhrase) : DefaultAuthenticationProvider.Instance;

                    IPrivacyProvider priv;
                    if ((level & Levels.Privacy) == Levels.Privacy)
                    {
                        priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                    }
                    else
                    {
                        priv = new DefaultPrivacyProvider(auth);
                    }

                    Discovery     discovery = Messenger.NextDiscovery;
                    ReportMessage report    = discovery.GetResponse(timeout, receiver);

                    Messenger.BulkWalk(version, receiver, new OctetString(user), test, result, timeout, maxRepetitions, mode, priv, report);
                }

                foreach (Variable variable in result)
                {
                    Console.WriteLine(variable);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #21
0
        public void Walkv1v2cAsync(SNMPVersion version, IPAddress ipAddress, string community, string oid, WalkMode walkMode, SNMPOptions options)
        {
            Task.Run(() =>
            {
                try
                {
                    IList <Variable> results = new List <Variable>();

                    Messenger.Walk(version == SNMPVersion.v1 ? VersionCode.V1 : VersionCode.V2, new IPEndPoint(ipAddress, options.Port), new OctetString(community), new ObjectIdentifier(oid), results, options.Timeout, walkMode);

                    foreach (Variable result in results)
                    {
                        OnReceived(new SNMPReceivedArgs(result.Id, result.Data));
                    }

                    OnComplete();
                }
                catch (Lextm.SharpSnmpLib.Messaging.TimeoutException)
                {
                    OnTimeout();
                }
                catch (ErrorException)
                {
                    OnError();
                }
            });
        }
Example #22
0
        public static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            int         maxRepetitions = 10;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      contextName    = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            WalkMode    mode           = WalkMode.WithinSubtree;
            bool        dump           = false;

            OptionSet p = new OptionSet()
                          .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                 {
                                                                                                     community = v;
                                                                                                 }
                               })
                          .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "Security name", delegate(string v) { user = v; })
                          .Add("C:", "Context name", delegate(string v) { contextName = v; })
                          .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("d", "Display message dump", delegate(string v) { dump = true; })
                          .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v|version:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                if (v == "2c")
                {
                    v = "2";
                }

                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            })
                          .Add("m|mode:", "WALK mode (subtree, all are supported)", delegate(string v)
            {
                if (v == "subtree")
                {
                    mode = WalkMode.WithinSubtree;
                }
                else if (v == "all")
                {
                    mode = WalkMode.Default;
                }
                else
                {
                    throw new ArgumentException("unknown argument: " + v);
                }
            })
                          .Add("Cr:", "Max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(v); });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if (extra.Count < 1 || extra.Count > 2)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyVersionAttribute>().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                var addresses = Dns.GetHostAddressesAsync(extra[0]);
                addresses.Wait();
                foreach (IPAddress address in
                         addresses.Result.Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                ObjectIdentifier test     = extra.Count == 1 ? new ObjectIdentifier("1.3.6.1.2.1") : new ObjectIdentifier(extra[1]);
                IList <Variable> result   = new List <Variable>();
                IPEndPoint       receiver = new IPEndPoint(ip, 161);
                if (version == VersionCode.V1)
                {
                    Messenger.Walk(version, receiver, new OctetString(community), test, result, timeout, mode);
                }
                else if (version == VersionCode.V2)
                {
                    Messenger.BulkWalk(version, receiver, new OctetString(community), new OctetString(string.IsNullOrWhiteSpace(contextName) ? string.Empty: contextName), test, result, timeout, maxRepetitions, mode, null, null);
                }
                else
                {
                    if (string.IsNullOrEmpty(user))
                    {
                        Console.WriteLine("User name need to be specified for v3.");
                        return;
                    }

                    IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                        ? GetAuthenticationProviderByName(authentication, authPhrase)
                        : DefaultAuthenticationProvider.Instance;
                    IPrivacyProvider priv;
                    if ((level & Levels.Privacy) == Levels.Privacy)
                    {
                        if (DESPrivacyProvider.IsSupported)
                        {
                            priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                        }
                        else
                        {
                            Console.WriteLine("DES (ECB) is not supported by .NET Core.");
                            return;
                        }
                    }
                    else
                    {
                        priv = new DefaultPrivacyProvider(auth);
                    }

                    Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetBulkRequestPdu);
                    ReportMessage report    = discovery.GetResponse(timeout, receiver);
                    Messenger.BulkWalk(version, receiver, new OctetString(user), new OctetString(string.IsNullOrWhiteSpace(contextName) ? string.Empty : contextName), test, result, timeout, maxRepetitions, mode, priv, report);
                }

                foreach (Variable variable in result)
                {
                    Console.WriteLine(variable);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #23
0
        /// <summary>
        /// Allows us to control the robot with the direction keys on the keybord. Also gives visual feedback in which direction the robot currently turns
        /// and at which velocity.
        /// </summary>
        private void CurrentMode(WalkMode walkMode, TurnMode turnMode)
        {
            switch (walkMode)
            {
            case WalkMode.FORWARDS_FAST:
                Console.WriteLine("       ^       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                break;

            case WalkMode.FORWARDS_MEDIUM:
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("       ^       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                break;

            case WalkMode.FORWARDS_SLOW:
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("       ^       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                break;

            case WalkMode.BACKWARDS:
                break;

            case WalkMode.STOP:
                break;

            default:
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                break;
            }

            Console.WriteLine("      ███      ");

            switch (turnMode)
            {
            case TurnMode.LEFT_HARD:
                Console.WriteLine(" <----███      ");
                break;

            case TurnMode.LEFT_SMOOTH:
                Console.WriteLine("   <--███      ");
                break;

            case TurnMode.STRAIGHT:
                Console.WriteLine("      ███      ");
                break;

            case TurnMode.RIGHT_SMOOTH:
                Console.WriteLine("      ███--> ");
                break;

            case TurnMode.RIGHT_HARD:
                Console.WriteLine("      ███----> ");
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(turnMode), turnMode, null);
            }

            Console.WriteLine("      ███      ");

            switch (walkMode)
            {
            case WalkMode.BACKWARDS:
                Console.WriteLine("       |       ");
                Console.WriteLine("       |       ");
                Console.WriteLine("       V       ");
                break;

            case WalkMode.STOP:
                break;

            case WalkMode.FORWARDS_SLOW:
                break;

            case WalkMode.FORWARDS_MEDIUM:
                break;

            case WalkMode.FORWARDS_FAST:
                break;

            default:
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                Console.WriteLine("               ");
                break;
            }
        }
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="mode">Walk mode.</param>
        /// <returns>
        /// Returns row count if the OID is a table. Otherwise this value is meaningless.
        /// </returns>
        public static int Walk(
            VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList <Variable> list, int timeout, WalkMode mode)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            var      result = 0;
            var      tableV = new Variable(table);
            Variable seed;
            var      next        = tableV;
            var      rowMask     = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
            var      subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);

            do
            {
                seed = next;
                if (seed == tableV)
                {
                    continue;
                }

                if (mode == WalkMode.WithinSubtree && !seed.Id.ToString().StartsWith(subTreeMask, StringComparison.Ordinal))
                {
                    // not in sub tree
                    break;
                }

                list.Add(seed);
                if (seed.Id.ToString().StartsWith(rowMask, StringComparison.Ordinal))
                {
                    result++;
                }
            }while (HasNext(version, endpoint, community, seed, timeout, out next));
            return(result);
        }
Example #25
0
        public void WalkV3Async(IPAddress ipAddress, string oid, SNMPV3Security security, string username, SNMPV3AuthenticationProvider authProvider, SecureString auth, SNMPV3PrivacyProvider privProvider, SecureString priv, WalkMode walkMode)
        {
            Task.Run(() =>
            {
                try
                {
                    var ipEndpoint = new IPEndPoint(ipAddress, Port);

                    // Discovery
                    var discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
                    var report    = discovery.GetResponse(Timeout, ipEndpoint);

                    IPrivacyProvider privacy;

                    switch (security)
                    {
                    case SNMPV3Security.AuthPriv:
                        privacy = GetPrivacy(authProvider, SecureStringHelper.ConvertToString(auth), privProvider, SecureStringHelper.ConvertToString(priv));
                        break;

                    // noAuthNoPriv
                    case SNMPV3Security.AuthNoPriv:
                        privacy = GetPrivacy(authProvider, SecureStringHelper.ConvertToString(auth));
                        break;

                    default:
                        privacy = GetPrivacy();
                        break;
                    }

                    var results = new List <Variable>();

                    Messenger.BulkWalk(VersionCode.V3, ipEndpoint, new OctetString(username), OctetString.Empty, new ObjectIdentifier(oid), results, Timeout, 10, walkMode, privacy, report);

                    foreach (var result in results)
                    {
                        OnReceived(new SNMPReceivedArgs(result.Id, result.Data));
                    }

                    OnComplete();
                }
                catch (Lextm.SharpSnmpLib.Messaging.TimeoutException)
                {
                    OnTimeoutReached();
                }
                catch (ErrorException)
                {
                    OnError();
                }
            });
        }
Example #26
0
        public void WalkV1V2CAsync(SNMPVersion version, IPAddress ipAddress, SecureString community, string oid, WalkMode walkMode)
        {
            Task.Run(() =>
            {
                try
                {
                    IList <Variable> results = new List <Variable>();

                    Messenger.Walk(version == SNMPVersion.V1 ? VersionCode.V1 : VersionCode.V2, new IPEndPoint(ipAddress, Port), new OctetString(SecureStringHelper.ConvertToString(community)), new ObjectIdentifier(oid), results, Timeout, walkMode);

                    foreach (var result in results)
                    {
                        OnReceived(new SNMPReceivedArgs(result.Id, result.Data));
                    }

                    OnComplete();
                }
                catch (Lextm.SharpSnmpLib.Messaging.TimeoutException)
                {
                    OnTimeoutReached();
                }
                catch (ErrorException)
                {
                    OnError();
                }
            });
        }
Example #27
0
        private async Task <List <Variable> > SnmpWalkAsyncWithTimeout(VersionCode snmpVersion, string oid, WalkMode walkMode, int snmpRequestTimeout)
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            Task timeoutTask = Task.Delay(snmpRequestTimeout);
            Task <List <Variable> > task;

            if (await Task.WhenAny(task = SnmpWalkAsync(snmpVersion, oid, walkMode), timeoutTask) == timeoutTask)
            {
                cancellationTokenSource.Cancel();
                throw new SnmpTimeoutException(_localizer["SNMP request timeout"]);
            }

            return(await task);
        }
Example #28
0
        /// <summary>
        /// Walks.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="table">OID.</param>
        /// <param name="list">A list to hold the results.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="mode">Walk mode.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="report">The report.</param>
        /// <returns></returns>
        public static int BulkWalk(VersionCode version, IPEndPoint endpoint, OctetString community, ObjectIdentifier table, IList<Variable> list, int timeout, int maxRepetitions, WalkMode mode, IPrivacyProvider privacy, ISnmpMessage report)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            var tableV = new Variable(table);
            var seed = tableV;
            IList<Variable> next;
            var result = 0;
            var message = report;
            while (BulkHasNext(version, endpoint, community, seed, timeout, maxRepetitions, out next, privacy, ref message))
            {
                var subTreeMask = string.Format(CultureInfo.InvariantCulture, "{0}.", table);
                var rowMask = string.Format(CultureInfo.InvariantCulture, "{0}.1.1.", table);
                foreach (var v in next)
                {
                    var id = v.Id.ToString();
                    if (v.Data.TypeCode == SnmpType.EndOfMibView)
                    {
                        goto end;
                    }

                    if (mode == WalkMode.WithinSubtree && !id.StartsWith(subTreeMask, StringComparison.Ordinal))
                    {
                        // not in sub tree
                        goto end;
                    }

                    list.Add(v);
                    if (id.StartsWith(rowMask, StringComparison.Ordinal))
                    {
                        result++;
                    }
                }

                seed = next[next.Count - 1];
            }

        end:
            return result;
        }
Example #29
0
 public CharaAnimCtrl GetAnimCtrl(InputMode inputMode, WalkMode walkmode)
 {
     return(new CharaAnimCtrl(inputMode, walkmode));
 }