Beispiel #1
0
 public IEnumerator <ITask> SetByKeyHandler(SetByKey set)
 {
     try
     {
         if (set.Body.Keys.Count != set.Body.Values.Count)
         {
             throw new ArgumentException("Lengths of indices and values lists must match");
         }
         var indices = new List <int>(set.Body.Keys.Count);
         for (int i = 0; i < set.Body.Keys.Count; i++)
         {
             int index = _state.indexCache[set.Body.Keys[i]];
             _state.Values[index] = set.Body.Values[i];
             indices.Add(index);
         }
         SetCallback(new SetElementsRequestInfo()
         {
             RequestType = RequestType.ByKey,
             Indices     = indices,
             Keys        = set.Body.Keys,
             Timestamp   = set.Body.Timestamp,
             Values      = set.Body.Values
         });
         set.ResponsePort.Post(DefaultUpdateResponseType.Instance);
         SendNotification <SetByKey>(set);
     }
     catch (Exception e)
     {
         set.ResponsePort.Post(RSUtils.FaultOfException(e));
     }
     yield break;
 }
Beispiel #2
0
        public void SetMotors(double leftPower, double rightPower)
        {
            if (!motorsOn)
            {
                EnableMotors();
            }

            //drive.SetDrivePowerRequest drivePowerReq = new drive.SetDrivePowerRequest();
            //drivePowerReq.LeftWheelPower = leftPower;
            //drivePowerReq.RightWheelPower = rightPower;
            //drive.SetDrivePower setDrivePower = new drive.SetDrivePower(drivePowerReq);
            //drivePort.Post(setDrivePower);

            //ManualResetEvent signal = new ManualResetEvent(false);
            //Arbiter.Activate(DssEnvironment.TaskQueue,
            //    Arbiter.Choice<DefaultUpdateResponseType, Fault>(
            //        drivePort.SetDrivePower((double)leftPower, (double)rightPower),
            //        delegate(DefaultUpdateResponseType state)
            //        {
            //            signal.Set();
            //        },
            //        delegate(Fault failure)
            //        {
            //            Console.WriteLine("*** Fault in SetMotors: ");
            //            foreach (var r in failure.Reason)
            //                Console.WriteLine("***    " + r.Value);
            //            signal.Set();
            //        }));
            //signal.WaitOne();
            RSUtils.ReceiveSync(taskQueue, drivePort.SetDrivePower(leftPower, rightPower), Myro.Utilities.Params.DefaultRecieveTimeout);
        }
Beispiel #3
0
 public IEnumerator <ITask> SetByIndexHandler(SetByIndex set)
 {
     try
     {
         if (set.Body.Indices.Count != set.Body.Values.Count)
         {
             throw new ArgumentException("Lengths of indices and values lists must match");
         }
         for (int i = 0; i < set.Body.Indices.Count; i++)
         {
             _state.Values[set.Body.Indices[i]] = set.Body.Values[i];
         }
         _state.Timestamp = set.Body.Timestamp;
         SetCallback(new SetElementsRequestInfo()
         {
             RequestType = RequestType.ByIndex,
             Indices     = set.Body.Indices,
             Keys        = new List <string>(
                 from i in set.Body.Indices
                 select(i < _state.Keys.Count ? _state.Keys[i] : "")),
             Timestamp = set.Body.Timestamp,
             Values    = set.Body.Values
         });
         set.ResponsePort.Post(DefaultUpdateResponseType.Instance);
         SendNotification <SetByIndex>(set);
     }
     catch (Exception e)
     {
         set.ResponsePort.Post(RSUtils.FaultOfException(e));
     }
     yield break;
 }
Beispiel #4
0
 /// <summary>
 /// Set the motor power.
 /// </summary>
 /// <param name="leftPower"></param>
 /// <param name="rightPower"></param>
 public void SetMotors(double leftPower, double rightPower)
 {
     if (!motorsOn)
     {
         EnableMotors();
     }
     RSUtils.ReceiveSync(taskQueue, drivePort.SetDrivePower(leftPower, rightPower), Myro.Utilities.Params.DefaultRecieveTimeout);
 }
Beispiel #5
0
 /// <summary>
 /// Set a single element in the vector by name.
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="value"></param>
 public void Set(string key, double value)
 {
     RSUtils.ReceiveSync <DefaultUpdateResponseType>(taskQueue, opPort.SetByKey(new List <string>()
     {
         key
     }, new List <double>()
     {
         value
     }, DateTime.Now), Myro.Utilities.Params.DefaultRecieveTimeout);
 }
