示例#1
0
        /// <summary>
        /// This method searches for a primary or alternate contract of the
        /// service that is present in the contracts list.  Requires a
        /// taskQueue to activate tasks on.  Throws NoContractFoundException
        /// in a Fault if one cannot be found.
        /// </summary>
        /// <param name="taskQueue"></param>
        /// <param name="service"></param>
        /// <param name="contracts"></param>
        /// <returns></returns>
        public static PortSet <ServiceInfoType, Fault> FindCompatibleContract(DispatcherQueue taskQueue, Uri service, List <string> contracts)
        {
            PortSet <ServiceInfoType, Fault> returnPort = new PortSet <ServiceInfoType, Fault>();

            PortSet <LookupResponse, Fault> responsePort = new PortSet <LookupResponse, Fault>();

            //Console.WriteLine("RSUtils: Querying " + service);
            DssEnvironment.ServiceForwarderUnknownType(service).PostUnknownType(
                new DsspDefaultLookup()
            {
                Body = new LookupRequestType(), ResponsePort = responsePort
            });
            Arbiter.Activate(taskQueue, Arbiter.Choice <LookupResponse, Fault>(
                                 responsePort,
                                 delegate(LookupResponse resp)
            {
                try
                {
                    //Console.WriteLine("RSUtils: Got response");
                    returnPort.Post(FindCompatibleContract(resp, contracts));
                }
                catch (NoContractFoundException e)
                {
                    returnPort.Post(FaultOfException(e));
                }
            },
                                 delegate(Fault failure)
            {
                returnPort.Post(failure);
            }));

            return(returnPort);
        }
        internal PortSet <string, Exception> DeserializeEnvelopeBody(loganalyzer.Envelope envelope)
        {
            var xmlResultPort = new PortSet <XmlWriter, Exception>();

            var o = loganalyzer.DssLogAnalyzerHelper.DeserializeEnvelope(envelope).Body;

            var stringbuilderOutput = new StringBuilder();
            var xmlWriter           = XmlWriter.Create(stringbuilderOutput, new XmlWriterSettings {
                Indent = true
            });

            var ser = new SerializeToXmlWriter(o, xmlWriter, xmlResultPort);

            SerializerPort.Post(ser);

            var resultPort = new PortSet <string, Exception>();

            Activate(
                Arbiter.Choice(
                    xmlResultPort,
                    success => resultPort.Post(stringbuilderOutput.ToString()),
                    failure => resultPort.Post(failure)));

            return(resultPort);
        }
示例#3
0
        /// <summary>
        /// Actuator callback
        /// </summary>
        protected override IEnumerator <ITask> SetCallback(Myro.Services.Generic.Vector.SetRequestInfo request, PortSet <vector.CallbackResponseType, Fault> responsePort)
        {
            var req = request as vector.SetElementsRequestInfo;

            if (req != null)
            {
                bool play = false;
                bool loud = false;
                foreach (var i in req.Indices)
                {
                    if (i == 0 || i == 1 || i == 2)
                    {
                        play = true;
                    }
                    else if (i == 3)
                    {
                        loud = true;
                    }
                }

                Fault error = null;
                if (loud)
                {
                    yield return(Arbiter.Choice(setLoud(),
                                                delegate(vector.CallbackResponseType s) { },
                                                delegate(Fault f) { error = f; }));
                }

                if (error == null && play)
                {
                    yield return(Arbiter.Choice(playTone(),
                                                delegate(vector.CallbackResponseType s1) { },
                                                delegate(Fault f) { error = f; }));
                }

                if (error == null)
                {
                    responsePort.Post(vector.CallbackResponseType.Instance);
                }
                else
                {
                    responsePort.Post(error);
                }
            }
            else
            {
                // Otherwise it was a SetAllRequestInfo
                Activate(Arbiter.Choice(setLoud(),
                                        delegate(vector.CallbackResponseType s)
                {
                    Activate(Arbiter.Choice(playTone(),
                                            delegate(vector.CallbackResponseType s1) { responsePort.Post(vector.CallbackResponseType.Instance); },
                                            delegate(Fault f) { responsePort.Post(f); }));
                },
                                        delegate(Fault f) { responsePort.Post(f); }));
            }
            yield break;
        }
示例#4
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;
 }
 /// <summary>
 /// Prompt for New log folder
 /// </summary>
 /// <param name="resultPort">The result port to post result</param>
 internal void PromptForNewLogFolder(PortSet <string, Fault> resultPort)
 {
     if (MessageBox.Show(
             Properties.Resources.XmlToBinaryConversionWarning,
             Properties.Resources.XmlToBinaryConversionWarningCaption,
             MessageBoxButton.YesNo,
             MessageBoxImage.Warning) == MessageBoxResult.Yes)
     {
         resultPort.Post(this.PresentLoadFileDialog(Properties.Resources.SelectFolderForConvertedBinaryFiles));
     }
     else
     {
         resultPort.Post(Fault.FromException(new Exception(Properties.Resources.UserCanceledLoad)));
     }
 }
示例#6
0
        /// <summary>
        /// Posts the appropriate response when handling the dialog being closed
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            if (DialogResult == DialogResult.OK)
            {
                // Return the current contents of the textbox
                _result.Post(txtValue.Text);
            }
            else
            {
                // If the user cancels the prompt, then an exception is returned
                _result.Post(new Exception("Cancelled"));
            }
        }
        /// <summary>
        /// Redirects the HTTP request from an alternate contract to a partner
        /// </summary>
        /// <param name="contract">The contract.</param>
        /// <param name="partner">The partner.</param>
        /// <param name="context">The context.</param>
        /// <param name="responsePort">The response port.</param>
        private void RedirectHttpRequest(
            string contract,
            IPort partner,
            HttpListenerContext context,
            PortSet <HttpResponseType, Fault> responsePort)
        {
            var alternate     = AlternateContractServiceInfo.Find(s => s.Contract == contract) ?? ServiceInfo;
            var basePath      = alternate.HttpServiceAlias.AbsolutePath;
            var requestedPath = context.Request.Url.PathAndQuery;
            var pathSuffix    = requestedPath.Substring(basePath.Length);

            var lookup = new DsspDefaultLookup();

            partner.PostUnknownType(lookup);
            this.Activate(
                lookup.ResponsePort.Choice(
                    svcinfo =>
            {
                var redirectPath = svcinfo.HttpServiceAlias.AbsolutePath + pathSuffix;
                context.Response.Redirect(redirectPath);
                context.Response.Close();
                responsePort.Post(new HttpResponseType());
            },
                    responsePort.Post));
        }