Beispiel #6
0
 /// <summary>
 /// Set a single element in the vector by index.
 /// </summary>
 /// <param name="index"></param>
 /// <param name="value"></param>
 public void Set(int index, double value)
 {
     RSUtils.ReceiveSync <DefaultUpdateResponseType>(taskQueue, opPort.SetByIndex(new List <int>()
     {
         index
     }, new List <double>()
     {
         value
     }, DateTime.Now), Myro.Utilities.Params.DefaultRecieveTimeout);
 }
Beispiel #7
0
 /// <summary>
 /// Set a group of elements in the vector by name.
 /// </summary>
 /// <param name="index"></param>
 /// <param name="value"></param>
 public void Set(List <string> keys, List <double> values)
 {
     //try
     //{
     RSUtils.ReceiveSync <DefaultUpdateResponseType>(taskQueue, opPort.SetByKey(keys, values, DateTime.Now), Myro.Utilities.Params.defaultRecieveTimeout);
     //}
     //catch (KeyNotFoundException)
     //{
     //    throw new AdapterArgumentException(Strings.KeyNotFound());
     //}
 }
Beispiel #8
0
 protected override IEnumerator <ITask> GetCallback(Myro.Services.Generic.Vector.GetRequestInfo request, PortSet <Myro.Services.Generic.Vector.CallbackResponseType, Fault> responsePort)
 {
     if (request is vector.GetAllRequestInfo)
     {
         PortSet <DefaultQueryResponseType, Fault> responses = new PortSet <DefaultQueryResponseType, Fault>();
         for (int i = 0; i < _state.Values.Count; i++)
         {
             int myI = i;
             Activate(Arbiter.Choice(_scribblerPort.GetObstacle(i),
                                     delegate(brick.UInt16Body r)
             {
                 _state.Set(myI, RSUtils.NormalizeUShort(r.Value), DateTime.Now);
                 responses.Post(DefaultQueryResponseType.Instance);
             },
                                     delegate(Fault f) { responses.Post(f); }));
         }
         yield return(Arbiter.MultipleItemReceive(responses, _state.Values.Count,
                                                  delegate(ICollection <DefaultQueryResponseType> ss, ICollection <Fault> fs)
         {
             if (fs.Count == 0)
             {
                 responsePort.Post(vector.CallbackResponseType.Instance);
             }
             else
             {
                 var reasons = new List <ReasonText>();
                 foreach (var f in fs)
                 {
                     reasons.AddRange(f.Reason.AsEnumerable());
                 }
                 responsePort.Post(new Fault()
                 {
                     Detail = new Detail()
                     {
                         Any = fs.ToArray()
                     }, Reason = reasons.ToArray()
                 });
             }
         }));
     }
     else
     {
         var info = (vector.GetElementRequestInfo)request;
         yield return(Arbiter.Choice(_scribblerPort.GetObstacle(info.Index),
                                     delegate(brick.UInt16Body r)
         {
             _state.Set(info.Index, RSUtils.NormalizeUShort(r.Value), DateTime.Now);
             responsePort.Post(vector.CallbackResponseType.Instance);
         },
                                     delegate(Fault f) { responsePort.Post(f); }));
     }
     yield break;
 }
Beispiel #9
0
        protected virtual void Initialize()
        {
            // Initialize the port and subscribe to the service to know when the motors are enabled
            motorsOn  = false;
            drivePort = DssEnvironment.ServiceForwarder <drive.DriveOperations>(new Uri(ServiceInfo.Service));
            drive.DriveOperations driveNotificationPort = new drive.DriveOperations();
            RSUtils.ReceiveSync(taskQueue, drivePort.Subscribe(driveNotificationPort), Params.DefaultRecieveTimeout);

            // Set up notifications
            Arbiter.Activate(DssEnvironment.TaskQueue,
                             Arbiter.Receive <drive.Update>(true, driveNotificationPort, NotifyDriveUpdate));
        }
Beispiel #10
0
        public void QueryFrame(MyroImageType type, out int Width, out int Height, out byte[] Image)
        {
            var r = RSUtils.ReceiveSync(queue,
                                        opPort.QueryFrame(new webcam.QueryFrameRequest()
            {
                Format = type.Guid
            }),
                                        Params.DefaultRecieveTimeout);

            Width  = r.Size.Width;
            Height = r.Size.Height;
            Image  = r.Frame;
        }
Beispiel #11
0
        protected void InitValues()
        {
            ReceivedFirstRender = false;

            string rand = RSUtils.RandomString();

            if (RenderLoopName == null || RenderLoopName.Length == 0)
            {
                RenderLoopName = "loop_" + rand;
            }

            KeepAliveService = new RSService(Scene.Host, Scene.Port);
        }