示例#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);
                     _state.Set(myI, 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
                 {
                     responsePort.Post(fs.First());
                     //// f.Reason was sometimes null
                     //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;
 }
示例#9
0
 private void ActionNotSupported(PortSet <DefaultUpdateResponseType, W3C.Soap.Fault> responsePort)
 {
     responsePort.Post(Fault.FromCodeSubcodeReason(
                           W3C.Soap.FaultCodes.Receiver,
                           DsspFaultCodes.ActionNotSupported,
                           Resources.NotModifiable
                           )
                       );
 }
示例#10
0
        /// <summary>
        /// Add an iRobot command to our script.
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="responsePort"></param>
        private void AddScriptCommand(Roomba.RoombaCommand cmd, PortSet <DefaultInsertResponseType, Fault> responsePort)
        {
            _state.CurrentScript.Commands.Add(cmd.ToString());
            _state.CurrentScript.PacketData    = Roomba.ByteArray.Combine(_state.CurrentScript.PacketData, cmd.GetPacket());
            _state.CurrentScript.PacketData[0] = (byte)(_state.CurrentScript.PacketData.Length - 1);

            _state.CurrentScript.ExpectedScriptResponseBytes += cmd.ExpectedResponseBytes();

            responsePort.Post(DefaultInsertResponseType.Instance);
        }
        /// <summary>
        /// Locates the camera entity.
        /// </summary>
        /// <param name="responsePort">The response port.</param>
        /// <returns>Standard ccr iterator</returns>
        private IEnumerator <ITask> LocateCameraEntity(PortSet <VisualEntity, Fault> responsePort)
        {
            // Subscribe for it in the simulation engine
            var simenginePort     = simengine.SimulationEngine.GlobalInstancePort;
            var notificationPort  = new simengine.SimulationEnginePort();
            var subscribeResponse = simenginePort.Subscribe(ServiceInfo.PartnerList, notificationPort);
            var subscribeFailure  = (Fault)subscribeResponse;

            if (subscribeFailure != null)
            {
                responsePort.Post(subscribeFailure);
                yield break;
            }

            var insertPort = notificationPort.P6;

            yield return(insertPort.Receive(inserted => responsePort.Post(inserted.Body)));

            yield break;
        }
示例#12
0
        private void CaptureSurveyorFrame(PortSet <Bitmap, Exception> capturePort)
        {
            if (!this._capturing)
            {
                return;
            }
            ;

            try
            {
                Bitmap frame = null;
                if (!this._scanMode)
                {
                    using (Image image = _srv1.ForceCaptureImage())
                    {
                        // To avoid GDI+ generic exception we're not using the capture image directly.
                        frame = new Bitmap(image);
                    }
                }
                else
                {
                    frame = this.CreateScanFrame();
                }
                // Check if the camera service is still active as it might have
                // been deactivated by another service running in another thread.
                if (this._capturing)
                {
                    capturePort.Post(frame);
                }
            }
            catch (TimeoutException ex)
            {
                if (this._capturing)
                {
                    capturePort.Post(ex);
                }
            }
        }
示例#13
0
        /// <summary>
        /// Service start method
        /// </summary>
        protected override void Start()
        {
            if (_state == null)
            {
                _state = new IpCameraState();
            }

            _utilitiesPort = DsspHttpUtilitiesService.Create(Environment);

            Uri httpAlias = ServiceInfo.HttpServiceAlias;

            if (httpAlias != null)
            {
                _prefix          = httpAlias.AbsolutePath;
                _alternatePrefix = AlternateContractServiceInfo[0].HttpServiceAlias.AbsolutePath;
            }
            else
            {
                LogError(LogGroups.Activation, "Service requires HTTP transport");
                DefaultDropHandler(new DsspDefaultDrop());
                return;
            }

            base.Start();

            MainPortInterleave.CombineWith(
                new Interleave(
                    new ExclusiveReceiverGroup(
                        Arbiter.Receive <Bitmap>(true, _imagePort, ImageHandler)
                        ),
                    new ConcurrentReceiverGroup(
                        Arbiter.Receive <DateTime>(true, _imagePort, GetImageHandler)
                        )
                    )
                );

            _imagePort.Post(DateTime.UtcNow);
        }
示例#14
0
        public virtual IEnumerator <ITask> ConfirmHandler(Confirm confirm)
        {
            PortSet <bool, Exception> result = new PortSet <bool, Exception>();
            ConfirmForm form = null;

            RunForm runForm = new RunForm(
                delegate()
            {
                form           = new ConfirmForm(result);
                form.Message   = confirm.Body.Message;
                form.Countdown = _defaultTimeout;

                return(form);
            }
                );

            WinFormsServicePort.Post(runForm);

            yield return(Arbiter.Choice(
                             runForm.pResult,
                             delegate(SuccessResult success) { },
                             delegate(Exception e)
            {
                result.Post(e);
            }
                             ));

            yield return(Arbiter.Choice(
                             result,
                             delegate(bool confirmed)
            {
                ConfirmResponse response = new ConfirmResponse();
                response.Confirmed = confirmed;

                confirm.ResponsePort.Post(response);

                if (form.Timeout)
                {
                    LogWarning("Confirm dialog cancelled due to timeout.");
                }
            },
                             delegate(Exception e)
            {
                Fault fault = Fault.FromException(e);
                LogError(null, "Error in Confirm Handler", fault);
                confirm.ResponsePort.Post(fault);
            }
                             ));
        }
示例#15
0
 private IEnumerator <ITask> PlaySound(bool synchronous, PortSet <DefaultSubmitResponseType, Fault> responsePort, SystemSound systemSound)
 {
     if (synchronous)
     {
         systemSound.Play();
     }
     else
     {
         Spawn(delegate()
         {
             systemSound.Play();
         }
               );
     }
     responsePort.Post(DefaultSubmitResponseType.Instance);
     yield break;
 }
示例#16
0
        public IEnumerator <ITask> RotateDegreesHandler(RotateDegrees rotateDegrees)
        {
            ValidateDriveConfiguration(true);
            if (_state.DistanceBetweenWheels <= 0)
            {
                rotateDegrees.ResponsePort.Post(new Fault());
                throw new InvalidOperationException("The wheel encoders are not properly configured");
            }
            else
            {
                _state.TimeStamp = DateTime.Now;

                // send immediate response
                rotateDegrees.ResponsePort.Post(DefaultUpdateResponseType.Instance);


                // send immediate response
                rotateDegrees.ResponsePort.Post(DefaultUpdateResponseType.Instance);

                // post request to internal port.
                _internalDriveOperationsPort.Post(rotateDegrees);
            }
            yield break;
        }
        /// <summary>
        /// Process Brick State
        /// </summary>
        /// <param name="brickState"></param>
        private IEnumerator <ITask> ProcessBrickState(brick.NxtBrickState brickState)
        {
            foreach (string key in brickState.Runtime.Devices.Keys)
            {
                brick.AttachRequest device = brickState.Runtime.Devices[key];
                if (device.Registration.DeviceType != LegoDeviceType.AnalogSensor &&
                    device.Registration.DeviceType != LegoDeviceType.DigitalSensor)
                {
                    continue;
                }

                PortSet <DsspDefaultLookup, DsspDefaultGet> lookupPort = ServiceForwarder <PortSet <DsspDefaultLookup, DsspDefaultGet> >(device.Registration.ServiceUri);
                DsspDefaultLookup lu = new DsspDefaultLookup();
                lookupPort.Post(lu);
                yield return(Arbiter.Choice(lu.ResponsePort,
                                            delegate(LookupResponse luResponse)
                {
                    foreach (PartnerType pt in luResponse.PartnerList)
                    {
                        // See if this service supports the analog sensor contract
                        if (pt.Contract == analog.Contract.Identifier)
                        {
                            // Check if we have already processed this one.
                            if (_sensorList.ContainsKey(pt.Service))
                            {
                                break;
                            }

                            string name = device.Registration.Name;
                            string model = device.Registration.DeviceModel;
                            int hardwareIdentifier = NxtCommon.HardwareIdentifier(device.Registration.Connection.Port);

                            LogVerbose(LogGroups.Console, string.Format("Configuring {0}:{1} on {2} with analog service at {3}", model, name, hardwareIdentifier, pt.Service));
                            analog.AnalogSensorOperations sensorPort = ServiceForwarder <analog.AnalogSensorOperations>(pt.Service);
                            Activate(Arbiter.Choice(sensorPort.Subscribe(_analogSensorNotificationsPort),
                                                    delegate(SubscribeResponseType response)
                            {
                                // Keep track of the subscription manager response
                                // so that we can unsubscribe later.
                                _sensorList.Add(pt.Service, response);
                            },
                                                    delegate(Fault fault)
                            {
                                LogError(LogGroups.Console, string.Format("Failure subscribing to {0} on port {1}.", model, hardwareIdentifier));
                            }));

                            foreach (SensorConfiguration cfg in _state.SensorConfiguration)
                            {
                                if (cfg.DeviceModel != model)
                                {
                                    continue;
                                }

                                SensorRange range = new SensorRange(hardwareIdentifier, model, name, cfg.RangeName);
                                PortConfiguration portConfig = new PortConfiguration(hardwareIdentifier, range.ContactSensorName, cfg.SuccessRangeMin, cfg.SuccessRangeMax);
                                portConfig.AnalogSensorServiceUri = pt.Service;

                                if (portConfig != null)
                                {
                                    _state.RuntimeConfiguration.Add(range, portConfig);
                                }
                            }
                            break;
                        }
                    }
                },
                                            delegate(Fault f) { }));
            }
        }
        /// <summary>
        /// Posts the appropriate response when handling the dialog being closed
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            _result.Post(DialogResult == DialogResult.OK);
        }
        /// <summary>
        /// Handles http requests
        /// </summary>
        /// <param name="context">Http context</param>
        /// <param name="responsePort">Response port</param>
        /// <returns>CCR ITask enumerator</returns>
        private IEnumerator<ITask> HttpHandler(HttpListenerContext context, PortSet<HttpResponseType, Fault> responsePort)
        {
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            string type = "image/png";
            ImageFormat format = ImageFormat.Png;

            if (request.Url.Query.ToLowerInvariant().EndsWith("depth"))
            {
                Bitmap image = null;

                if (!this.TryCreateDepthImage(out image))
                {
                    responsePort.Post(Fault.FromException(new InvalidOperationException()));
                    yield break;
                }

                using (image)
                {
                    using (var memStream = new MemoryStream())
                    {
                        image.Save(memStream, ImageFormat.Png);
                        response.AddHeader("Cache-Control", "No-cache");
                        response.ContentType = type;
                        memStream.WriteTo(response.OutputStream);
                    }
                }

                Microsoft.Dss.Core.DsspHttpUtilities.Utilities.HttpClose(context);
            }
            else if (request.Url.Query.ToLowerInvariant().EndsWith("floor"))
            {
                // show the pre-calculated floor/ceiling map
                if (this.floorCeilingMaxDepths == null)
                {
                    responsePort.Post(Fault.FromException(new InvalidOperationException()));
                    yield break;
                }

                // insert the depth image bits
                var imageBits = new byte[DefaultDepthCamImageWidth * DefaultDepthcamImageHeight * 3];
                for (int i = 0; i < this.depthDownSampleBuffer.Length; i++)
                {
                    var depth8bpp = (this.floorCeilingMaxDepths[i] * 255) / (int)MaxValidDepth;
                    imageBits[(i * 3) + 0] = (byte)depth8bpp;
                    imageBits[(i * 3) + 1] = (byte)depth8bpp;
                    imageBits[(i * 3) + 2] = (byte)depth8bpp;
                }

                using (var image = new Bitmap(DefaultDepthCamImageWidth, DefaultDepthcamImageHeight, PixelFormat.Format24bppRgb))
                {
                    var raw = image.LockBits(
                                new Rectangle(0, 0, DefaultDepthCamImageWidth, DefaultDepthcamImageHeight),
                                ImageLockMode.WriteOnly,
                                PixelFormat.Format24bppRgb);
                    System.Runtime.InteropServices.Marshal.Copy(imageBits, 0, raw.Scan0, imageBits.Length);
                    image.UnlockBits(raw);
                    using (var memStream = new MemoryStream())
                    {
                        image.Save(memStream, ImageFormat.Png);
                        response.AddHeader("Cache-Control", "No-cache");
                        response.ContentType = type;
                        memStream.WriteTo(response.OutputStream);
                    }
                }

                Microsoft.Dss.Core.DsspHttpUtilities.Utilities.HttpClose(context);
            }
            else
            {
                responsePort.Post(Fault.FromException(new NotSupportedException()));
                yield break;
            }

            response.Close();
        }
示例#20
0
        /// <summary>
        /// Tries to subscribe to an auto partner single contract, or throws an exception
        /// if we don't support the contract.  Also starts a 1-second poll that continues
        /// until publishers send non-zero-length arrays.
        /// </summary>
        /// <param name="def"></param>
        /// <param name="serviceInfo"></param>
        private void subscribeAutoSingle(AutoDefinition def, ServiceInfoType serviceInfo)
        {
            // Check for each contract we know about and subscribe.

            ////////////////// Analog Sensor
            if (serviceInfo.Contract.Equals(analog.Contract.Identifier))
            {
                var partnerPort = ServiceForwarder <analog.AnalogSensorOperations>(new Uri(serviceInfo.Service));
                var notifyPort  = new Port <analog.Replace>();
                Activate(Arbiter.Choice(partnerPort.Subscribe(notifyPort, typeof(analog.Replace)),
                                        delegate(SubscribeResponseType success)
                {
                    MainPortInterleave.CombineWith(new Interleave(
                                                       new ExclusiveReceiverGroup(
                                                           Arbiter.Receive(true, notifyPort,
                                                                           delegate(analog.Replace replace)
                                                                           { autoSubscribeNotificationHelper(def, new List <double>(1)
                        {
                            replace.Body.RawMeasurement
                        }, replace.Body.TimeStamp, false); }
                                                                           )),
                                                       new ConcurrentReceiverGroup()));
                },
                                        delegate(Fault failure)
                {
                    LogError("Fault while subscribing to auto partner", failure);
                }));
            }

            ////////////////// Analog Sensor Array
            else if (serviceInfo.Contract.Equals(analogArray.Contract.Identifier))
            {
                var  partnerPort     = ServiceForwarder <analogArray.AnalogSensorOperations>(new Uri(serviceInfo.Service));
                var  notifyPort      = new Port <analogArray.Replace>();
                var  pollPort        = base.TimeoutPort(1000);
                bool gotNonzeroState = false;
                Activate(Arbiter.Receive(true, pollPort,
                                         delegate(DateTime time)
                {
                    if (gotNonzeroState == false)
                    {
                        Activate(Arbiter.Choice(partnerPort.Get(),
                                                delegate(analogArray.AnalogSensorArrayState state) { notifyPort.Post(new analogArray.Replace(state)); },
                                                delegate(Fault failure) { LogError("Vector got fault while trying to get polled state", failure); }));
                        TaskQueue.EnqueueTimer(TimeSpan.FromMilliseconds(1000.0), pollPort);
                    }
                }));
                Activate(Arbiter.Choice(partnerPort.Subscribe(notifyPort, typeof(analogArray.Replace)),
                                        delegate(SubscribeResponseType success)
                {
                    MainPortInterleave.CombineWith(new Interleave(
                                                       new ExclusiveReceiverGroup(
                                                           Arbiter.Receive(true, notifyPort,
                                                                           delegate(analogArray.Replace replace)
                    {
                        if (replace.Body.Sensors.Count > 0)
                        {
                            gotNonzeroState = true;
                        }
                        autoSubscribeNotificationHelper(def,
                                                        new List <double>(from s in replace.Body.Sensors select s.RawMeasurement),
                                                        (replace.Body.Sensors.Count > 0 ? replace.Body.Sensors[0].TimeStamp : DateTime.Now), false);
                    })),
                                                       new ConcurrentReceiverGroup()));
                },
                                        delegate(Fault failure)
                {
                    LogError("Fault while subscribing to auto partner", failure);
                }));
            }

            ////////////////// Contact Sensor
            else if (serviceInfo.Contract.Equals(contact.Contract.Identifier))
            {
                var partnerPort = ServiceForwarder <contact.ContactSensorArrayOperations>(new Uri(serviceInfo.Service));
                var notifyPort  = new PortSet <contact.Replace, contact.Update>();
                // Post an initial Replace notification to update the HW ID map (no, this is now done automatically)
                //notifyPort.Post(new contact.Replace(RSUtils.ReceiveSync(TaskQueue, partnerPort.Get(), Params.defaultRecieveTimeout)));
                var  pollPort        = base.TimeoutPort(1000);
                bool gotNonzeroState = false;
                Activate(Arbiter.Receive(true, pollPort,
                                         delegate(DateTime time)
                {
                    if (gotNonzeroState == false)
                    {
                        Activate(Arbiter.Choice(partnerPort.Get(),
                                                delegate(contact.ContactSensorArrayState state) { notifyPort.Post(new contact.Replace(state)); },
                                                delegate(Fault failure) { LogError("Vector got fault while trying to get polled state", failure); }));
                        TaskQueue.EnqueueTimer(TimeSpan.FromMilliseconds(1000.0), pollPort);
                    }
                }));
                Activate(Arbiter.Choice(partnerPort.Subscribe(notifyPort, typeof(contact.Replace), typeof(contact.Update)),
                                        delegate(SubscribeResponseType success)
                {
                    var contactHWIDMap = new Dictionary <int, int>();
                    MainPortInterleave.CombineWith(new Interleave(
                                                       new ExclusiveReceiverGroup(
                                                           Arbiter.Receive <contact.Replace>(true, notifyPort,
                                                                                             delegate(contact.Replace replace)
                    {
                        if (replace.Body.Sensors.Count > 0)
                        {
                            gotNonzeroState = true;
                        }
                        if (def.hwKeys.Count < replace.Body.Sensors.Count)
                        {
                            def.hwKeys.Capacity = replace.Body.Sensors.Count;
                            while (def.hwKeys.Count < replace.Body.Sensors.Count)
                            {
                                def.hwKeys.Add("");
                            }
                        }
                        // Refresh the HW ID map
                        contactHWIDMap.Clear();
                        for (int i = 0; i < replace.Body.Sensors.Count; i++)
                        {
                            contactHWIDMap.Add(replace.Body.Sensors[i].HardwareIdentifier, i);
                            //if (def.hwKeys[i] == null || def.hwKeys[i].Length <= 0)
                            def.hwKeys[i] = replace.Body.Sensors[i].Name;
                        }
                        autoSubscribeNotificationHelper(def,
                                                        new List <double>(from s in replace.Body.Sensors select(s.Pressed ? 1.0 : 0.0)),
                                                        (replace.Body.Sensors.Count > 0 ? replace.Body.Sensors[0].TimeStamp : DateTime.Now), true);
                    }),
                                                           Arbiter.Receive <contact.Update>(true, notifyPort,
                                                                                            delegate(contact.Update update)
                    {
                        gotNonzeroState = true;
                        try
                        {
                            int i = contactHWIDMap[update.Body.HardwareIdentifier];
                            autoSubscribeNotificationUpdateHelper(def, i, (update.Body.Pressed ? 1.0 : 0.0), update.Body.TimeStamp);
                        }
                        catch (KeyNotFoundException)
                        {
                            LogError("Vector got update for contact sensor hardware identifier " + update.Body.HardwareIdentifier + " and doesn't know about this hardware ID.  Trying to fetch entire state.");
                            Activate(Arbiter.Choice(partnerPort.Get(),
                                                    delegate(contact.ContactSensorArrayState state) { notifyPort.Post(new contact.Replace(state)); },
                                                    delegate(Fault failure) { LogError("Vector got fault while trying to get contact state", failure); }));
                        }
                    })),
                                                       new ConcurrentReceiverGroup()));
                },
                                        delegate(Fault failure)
                {
                    LogError("Fault while subscribing to auto partner", failure);
                }));
            }
            else
            {
                throw new UnrecognizedContractException();
            }
        }