Beispiel #12
0
        /// <summary>
        /// Retrieve a single element from the state vetor, by name, with full
        /// safety checks.  Throws AdapterArgumentException and
        /// AdapterOperationException.
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public double Get(string key)
        {
            //try
            //{
            var resp = RSUtils.ReceiveSync <vector.GetElementResponseType>(taskQueue, opPort.GetByKey(key), Myro.Utilities.Params.defaultRecieveTimeout);

            return(resp.Value);
            //}
            //catch (KeyNotFoundException)
            //{
            //    throw new AdapterArgumentException(Strings.KeyNotFound(key));
            //}
        }
Beispiel #13
0
        /// <summary>
        /// Retrieve a single element from the state vector, with full safety
        /// checks.  Throws AdapterArgumentException and
        /// AdapterOperationException.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public double Get(int index)
        {
            //try
            //{
            var resp = RSUtils.ReceiveSync <vector.GetElementResponseType>(taskQueue, opPort.GetByIndex(index), Myro.Utilities.Params.defaultRecieveTimeout);

            return(resp.Value);
            //}
            //catch (ArgumentOutOfRangeException)
            //{
            //    throw new AdapterArgumentException(Strings.IndexOutOfBounds(index));
            //}
        }
Beispiel #14
0
 /// <summary>
 /// "Darken" the camera, so that it only sees bright lights.  This
 /// turns off automatic exposure, gain, and white balance.
 /// </summary>
 /// <param name="level"></param>
 public void DarkenCamera(byte level)
 {
     RSUtils.ReceiveSync(queue, opPort.SetCamera(new fluke.CamControlState()
     {
         Darkness         = level,
         Val1             = 0,
         Val2             = 0,
         Brightness       = 0,
         Exposure         = 0,
         AutoExposure     = false,
         AutoGain         = false,
         AutoWhiteBalance = false
     }), Params.DefaultRecieveTimeout);
 }
Beispiel #15
0
 /// <summary>
 /// Return the camera to automatic mode, auto exposure, gain, and WB.
 /// </summary>
 public void AutoCamera()
 {
     RSUtils.ReceiveSync(queue, opPort.SetCamera(new fluke.CamControlState()
     {
         Darkness         = 0,
         Val1             = 0x80,
         Val2             = 0x80,
         Brightness       = b.ScribblerHelper.CameraParams.CAM_BRT_DEFAULT,
         Exposure         = b.ScribblerHelper.CameraParams.CAM_EXP_DEFAULT,
         AutoExposure     = true,
         AutoGain         = true,
         AutoWhiteBalance = true
     }), Params.DefaultRecieveTimeout);
 }
Beispiel #16
0
 /// <summary>
 /// Set a group of elements in the vector by index.
 /// </summary>
 /// <param name="index"></param>
 /// <param name="value"></param>
 public void Set(List <int> indices, List <double> values)
 {
     //try
     //{
     RSUtils.ReceiveSync <DefaultUpdateResponseType>(taskQueue, opPort.SetByIndex(indices, values, DateTime.Now), Myro.Utilities.Params.defaultRecieveTimeout);
     //}
     //catch (ArgumentOutOfRangeException e)
     //{
     //    throw new AdapterArgumentException(
     //        e.ActualValue is Int32 ?
     //        Strings.IndexOutOfBounds((Int32)e.ActualValue) :
     //        Strings.IndexOutOfBounds());
     //}
 }
Beispiel #17
0
        public IEnumerator <ITask> HttpGetHandler(HttpGet get)
        {
            VectorState response = _state;

            try
            {
                GetCallback(new GetAllRequestInfo());
                get.ResponsePort.Post(new HttpResponseType(_state));
            }
            catch (Exception e)
            {
                get.ResponsePort.Post(RSUtils.FaultOfException(e));
            }
            yield break;
        }
Beispiel #18
0
        public IEnumerator <ITask> QueryFrameHandler(webcam.QueryFrame req)
        {
            yield return(Arbiter.Choice(_scribblerPort.GetImage(req.Body.Format),
                                        delegate(brick.ImageResponse r)
            {
                try
                {
                    var resp = new webcam.QueryFrameResponse()
                    {
                        Format = req.Body.Format,
                        Size = new System.Drawing.Size(r.Width, r.Height),
                        TimeStamp = r.Timestamp,
                    };
                    if (req.Body.Format.Equals(MyroImageType.Color.Guid))
                    {
                        resp.Frame = convertColorToRGB(r.Data, r.Width, r.Height);
                    }
                    else if (req.Body.Format.Equals(MyroImageType.Gray.Guid))
                    {
                        resp.Frame = r.Data;
                    }
                    else if (req.Body.Format.Equals(MyroImageType.JpegColor.Guid) ||
                             req.Body.Format.Equals(MyroImageType.JpegColorFast.Guid))
                    {
                        resp.Frame = r.Data;
                    }
                    else if (req.Body.Format.Equals(MyroImageType.JpegGray.Guid) ||
                             req.Body.Format.Equals(MyroImageType.JpegGrayFast.Guid))
                    {
                        resp.Frame = r.Data;
                    }
                    else
                    {
                        throw new Exception("FlukeCam does not know how to convert this image type");
                    }

                    req.ResponsePort.Post(resp);
                }
                catch (Exception e)
                {
                    req.ResponsePort.Post(RSUtils.FaultOfException(e));
                }
            },
                                        delegate(Fault f)
            {
                req.ResponsePort.Post(f);
            }));
        }