示例#21
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;
 }
 /// <summary>
 /// Send a success or failure SetMotorPower response. 
 /// </summary>
 /// <param name="responsePort"></param>
 /// <param name="success"></param>
 private void RespondToMotorPowerRequest(PortSet<DefaultUpdateResponseType, Fault> responsePort, bool success)
 {
     if (success)
     {
         LogVerbose(LogGroups.Console, "SetMotorPower Completed Successfully");
         responsePort.Post(DefaultUpdateResponseType.Instance);
     }
     else
     {
         string msg = "The motor operation was cancelled by a newer motor request.";
         responsePort.Post(Fault.FromException(new OperationCanceledException(msg)));
         LogVerbose(LogGroups.Console, msg);
     }
 }
示例#23
0
        public virtual IEnumerator <ITask> PromptHandler(Prompt prompt)
        {
            PortSet <string, Exception> result = new PortSet <string, Exception>();
            PromptForm form = null;

            RunForm runForm = new RunForm(
                delegate()
            {
                form              = new PromptForm(result);
                form.Message      = prompt.Body.Message;
                form.DefaultValue = prompt.Body.DefaultValue;
                form.Countdown    = _defaultTimeout;

                return(form);
            }
                );

            WinFormsServicePort.Post(runForm);

            yield return(Arbiter.Choice(
                             runForm.pResult,
                             delegate(SuccessResult success) { },
                             delegate(Exception e)
            {
                result.Post(e);
            }
                             ));

            yield return(Arbiter.Choice(
                             result,
                             delegate(string value)
            {
                PromptResponse response = new PromptResponse();
                response.TextData = value;
                response.Confirmed = true;

                prompt.ResponsePort.Post(response);
            },
                             delegate(Exception e)
            {
                if (e.Message == "Cancelled")
                {
                    // If the Cancel button was pressed, return the default text
                    PromptResponse response = new PromptResponse();
                    response.TextData = prompt.Body.DefaultValue;
                    response.Confirmed = false;

                    prompt.ResponsePort.Post(response);

                    if (form.Timeout)
                    {
                        LogWarning("Prompt dialog cancelled due to timeout.");
                    }
                }
                else
                {
                    Fault fault = Fault.FromException(e);
                    LogError(null, "Error in Prompt Handler", fault);
                    prompt.ResponsePort.Post(fault);
                }
            }
                             ));
        }
示例#24
0
        IEnumerator <ITask> HttpHandler(HttpListenerContext context, PortSet <HttpResponseType, Fault> responsePort)
        {
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            bool alternate = false;

            string path = request.Url.AbsolutePath.ToLower(ci.InvariantCulture);

            if (path.StartsWith(_alternatePrefix))
            {
                alternate = true;
                path      = path.Substring(_alternatePrefix.Length);
            }
            else if (path.StartsWith(_prefix))
            {
                path = path.Substring(_prefix.Length);
            }

            string      type;
            ImageFormat format;

            switch (path)
            {
            case "/jpeg":
            case "/jpg":
                type   = MediaTypeNames.Image.Jpeg;
                format = ImageFormat.Jpeg;
                break;

            case "/bmp":
                type   = "image/bmp";
                format = ImageFormat.Bmp;
                break;

            case "/png":
                type   = "image/png";
                format = ImageFormat.Png;
                break;

#if !URT_MINCLR
            case "/tif":
            case "/tiff":
                type   = "image/tiff";
                format = ImageFormat.Tiff;
                break;
#endif
            case "/gif":
                type   = MediaTypeNames.Image.Gif;
                format = ImageFormat.Gif;
                break;

            default:
                if (alternate)
                {
                    responsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state.ToGenericState(), _transform));
                }
                else if (path == "/log")
                {
                    var log = new PipeServerOutput();
                    lock (_pipeServerOutput)
                    {
                        log.Output = new List <string>(_pipeServerOutput);
                    }
                    responsePort.Post(new HttpResponseType(log));
                }
                else
                {
                    responsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state, _transform));
                }
                yield break;
            }

            if (_state.Image == null)
            {
                if (_state.FramesOnDemand)
                {
                    if (_state.Selected != null &&
                        _state.Selected.Started)
                    {
                        var internalRequest = new InternalFrameRequest
                        {
                            Context = context,
                            Type    = type,
                            Format  = format
                        };

                        _frameRequestPort.Post(internalRequest);

//                        _state.Selected.FrameGrabber.ResumeCapture();

                        yield return(Arbiter.Receive(false, internalRequest.ResponsePort, EmptyHandler));

//                        _state.Selected.FrameGrabber.PauseCapture();
                    }
                }
                else if (alternate)
                {
                    responsePort.Post(new HttpResponseType(HttpStatusCode.NotFound, _state.ToGenericState(), _transform));
                }
                else
                {
                    responsePort.Post(new HttpResponseType(HttpStatusCode.NotFound, _state, _transform));
                }
                yield break;
            }

            using (MemoryStream stream = new MemoryStream())
            {
                _state.Image.Save(stream, format);
                stream.Position = 0;

                yield return(Arbiter.Choice(
                                 WriteImageToHttpResponse(context, type, stream),
                                 success => stream.Close(),
                                 exception => { stream.Close(); LogWarning("Writing image to stream:" + exception.Message); }
                                 ));
            }
        }
        IEnumerator <ITask> ProcessPipe(NamedPipeClientStream client)
        {
            Port <IAsyncResult> continuation = new Port <IAsyncResult>();

            for (; ;)
            {
                IAsyncResult ar       = null;
                var          response = new WebcamResponse();

                client.BeginRead(response.header,
                                 0,
                                 WebcamResponse.HeaderSize,
                                 continuation.Post,
                                 null
                                 );

                yield return(Arbiter.Receive(false, continuation, result => ar = result));

                var length = client.EndRead(ar);
                if (length != 8)
                {
                    if (0 < Interlocked.CompareExchange(ref _shutdown, 1, 1))
                    {
                        LogInfo("Pipe has been closed");
                        client = null;
                    }
                    else
                    {
                        LogError("Bad header length read from pipe");
                    }
                    yield break;
                }

                response.packet = new byte[response.packetSize];

                client.BeginRead(response.packet,
                                 0,
                                 response.packetSize,
                                 continuation.Post,
                                 null
                                 );

                yield return(Arbiter.Receive(false, continuation, result => ar = result));

                length = client.EndRead(ar);
                if (length != response.packetSize)
                {
                    if (0 < Interlocked.CompareExchange(ref _shutdown, 1, 1))
                    {
                        LogInfo("Pipe has been closed");
                        client = null;
                    }
                    else
                    {
                        LogError("Bad packet length read from pipe");
                    }
                    yield break;
                }

                if (response.IsKnownType)
                {
                    var item = response.KnownType;

                    if (item is EnumResponse)
                    {
                        _pipeDataPort.Post((EnumResponse)item);
                    }
                    else if (item is FormatResponse)
                    {
                        var format = (FormatResponse)item;

                        if (format.Index == -1)
                        {
                            _format = format;
                            if (_state.Selected != null)
                            {
                                if (_state.Selected.Format == null)
                                {
                                    _state.Selected.Format = new Format();
                                }
                                _state.Selected.Format.Width  = _format.Width;
                                _state.Selected.Format.Height = _format.Height;
                            }
                        }
                        else
                        {
                            _pipeDataPort.Post(format);
                        }
                    }
                    else if (item is HresultResponse)
                    {
                        _pipeDataPort.Post((HresultResponse)item);
                    }
                }
                else if (response.IsFrame)
                {
                    ProcessFrame(response);
                }
            }
        }