Beispiel #19
0
 /// <summary>
 /// Set a single element in the vector by index.
 /// </summary>
 /// <param name="index"></param>
 /// <param name="value"></param>
 public void Set(int index, double value)
 {
     //try
     //{
     RSUtils.ReceiveSync <DefaultUpdateResponseType>(taskQueue, opPort.SetByIndex(new List <int>()
     {
         index
     }, new List <double>()
     {
         value
     }, DateTime.Now), Myro.Utilities.Params.defaultRecieveTimeout);
     //}
     //catch (ArgumentOutOfRangeException)
     //{
     //    throw new AdapterArgumentException(Strings.IndexOutOfBounds(index));
     //}
 }
Beispiel #20
0
 /// <summary>
 /// Set a single element in the vector by name.
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="value"></param>
 public void Set(string key, double value)
 {
     //try
     //{
     RSUtils.ReceiveSync <DefaultUpdateResponseType>(taskQueue, opPort.SetByKey(new List <string>()
     {
         key
     }, new List <double>()
     {
         value
     }, DateTime.Now), Myro.Utilities.Params.DefaultRecieveTimeout);
     //}
     //catch (KeyNotFoundException)
     //{
     //    throw new AdapterArgumentException(Strings.KeyNotFound(key));
     //}
 }
Beispiel #21
0
        /// <summary>
        /// This is a helper mehtod that connects the Scribbler on the specified
        /// COM port.  It waits for the connection to complete, and re-throws any
        /// exceptions generated by the Scribbler service.
        /// </summary>
        /// <param name="comPort"></param>
        private static void connectWaitForScribbler(string comPort)
        {
            ManualResetEvent evt = new ManualResetEvent(false);

            waitForService(new ServiceInfoType(scribbler.Contract.Identifier),
                           delegate(ServiceInfoType info) { brickService = info; evt.Set(); });
            evt.WaitOne(Params.DefaultRecieveTimeout, false);
            if (brickService == null)
            {
                throw new MyroInitException("Could not find Scribbler service");
            }
            var             scribPort = DssEnvironment.ServiceForwarder <scribbler.ScribblerOperations>(new Uri(brickService.Service));
            DispatcherQueue queue     = new DispatcherQueue("init", new Dispatcher());

            try
            {
                if (comPort != null)
                {
                    int comNumber;
                    if (comPort.ToLower().StartsWith("com"))
                    {
                        comNumber = Int32.Parse(comPort.Substring(3));
                    }
                    else
                    {
                        throw new MyroInitException("COM port string must be of the format com2, com5, etc.");
                    }
                    RSUtils.ReceiveSync(queue, scribPort.Replace(new scribbler.ScribblerState()
                    {
                        ComPort = comNumber
                    }), Params.DefaultRecieveTimeout);
                }
                DssEnvironment.LogInfo("calling reconnect...");
                RSUtils.ReceiveSync(queue, scribPort.Reconnect(), Params.DefaultRecieveTimeout);
                DssEnvironment.LogInfo("reconnect returned");
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                queue.Dispose();
            }
        }
Beispiel #22
0
        private T tryCreateAdapter()
        {
            lock (this)
            {
                try
                {
                    // Query the service initially
                    PortSet <LookupResponse, Fault> responsePort = new PortSet <LookupResponse, Fault>();
                    DssEnvironment.ServiceForwarderUnknownType(new Uri("dssp.tcp://localhost/" + Name)).PostUnknownType(
                        new DsspDefaultLookup()
                    {
                        Body = new LookupRequestType(), ResponsePort = responsePort
                    });
                    ServiceInfoType responseRecord = RSUtils.ReceiveSync(responsePort, Myro.Utilities.Params.DefaultRecieveTimeout);

                    // Try to find a working contract for each adapter
                    foreach (var factory in adapterFactories)
                    {
                        try
                        {
                            ServiceInfoType serviceRecord = RSUtils.FindCompatibleContract(responseRecord, factory.SupportedContracts);
                            T ret = (T)factory.Create(serviceRecord);
                            Console.WriteLine("Attached to " + serviceRecord.Service + " as \"" + Name + "\"");
                            return(ret);
                        }
                        catch (NoContractFoundException) { }
                    }

                    // If we haven't returned already in the loop, we didn't find
                    // an adapter that works.
                    throw new NoAdapterFoundException(responseRecord);
                }
                catch (NoAdapterFoundException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    DssEnvironment.LogError("Error querying or attaching to " + "dssp.tcp://localhost/" + Name + ": " + e.ToString());
                    throw;
                }
            }
        }