示例#26
0
 private void ActionNotSupported(PortSet<DefaultUpdateResponseType, W3C.Soap.Fault> responsePort)
 {
     responsePort.Post(Fault.FromCodeSubcodeReason(
         W3C.Soap.FaultCodes.Receiver,
         DsspFaultCodes.ActionNotSupported,
         Resources.NotModifiable
         )
     );
 }
示例#27
0
        /// <summary>
        /// Service start
        /// </summary>
        protected override void Start()
        {
            //
            // Add service specific initialization here
            //

            base.Start();
            int exampleNum = 3;

            switch (exampleNum)
            {
            case 1:
                // Create port that accepts instances of System.Int32
                Port <int> portInt1 = new Port <int>();

                // Add the number 10 to the port
                portInt1.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt1.ItemCount);
                break;

            case 2:
                // Create port that accepts instances of System.Int32
                var portInt2 = new Port <int>();

                // Add the number 10 to the port
                portInt2.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt2.ItemCount);

                // retrieve the item using Test
                int item2;
                var hasItem2 = portInt2.Test(out item2);
                if (hasItem2)
                {
                    Console.WriteLine("Found item in port:" + item2);
                }
                portInt2.Post(11);
                // alternative to using Test is just assignment of port to variable using
                // implicit operator
                var nextItem = portInt2;

                Console.WriteLine("Found item in port:" + nextItem);
                break;

            case 3:
                // Create port that accepts instances of System.Int32
                var portInt3 = new Port <int>();

                // Add the number 10 to the port
                portInt3.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt3.ItemCount);

                // create dispatcher and dispatcher queue for scheduling tasks
                Dispatcher      dispatcher = new Dispatcher();
                DispatcherQueue taskQueue  = new DispatcherQueue("sample queue", dispatcher);

                // retrieve the item by attaching a one time receiver
                Arbiter.Activate(
                    taskQueue,
                    portInt3.Receive(delegate(int item3)     // anonymous method
                {
                    // this code executes in parallel with the method that
                    // activated it
                    Console.WriteLine("Received item:" + item3);
                }
                                     ));
                // any code below runs in parallel with delegate

                break;

            case 4:
                // Create a PortSet using generic type arguments
                var genericPortSet4 = new PortSet <int, string, double>();
                genericPortSet4.Post(10);
                genericPortSet4.Post("hello");
                genericPortSet4.Post(3.14159);

                // Create a runtime PortSet, using the initialization
                // constructor to supply an array of types
                PortSet runtimePortSet4 = new PortSet(
                    typeof(int),
                    typeof(string),
                    typeof(double)
                    );

                runtimePortSet4.PostUnknownType(10);
                runtimePortSet4.PostUnknownType("hello");
                runtimePortSet4.PostUnknownType(3.14159);
                break;

            case 5:
                // create dispatcher and dispatcher queue for scheduling tasks
                Dispatcher      dispatcher5 = new Dispatcher();
                DispatcherQueue taskQueue5  = new DispatcherQueue("sample queue", dispatcher5);
                CcrConsolePort  port5       = CcrConsoleService.Create(taskQueue5);
                break;

            case 6:
                Dispatcher      dispatcher6 = new Dispatcher();
                DispatcherQueue taskQueue6  = new DispatcherQueue("sample queue", dispatcher6);
                CcrConsolePort  port6       = CcrConsoleService.Create(taskQueue6);
                var             portSet6    = new PortSet <int, string, double>();
                // the following statement compiles because of the implicit assignment operators
                // that "extract" the instance of Port<int> from the PortSet
                var portInt6 = portSet6;

                // the implicit assignment operator is used below to "extract" the Port<int>
                // instance so the int receiver can be registered
                Arbiter.Activate(taskQueue6,
                                 Arbiter.Receive <int>(true, portSet6, item => Console.WriteLine(item))
                                 );

                break;

            case 7:
                Dispatcher      dispatcher7 = new Dispatcher();
                DispatcherQueue taskQueue7  = new DispatcherQueue("sample queue", dispatcher7);
                var             port7       = new Port <int>();
                Arbiter.Activate(taskQueue7,
                                 Arbiter.Receive(
                                     true,
                                     port7,
                                     item => Console.WriteLine(item)

                                     /** older syntax
                                      *    delegate(int item){
                                      *        Console.WriteLine(item);
                                      *    }
                                      *
                                      **/

                                     )
                                 );

                // post item, so delegate executes
                port7.Post(5);
                break;

            case 8:
                Dispatcher      dispatcher8 = new Dispatcher();
                DispatcherQueue taskQueue8  = new DispatcherQueue("sample queue", dispatcher8);
                var             port8       = new Port <int>();
                // alternate version that explicitly constructs a Receiver by passing
                // Arbiter class factory methods
                var persistedReceiver = new Receiver <int>(
                    true,                                           // persisted
                    port8,
                    null,                                           // no predicate
                    new Task <int>(item => Console.WriteLine(item)) // task to execute
                    );
                Arbiter.Activate(taskQueue8, persistedReceiver);
                break;

            case 9:
                Dispatcher      dispatcher9 = new Dispatcher();
                DispatcherQueue taskQueue9  = new DispatcherQueue("sample queue", dispatcher9);
                // create a simple service listening on a port
                ServicePort servicePort9 = SimpleService.Create(taskQueue9);

                // create request
                GetState get = new GetState();

                // post request
                servicePort9.Post(get);

                // use the extension method on the PortSet that creates a choice
                // given two types found on one PortSet. This a common use of
                // Choice to deal with responses that have success or failure
                Arbiter.Activate(taskQueue9,
                                 get.ResponsePort.Choice(
                                     s => Console.WriteLine(s),  // delegate for success
                                     ex => Console.WriteLine(ex) // delegate for failure
                                     ));
                break;

            case 10:
                Dispatcher      dispatcher10 = new Dispatcher();
                DispatcherQueue taskQueue10  = new DispatcherQueue("sample queue", dispatcher10);
                var             portDouble   = new Port <double>();
                var             portString   = new Port <string>();

                // activate a joined receiver that will execute only when one
                // item is available in each port.
                Arbiter.Activate(taskQueue10,
                                 portDouble.Join(
                                     portString,             // port to join with
                                     (value, stringValue) => // delegate
                {
                    value      /= 2.0;
                    stringValue = value.ToString();
                    // post back updated values
                    portDouble.Post(value);
                    portString.Post(stringValue);
                })
                                 );

                // post items. The order does not matter, which is what Join its power
                portDouble.Post(3.14159);
                portString.Post("0.1");

                //after the last post the delegate above will execute
                break;
            }
        }
示例#28
0
        IEnumerator <ITask> HttpHandler(HttpListenerContext context, PortSet <HttpResponseType, Fault> responsePort)
        {
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            bool alternate = false;

            string path = request.Url.AbsolutePath.ToLowerInvariant();

            if (path.StartsWith(_alternatePrefix))
            {
                alternate = true;
                path      = path.Substring(_alternatePrefix.Length);
            }
            else if (path.StartsWith(_prefix))
            {
                path = path.Substring(_prefix.Length);
            }

            string      type;
            ImageFormat format;

            switch (path)
            {
            case "/jpeg":
            case "/jpg":
                type   = MediaTypeNames.Image.Jpeg;
                format = ImageFormat.Jpeg;
                break;

            case "/bmp":
                type   = "image/bmp";
                format = ImageFormat.Bmp;
                break;

            case "/png":
                type   = "image/png";
                format = ImageFormat.Png;
                break;

            case "/tif":
            case "/tiff":
                type   = "image/tiff";
                format = ImageFormat.Tiff;
                break;

            case "/gif":
                type   = MediaTypeNames.Image.Gif;
                format = ImageFormat.Gif;
                break;

            default:
                if (alternate)
                {
                    responsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state.Clone(), _transform));
                }
                else
                {
                    responsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state, _transform));
                }
                yield break;
            }

            if (_state.Frame == null)
            {
                if (alternate)
                {
                    responsePort.Post(new HttpResponseType(HttpStatusCode.NotFound, _state.Clone(), _transform));
                }
                else
                {
                    responsePort.Post(new HttpResponseType(HttpStatusCode.NotFound, _state, _transform));
                }
                yield break;
            }

            using (MemoryStream stream = new MemoryStream())
            {
                _state.Frame.Save(stream, format);
                stream.Position = 0;

                response.AddHeader("Cache-Control", "No-cache");

                WriteResponseFromStream write = new WriteResponseFromStream(
                    context, stream, type
                    );

                _utilitiesPort.Post(write);

                yield return(Arbiter.Choice(
                                 write.ResultPort,
                                 delegate(Stream res)
                {
                    stream.Close();
                },
                                 delegate(Exception e)
                {
                    stream.Close();
                    LogError(e);
                }
                                 ));
            }
        }