Beispiel #23
0
 public IEnumerator <ITask> ReplaceHandler(Replace replace)
 {
     _state = replace.Body;
     try
     {
         SetCallback(new SetAllRequestInfo()
         {
             Timestamp = replace.Body.Timestamp,
             Values    = replace.Body.Values
         });
         replace.ResponsePort.Post(DefaultReplaceResponseType.Instance);
         SendNotification <Replace>(replace);
     }
     catch (Exception e)
     {
         replace.ResponsePort.Post(RSUtils.FaultOfException(e));
     }
     yield break;
 }
Beispiel #24
0
        private DsspResponsePort <vector.CallbackResponseType> playTone()
        {
            var responsePort = new DsspResponsePort <vector.CallbackResponseType>();

            brick.PlayToneBody play = new brick.PlayToneBody()
            {
                Frequency1 = (int)Math.Round(_state.Values[0]),
                Frequency2 = (int)Math.Round(_state.Values[1]),
                Duration   = (int)Math.Round(_state.Values[2])
            };
            if (play.Frequency1 < 0 || play.Frequency2 < 0 || play.Duration < 0)
            {
                responsePort.Post(RSUtils.FaultOfException(new ArgumentOutOfRangeException()));
            }
            else
            {
                Activate(Arbiter.Choice(_scribblerPort.PlayTone(play),
                                        delegate(DefaultUpdateResponseType success) { responsePort.Post(vector.CallbackResponseType.Instance); },
                                        delegate(Fault failure) { responsePort.Post(failure); }));
            }
            return(responsePort);
        }
Beispiel #25
0
 public IEnumerator <ITask> GetByKeyHandler(GetByKey get)
 {
     try
     {
         GetElementResponseType response = new GetElementResponseType()
         {
             Value     = _state.Get(get.Body.Key),
             Timestamp = _state.Timestamp
         };
         GetCallback(new GetElementRequestInfo()
         {
             RequestType = RequestType.ByKey,
             Index       = _state.indexCache[get.Body.Key],
             Key         = get.Body.Key
         });
         get.ResponsePort.Post(response);
     }
     catch (Exception e)
     {
         get.ResponsePort.Post(RSUtils.FaultOfException(e));
     }
     yield break;
 }
Beispiel #26
0
 public IEnumerator <ITask> GetByIndexHandler(GetByIndex get)
 {
     try
     {
         GetElementResponseType response = new GetElementResponseType()
         {
             Value     = _state.Get(get.Body.Index),
             Timestamp = _state.Timestamp
         };
         GetCallback(new GetElementRequestInfo()
         {
             RequestType = RequestType.ByIndex,
             Index       = get.Body.Index,
             Key         = ((_state.Keys.Count >= (get.Body.Index + 1)) ? _state.Keys[get.Body.Index] : "")
         });
         get.ResponsePort.Post(response);
     }
     catch (Exception e)
     {
         get.ResponsePort.Post(RSUtils.FaultOfException(e));
     }
     yield break;
 }