示例#29
0
 public void OpenHandler(Open open)
 {
     _commOpenClosePort.Post(open);
 }
        private bool ValidateDriveEnabledAndRespondHelper(PortSet<DefaultUpdateResponseType, Fault> responsePort)
        {
            Fault fault = null;

            // Acknowledge request or fault
            if (_genericState.IsEnabled == false)
            {
                fault = Fault.FromException(new InvalidOperationException("Attempting to process a drive operation, but the differential drive is not enabled"));
                responsePort.Post(fault);
            }
            else
            {
                responsePort.Post(DefaultUpdateResponseType.Instance);
            }
            return _genericState.IsEnabled;
        }
示例#31
0
        /// <summary>
        /// Actuator callback
        /// </summary>
        protected override IEnumerator<ITask> SetCallback(Myro.Services.Generic.Vector.SetRequestInfo request, PortSet<vector.CallbackResponseType, Fault> responsePort)
        {
            var req = request as vector.SetElementsRequestInfo;
            if (req != null)
            {
                bool play = false;
                bool loud = false;
                foreach (var i in req.Indices)
                    if (i == 0 || i == 1 || i == 2)
                        play = true;
                    else if (i == 3)
                        loud = true;

                Fault error = null;
                if (loud)
                    yield return Arbiter.Choice(setLoud(),
                        delegate(vector.CallbackResponseType s) { },
                        delegate(Fault f) { error = f; });

                if (error == null && play)
                    yield return Arbiter.Choice(playTone(),
                        delegate(vector.CallbackResponseType s1) { },
                        delegate(Fault f) { error = f; });

                if (error == null)
                    responsePort.Post(vector.CallbackResponseType.Instance);
                else
                    responsePort.Post(error);
            }
            else
            {
                // Otherwise it was a SetAllRequestInfo
                Activate(Arbiter.Choice(setLoud(),
                    delegate(vector.CallbackResponseType s)
                    {
                        Activate(Arbiter.Choice(playTone(),
                            delegate(vector.CallbackResponseType s1) { responsePort.Post(vector.CallbackResponseType.Instance); },
                            delegate(Fault f) { responsePort.Post(f); }));
                    },
                    delegate(Fault f) { responsePort.Post(f); }));
            }
            yield break;
        }
示例#32
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++;
                     byte val =
                         (_state.Get(4) <= 0.0) ?
                         (byte)0 :
                         (byte)(_state.Get(4) * (255.0 - 170.0) + 170.0);
                     Activate(Arbiter.Choice(
                         _scribblerPort.SetLEDBack(val),
                         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;
 }
        IEnumerator <ITask> HttpHandler(HttpListenerContext context, PortSet <HttpResponseType, Fault> responsePort)
        {
            PostUpdateFrameIfNeeded();

            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            string path = request.Url.AbsolutePath;
            string type;

            System.Drawing.Imaging.ImageFormat format;

            if ((path.EndsWith("/jpg")) || (path.EndsWith("/jpeg")))
            {
                type   = MediaTypeNames.Image.Jpeg;
                format = System.Drawing.Imaging.ImageFormat.Jpeg;
            }
            else if (path.EndsWith("/bmp"))
            {
                type   = "image/bmp";
                format = System.Drawing.Imaging.ImageFormat.Bmp;
            }
            else if (path.EndsWith("gif"))
            {
                type   = MediaTypeNames.Image.Gif;
                format = System.Drawing.Imaging.ImageFormat.Gif;
            }
            else if (path.EndsWith("/png"))
            {
                type   = "image/png";
                format = System.Drawing.Imaging.ImageFormat.Png;
            }
            else
            {
                responsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state, _transform));
                yield break;
            }

            if (_entity == null)
            {
                responsePort.Post(Fault.FromException(new Exception("No camera entity found.")));
            }
            else
            {
                var result = new PortSet <int[], Exception>();
                _entity.CaptureScene(result);

                yield return(Arbiter.Choice(result,
                                            delegate(int [] data)
                {
                    var memStream = new MemoryStream();
                    using (var b = _entity.CreateBitmapFromArray(data))
                    {
                        b.Save(memStream, format);
                    }

                    memStream.Seek(0, SeekOrigin.Begin);
                    memStream.WriteTo(response.OutputStream);
                    response.AddHeader("Cache-Control", "No-cache");
                    response.ContentType = type;
                    _state.LastFrameUpdate = DateTime.Now;
                    Utilities.HttpClose(context);
                },
                                            delegate(Exception ex)
                {
                    responsePort.Post(Fault.FromException(ex));
                }
                                            ));
            }
        }