Beispiel #27
0
 protected override IEnumerator <ITask> SetCallback(vector.SetRequestInfo request, PortSet <vector.CallbackResponseType, Fault> responsePort)
 {
     if (request is vector.SetAllRequestInfo)
     {
         Activate(Arbiter.Choice(
                      _scribblerPort.SetAllLEDs(new brick.SetAllLedsBody()
         {
             LeftLED = _state.GetBool(0), CenterLED = _state.GetBool(1), RightLED = _state.GetBool(2)
         }),
                      delegate(DefaultUpdateResponseType success) { responsePort.Post(vector.CallbackResponseType.Instance); },
                      delegate(Fault failure) { responsePort.Post(failure); }));
     }
     else if (request is vector.SetElementsRequestInfo)
     {
         vector.SetElementsRequestInfo info = (vector.SetElementsRequestInfo)request;
         int setLEDScribblerIndex           = -1; // will be set to -2 for set all
         var responses  = new PortSet <DefaultUpdateResponseType, Fault>();
         int nResponses = 0;
         foreach (int i in info.Indices)
         {
             if (i >= 0)
             {
                 if (i <= 2)
                 {
                     if (setLEDScribblerIndex >= 0)
                     {
                         setLEDScribblerIndex = -2;
                     }
                     else
                     {
                         setLEDScribblerIndex = i;
                     }
                 }
                 else if (i == 3)
                 {
                     nResponses++;
                     Activate(Arbiter.Choice(_scribblerPort.SetLEDFront(_state.GetBool(3)),
                                             delegate(DefaultUpdateResponseType s) { responses.Post(DefaultUpdateResponseType.Instance); },
                                             delegate(Fault f) { responses.Post(f); }));
                 }
                 else if (i == 4)
                 {
                     nResponses++;
                     Activate(Arbiter.Choice(_scribblerPort.SetLEDBack(RSUtils.UnnormalizeDouble(_state.Get(4))),
                                             delegate(DefaultUpdateResponseType s) { responses.Post(DefaultUpdateResponseType.Instance); },
                                             delegate(Fault f) { responses.Post(f); }));
                 }
             }
         }
         if (setLEDScribblerIndex == -2)
         {
             nResponses++;
             Activate(Arbiter.Choice(
                          _scribblerPort.SetAllLEDs(new brick.SetAllLedsBody()
             {
                 LeftLED = _state.GetBool(0), CenterLED = _state.GetBool(1), RightLED = _state.GetBool(2)
             }),
                          delegate(DefaultUpdateResponseType s) { responses.Post(DefaultUpdateResponseType.Instance); },
                          delegate(Fault f) { responses.Post(f); }));
         }
         else if (setLEDScribblerIndex >= 0)
         {
             nResponses++;
             Activate(Arbiter.Choice(
                          _scribblerPort.SetLED(new brick.SetLedBody()
             {
                 LED = setLEDScribblerIndex, State = _state.GetBool(setLEDScribblerIndex)
             }),
                          delegate(DefaultUpdateResponseType s) { responses.Post(DefaultUpdateResponseType.Instance); },
                          delegate(Fault f) { responses.Post(f); }));
         }
         Activate(Arbiter.MultipleItemReceive(responses, nResponses,
                                              delegate(ICollection <DefaultUpdateResponseType> ss, ICollection <Fault> fs)
         {
             if (fs.Count == 0)
             {
                 responsePort.Post(vector.CallbackResponseType.Instance);
             }
             else
             {
                 responsePort.Post(fs.First());
                 ////f.Readon could be null
                 //var reasons = new List<ReasonText>();
                 //foreach (var f in fs)
                 //    if (f.Reason != null)
                 //        reasons.AddRange(f.Reason.AsEnumerable());
                 //responsePort.Post(new Fault() { Detail = new Detail() { Any = fs.ToArray() }, Reason = reasons.ToArray() });
             }
         }));
     }
     yield break;
 }
Beispiel #28
0
 public drive.DriveDifferentialTwoWheelState Get()
 {
     return(RSUtils.ReceiveSync <drive.DriveDifferentialTwoWheelState>(taskQueue, drivePort.Get(), Myro.Utilities.Params.DefaultRecieveTimeout));
 }
Beispiel #29
0
        ///// <summary>
        ///// </summary>
        //private void subscribeAutos()
        //{
        //    // Get the list of partners whose names start with "auto:"
        //    //var request = new partnerList.GetOperation()
        //    //{
        //    //    Body = new GetRequestType(),
        //    //    ResponsePort = new DsspResponsePort<PartnerListType>()
        //    //};
        //    //base.PartnerListManagerPort.Post(request);
        //    //Activate(Arbiter.Choice<PartnerListType, Fault>(
        //    //    request.ResponsePort,
        //    //    delegate(PartnerListType partners)
        //    //    {
        //    //        string autoPrefix = "Auto_";
        //    //        List<PartnerType> autoPartners = new List<PartnerType>(
        //    //            from partner in partners.PartnerList
        //    //            where partner.Name.Name.StartsWith(autoPrefix)
        //    //            select partner);

        //    //        foreach (var p in autoPartners)
        //    //            Console.WriteLine(p.Name);

        //    //        // This method will take care of subscribing and updating state
        //    //        //if (autoPartners.Count > 0)
        //    //        //    subscribeAutos2(autoPartners, autoPrefix.Length);
        //    //    },
        //    //    delegate(Fault failure)
        //    //    {
        //    //        LogError("Fault while getting partner list to subscribe to autos", failure);
        //    //    }));

        //    //List<PartnerType> partnerList = new List<PartnerType>();
        //    //var responsePort = new DsspResponsePort<DefaultUpsertResponseType>();
        //    //Activate(Arbiter.MultipleItemReceive(responsePort, _state.AutoSubsets.Count,
        //    //    delegate(ICollection<DefaultUpsertResponseType> successes, ICollection<Fault> failures)
        //    //    {
        //    //        foreach (Fault failure in failures)
        //    //            LogError("Inserting partner failed", failure);
        //    subscribeAutos2();
        //    //}));
        //}

        /// <summary>
        /// Subscribes to any services specified in the partner list to
        /// automatically update the state.
        /// Once we have a list of auto partners, this method creates AutoDefiniton
        /// objects for each auto partner.  It then waits for each partner to be
        /// found, and calls subscribeAutoSingle to subscribe to each one.
        /// </summary>
        /// <param name="partList"></param>
        /// <param name="removeFromName"></param>
        private void subscribeAutos()
        {
            //foreach (var subset in _state.AutoSubsets)
            //{
            //    PartnerType partner = new PartnerType() { Name = new XmlQualifiedName(subset.PartnerName, Contract.Identifier) };
            //    partnerList.Add(partner);
            //    //base.PartnerListManagerPort.Post(new partnerList.Upsert() { Body = partner, ResponsePort = responsePort });
            //}
            // Create AutoDefinition objects
            autoDefs = new List <AutoDefinition>(_state.AutoSubsets.Count);
            //int lastIndex = 0;
            //List<string> allKeys = new List<string>();
            List <double> allValues = new List <double>();

            foreach (var subset in _state.AutoSubsets)
            {
                // Create AutoDefinition object and add to list
                //string[] keys = part.Name.Name.Substring(removeFromName).Split('_');
                //AutoSubset subset = _state.AutoSubsets.Find((s => part.Name.Name.Equals(s.PartnerName, StringComparison.OrdinalIgnoreCase)));
                //if (subset != default(AutoSubset))
                //{
                //var newKeys = new List<string>();
                //for (int i = 0; i < subset.startIndex; i++)
                //    newKeys.Add("");
                //newKeys.AddRange(subset.keys);
                //}
                AutoDefinition autoDef = new AutoDefinition()
                {
                    partnerName = subset.PartnerName,
                    startIndex  = 0,
                    count       = 0,
                    subsetStart = (subset == default(AutoSubset) ? 0 : subset.StartIndex),
                    subsetCount = (subset == default(AutoSubset) ? 0 : subset.Count),
                    keys        = (subset == default(AutoSubset) ? new List <string>() : subset.Keys)
                };
                autoDefs.Add(autoDef);
            }

            foreach (var autoDef in autoDefs)
            {
                if (autoDef.subsetCount >= 1)
                {
                    // Also build a default vector
                    var values = new List <double>(autoDef.subsetCount);
                    for (int i = 0; i < autoDef.subsetCount; i++)
                    {
                        values.Add(0.0);
                    }
                    modifyStateSubset(autoDef, values);
                }
            }


            // Set values, and take keys provided in subset defs by user
            //_state.SetAll(allValues, DateTime.Now);
            //applyKeysFromSubsets();

            //var upsertRespPort = new DsspResponsePort<DefaultUpsertResponseType>();
            //PartnerListManagerPort.Post(new partnerList.Upsert() { Body = new PartnerType() { Name = new XmlQualifiedName("iRobotGenericDrive", Microsoft.Dss.ServiceModel.Dssp.Contract.Identifier) }, ResponsePort = upsertRespPort });
            //Activate(Arbiter.Choice(upsertRespPort,
            //    delegate(DefaultUpsertResponseType suc)
            //    {
            //        //var queryRespPort = new DsspResponsePort<Microsoft.Dss.Schemas.PartnerListManager.QueryResponseType>();
            //        //PartnerListManagerPort.Post(new partnerList.Query() { Body = new partnerListS.QueryRequestType() { Name = new XmlQualifiedName("iRobotGenericDrive", Contract.Identifier) }, ResponsePort = queryRespPort });
            //        //Activate(Arbiter.Choice(queryRespPort,
            //        //    delegate(partnerListS.QueryResponseType qsuc)
            //        //    {
            //        //        Console.WriteLine(qsuc.Partner.Name + " : " + qsuc.Partner.Contract + " : " + qsuc.Partner.Service);
            //        //    },
            //        //    delegate(Fault failure)
            //        //    {
            //        //        Console.WriteLine("Fault querying");
            //        //    }));
            //        var partsRespPort = base.IssuePartnerSubscribe(new XmlQualifiedName("iRobotGenericDrive", Microsoft.Dss.ServiceModel.Dssp.Contract.Identifier));
            //        Activate(Arbiter.Choice(partsRespPort,
            //            delegate(PartnerListType partListResponse)
            //            {
            //                foreach (var partner in partListResponse.PartnerList)
            //                {
            //                    Console.WriteLine(partner.Name + " : " + partner.Contract + " : " + partner.Service);
            //                }
            //            },
            //            delegate(Fault failure)
            //            {
            //                Console.WriteLine("Fault querying");
            //            }));
            //    },
            //    delegate(Fault fail)
            //    {
            //        Console.WriteLine("Fault upserting");
            //    }));


            // Create the new vector state reflecting the keys
            //List<double> allValues = new List<double>(from k in allKeys select 0.0);
            //VectorState newState = new VectorState(allValues, allKeys, DateTime.Now);
            //var responsePort = new DsspResponsePort<DefaultReplaceResponseType>();
            //OperationsPort.Post(new Replace(newState, responsePort));
            //Activate(Arbiter.Choice(responsePort,
            //    delegate(DefaultReplaceResponseType r) { },
            //    delegate(Fault f) { LogError("Fault while replacing initial vector state", f); }));

            // Try to subscribe to compatible contracts with the AutoDefinition objects
            foreach (var autoDef in autoDefs)
            {
                AutoDefinition myAutoDef = autoDef;
                //Console.WriteLine("Waiting 10 seconds before subscribing to partner list...");
                //Thread.Sleep(10000);
                var partRespPort = base.IssuePartnerSubscribe(new XmlQualifiedName(myAutoDef.partnerName, Contract.Identifier));
                //Console.WriteLine("Looking for " + myAutoDef.infoAsPartner.Name);
                Activate(Arbiter.Choice(partRespPort,
                                        delegate(PartnerListType partListResponse)
                {
                    //Console.WriteLine("Found " + partListResponse.PartnerList.Count + " for " + myAutoDef.infoAsPartner.Name);
                    if (partListResponse.PartnerList.Count > 1)
                    {
                        LogWarning("More than one partner found for " + myAutoDef.partnerName);
                    }
                    else if (partListResponse.PartnerList.Count < 1)
                    {
                        LogWarning("No partners found for " + myAutoDef.partnerName);
                    }
                    foreach (var partner in partListResponse.PartnerList)
                    {
                        if (myAutoDef.infoAsConnected == null)
                        {
                            //Console.WriteLine("Searching for a contract for " + partner.Service);
                            Activate(Arbiter.Choice(RSUtils.FindCompatibleContract(TaskQueue, new Uri(partner.Service), new List <string>()
                            {
                                analog.Contract.Identifier, analogArray.Contract.Identifier, contact.Contract.Identifier
                            }),
                                                    delegate(ServiceInfoType serviceInfoResponse)
                            {
                                try
                                {
                                    subscribeAutoSingle(myAutoDef, serviceInfoResponse);
                                    myAutoDef.infoAsConnected = serviceInfoResponse;
                                    LogInfo("Vector service " + base.ServiceInfo.Service + " subscribed auto update to " + serviceInfoResponse.Service + " with contract " + serviceInfoResponse.Contract);
                                }
                                catch (Exception e)
                                {
                                    LogError("Exception while subscribing to auto partner", e);
                                }
                            },
                                                    delegate(Fault failure)
                            {
                                Exception e = RSUtils.ExceptionOfFault(failure);
                                if (e is NoContractFoundException)
                                {
                                    LogError("Could not subscribe to auto partner " + myAutoDef.partnerName + ".  Could not find a supported contract.");
                                }
                                else if (e is Exception)
                                {
                                    LogError("Fault while searching for compatible contract", e);
                                }
                            }));
                        }
                    }
                },
                                        delegate(Fault failure)
                {
                    Console.WriteLine("Fault for " + myAutoDef.partnerName);
                    LogError("Fault from subscription to partner list service", failure);
                }));
                //Thread.Sleep(2000);
            }
        }
Beispiel #30
0
        //public override bool Equals(Object obj)
        //{
        //    if (obj is String)
        //    {
        //        string truncUri = ServiceInfo.Service.Substring(ServiceInfo.Service.IndexOf('/', ServiceInfo.Service.IndexOf("//") + 2));
        //        return String.Equals(truncUri, obj);
        //    }
        //    else
        //        return String.Equals(this.ServiceInfo.Service, ((DriveAdapter)obj).ServiceInfo.Service);
        //}

        public void Stop()
        {
            RSUtils.ReceiveSync <DefaultUpdateResponseType>(taskQueue, drivePort.AllStop(), Myro.Utilities.Params.DefaultRecieveTimeout);
        }