예제 #1
0
 public AdapterSpec(AdapterTypeEnum type, string name, ServiceInfoType serviceConfig)
 {
     Type          = type;
     Name          = name;
     Adapter       = null;
     ServiceConfig = serviceConfig;
 }
예제 #2
0
 public VectorAdapter(ServiceInfoType serviceRecord)
 {
     ServiceInfo = serviceRecord;
     opPort      = DssEnvironment.ServiceForwarder <vector.VectorOperations>(new Uri(serviceRecord.Service));
     //if (opPort == null)
     //    throw new AdapterCreationException("Service forwarder port was null");
 }
예제 #3
0
        private void listDirectory_DoubleClick(object sender, EventArgs e)
        {
            ServiceInfoType[] list = listDirectory.Tag as ServiceInfoType[];

            if (list != null &&
                listDirectory.SelectedIndex >= 0 &&
                listDirectory.SelectedIndex < list.Length)
            {
                // get the service path from the selected item
                string[] tokens = ((string)listDirectory.SelectedItem).Split(new char[] { ' ' });
                if (tokens.Length == 0)
                {
                    return;
                }

                ServiceInfoType info = FindServiceInfoFromServicePath(tokens[tokens.Length - 1]);
                if (info == null)
                {
                    return;
                }
                if (info.Contract == drive.Contract.Identifier)
                {
                    _eventsPort.Post(new OnConnectMotor(this, info.Service));
                }
                else if (info.Contract == sicklrf.Contract.Identifier)
                {
                    _eventsPort.Post(new OnConnectSickLRF(this, info.Service));
                }
                else if (info.Contract == arm.Contract.Identifier)
                {
                    _eventsPort.Post(new OnConnectArticulatedArm(this, info.Service));
                }
            }
        }
예제 #4
0
        IEnumerator <ITask> OnConnectHandler(OnConnect onConnect)
        {
            if (onConnect.DriveControl == _driveControl)
            {
                UriBuilder builder = new UriBuilder(onConnect.Service);
                builder.Scheme = new Uri(ServiceInfo.Service).Scheme;

                ds.DirectoryPort port = ServiceForwarder <ds.DirectoryPort>(builder.Uri);
                ds.Get           get  = new ds.Get();

                port.Post(get);
                ServiceInfoType[] list = null;

                yield return(Arbiter.Choice(get.ResponsePort,
                                            delegate(ds.GetResponseType response)
                {
                    list = response.RecordList;
                },
                                            delegate(Fault fault)
                {
                    list = new ServiceInfoType[0];
                    LogError(fault);
                }
                                            ));

                WinFormsServicePort.FormInvoke(
                    delegate()
                {
                    _driveControl.ReplaceDirectoryList(list);
                }
                    );
            }
        }
예제 #5
0
 public NoContractFoundException(ServiceInfoType goal, List <string> targets) :
     base("Could not find a contract of service " + goal.Service + " matching any compatible contracts: " +
          String.Concat((from t in targets
                         select t + "   ").ToArray()))
 {
     //Console.WriteLine("***" + this.ToString());
 }
예제 #6
0
 /// <summary>
 /// See adapter documentation in the Myro 3 developer manual.
 /// http://wiki.roboteducation.org/Myro_3.0_Developer_Manual
 /// </summary>
 public VectorAdapter(ServiceInfoType serviceRecord)
 {
     ServiceInfo = serviceRecord;
     opPort = DssEnvironment.ServiceForwarder<vector.VectorOperations>(new Uri(serviceRecord.Service));
     //if (opPort == null)
     //    throw new AdapterCreationException("Service forwarder port was null");
 }
예제 #7
0
        public void ServiceInfoType_To_CommonIPTVServiceV7ServiceInfoType()
        {
            //*** Arrange ***
            var serviceInfoType = new ServiceInfoType
            {
            };

            //*** Act ***
            var apmaxSubscriberTypeV3 = ObjectFactory.CreateInstanceAndMap <ServiceInfoType, Common.IPTVServiceV7.ServiceInfoType>(_commonMapper, serviceInfoType);

            Assert.IsNotNull(apmaxSubscriberTypeV3);
        }
        /// <summary>
        /// Creates an instance of the service associated with this contract
        /// </summary>
        /// <param name="contructorServicePort">Contractor Service that will create the instance</param>
        /// <param name="partners">Optional list of service partners for new service instance</param>
        /// <returns>Result PortSet for retrieving service creation response</returns>
        public static DsspResponsePort<CreateResponse> CreateService(constructor.ConstructorPort contructorServicePort, params PartnerType[] partners)
        {
            DsspResponsePort<CreateResponse> result = new DsspResponsePort<CreateResponse>();
            ServiceInfoType si = new ServiceInfoType(Contract.Identifier, null);
            if (partners != null)
            {
                si.PartnerList = new List<PartnerType>(partners);
            }
            Microsoft.Dss.Services.Constructor.Create create =
                new Microsoft.Dss.Services.Constructor.Create(si, result);
            contructorServicePort.Post(create);
            return result;

        }
예제 #9
0
        protected void readConfig(string configFile)
        {
            services = new List <ServiceInfoType>();
            //adapterTypes = new Dictionary<AdapterTypes,ArrayList>();
            adapterNames = new Dictionary <string, AdapterSpec>();

            XPathNavigator nav = new XPathDocument(configFile).CreateNavigator();

            // Add plain services to list
            XPathNodeIterator startservices = nav.Select("//StartService");

            foreach (XPathNavigator node in startservices)
            {
                services.Add(new ServiceInfoType(getChild(node, "Contract"), getChild(node, "Service")));
            }

            // Add adapters to list, and to dictionary
            XPathNodeIterator adapters = nav.Select("//Adapter");

            Console.WriteLine(adapters.Count + " adapters in config");
            foreach (XPathNavigator node in adapters)
            {
                // Get the relevant info for this adapter

                // Attributes
                string          sType = node.GetAttribute("type", "");
                AdapterTypeEnum type  = AdapterFactory.GetType(sType);
                string          name  = node.GetAttribute("name", "");

                // Children
                string contract = getChild(node, "Contract", true);
                string service  = getChild(node, "Service");

                // Add elements to the service array and dictionary
                if (adapterNames.ContainsKey(name))
                {
                    throw new ConfigException("Duplicate adapter name \"" + name + "\"");
                }
                else
                {
                    // Add a null adapter for now.  An adapter will be created when the service is actually started
                    ServiceInfoType serviceInfo = new ServiceInfoType(contract, service);
                    AdapterSpec     adapterInfo = new AdapterSpec(type, name, serviceInfo);
                    adapterNames.Add(name, adapterInfo);
                    //adapterServices.Add(service, adapterInfo);
                    //services.Add(serviceInfo);
                }
            }
        }
예제 #10
0
        public void Can_Map_Provisioning_API_ServiceInfoType_To_ApMax_SubscriberTypeV4_ServiceInfoType()
        {
            //*** Arrange ***
            var provSubscriberType = new ServiceInfoType
            {
                ApSystemId            = null,
                BillingServiceAddress = "111 my addres st Sioux Falls, SD 57111",
                BillingServiceID      = "2",
                ServiceGuid           = Guid.NewGuid().ToString(),
                ServiceType           = ServiceType.Iptv
            };

            //*** Act ***
            var apmaxSubscriberTypeV3 = ObjectFactory.CreateInstanceAndMap <ServiceInfoType, Common.SubscriberV4.ServiceInfoType>(_commonMapper, provSubscriberType);

            Assert.IsNotNull(apmaxSubscriberTypeV3);
        }
예제 #11
0
파일: Robot.cs 프로젝트: yingted/Myro
        /// <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();
            }
        }
예제 #12
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;
                }
            }
        }
예제 #13
0
        IEnumerator <ITask> OnStartServiceHandler(OnStartService onStartService)
        {
            if (onStartService.DriveControl == _driveControl &&
                onStartService.Constructor != null)
            {
                cs.ConstructorPort port = ServiceForwarder <cs.ConstructorPort>(onStartService.Constructor);

                ServiceInfoType request = new ServiceInfoType(onStartService.Contract);
                cs.Create       create  = new cs.Create(request);

                port.Post(create);

                string service = null;

                yield return(Arbiter.Choice(
                                 create.ResponsePort,
                                 delegate(CreateResponse response)
                {
                    service = response.Service;
                },
                                 delegate(Fault fault)
                {
                    LogError(fault);
                }
                                 ));


                if (service == null)
                {
                    yield break;
                }

                WinFormsServicePort.FormInvoke(
                    delegate()
                {
                    _driveControl.StartedSickLRF();
                }
                    );
            }
        }
예제 #14
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
        /// if one cannot be found.
        /// </summary>
        /// <param name="taskQueue"></param>
        /// <param name="service"></param>
        /// <param name="contracts"></param>
        /// <returns></returns>
        public static ServiceInfoType FindCompatibleContract(ServiceInfoType serviceRecord, List <string> contracts)
        {
            ServiceInfoType ret      = null;
            int             retIndex = Int32.MaxValue;

            // See if we can understand the primary contract
            int i = contracts.FindIndex(
                (s => serviceRecord.Contract.Equals(s, StringComparison.Ordinal)));

            if (i >= 0 && i < retIndex)
            {
                ret      = serviceRecord;
                retIndex = i;
            }

            // Now try each alternate contract
            foreach (var part in serviceRecord.PartnerList)
            {
                // Alternate contract services have a name of "AlternateContractService".
                if (part.Name.Name.StartsWith("AlternateContractService"))
                {
                    i = contracts.FindIndex(
                        (s => part.Contract.Equals(s, StringComparison.Ordinal)));
                    if (i >= 0 && i < retIndex)
                    {
                        ret      = part;
                        retIndex = i;
                    }
                }
            }
            if (ret != null)
            {
                return(ret);
            }
            else
            {
                throw new NoContractFoundException(serviceRecord, contracts);
            }
        }
예제 #15
0
        public static void CreateAdapterIfNeeded(AdapterSpec adapterSpec, ServiceInfoType serviceRecord)
        {
            Monitor.Enter(adapterSpec);
            try
            {
                if (adapterSpec.Adapter == null)
                {
                    switch (adapterSpec.Type)
                    {
                    case AdapterTypeEnum.Vector:
                        adapterSpec.Adapter = (IAdapter <Object>)(new Adapters.VectorAdapter(serviceRecord));
                        break;

                    case AdapterTypeEnum.Drive:
                        adapterSpec.Adapter = (IAdapter <Object>)(new Adapters.DriveAdapter(serviceRecord));
                        break;

                    default:
                        throw new Exception("Adapter type " + GetTypeName(adapterSpec.Type) + " not yet supported");
                    }
                }
                else
                {
                    //Console.WriteLine("*** ERROR *** Adapter for this AdapterSpec already has been created");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("*** ERROR *** " + e);
            }
            finally
            {
                //Console.WriteLine("Unlocking");
                Monitor.Exit(adapterSpec);
            }
        }
예제 #16
0
파일: Robot.cs 프로젝트: yingted/Myro
        /// <summary>
        /// Helper method that waits for a service to start and runs a handler when it does.
        /// This subscribes to and queries the DSS directory.
        /// </summary>
        /// <param name="serviceInfo"></param>
        /// <param name="handler"></param>
        private static void waitForService(ServiceInfoType serviceInfo, Handler <ServiceInfoType> handler)
        {
            var dirPort = DssEnvironment.ServiceForwarder <directory.DirectoryPort>(new Uri("dssp.tcp://localhost/directory"));
            var notPort = new directory.DirectoryPort();

            // Keep this flag to only run the handler once
            bool   ranHandler = false;
            Object lockObj    = new Object();

            // Subscribe first, then query, to make sure we don't miss the service registering itself
            DssEnvironment.LogInfo("Subscribing to directory");
            Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Choice(
                                 dirPort.Subscribe(
                                     new directory.SubscribeRequest()
            {
                QueryRecordList = new List <ServiceInfoType>()
                {
                    serviceInfo
                },
                NotificationCount = 1
            },
                                     notPort,
                                     typeof(directory.Insert)),
                                 delegate(SubscribeResponseType r)
            {
                DssEnvironment.LogInfo("Subscribed to directory!");

                // Run handler if the service starts and we get the subscription notification
                DssEnvironment.LogInfo("Activating subscription receive");
                Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Receive <directory.Insert>(false, notPort,
                                                                                              delegate(directory.Insert ins)
                {
                    DssEnvironment.LogInfo("Got subscription notification!");
                    lock (lockObj)
                    {
                        if (ranHandler == false)
                        {
                            new Thread(new ThreadStart(delegate() { handler.Invoke(ins.Body.Record); })).Start();
                            ranHandler = true;
                        }
                    }
                }));
            },
                                 delegate(Fault f)
            {
                lock (lockObj)
                {
                    if (ranHandler == false)
                    {
                        new Thread(new ThreadStart(delegate() { handler.Invoke(null); })).Start();
                        ranHandler = true;
                    }
                }
                DssEnvironment.LogError("Fault received while subscribing to directory: " + Strings.FromFault(f));
            }));

            // Query directory, run handler if the service is already started
            DssEnvironment.LogInfo("Querying directory");
            Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Choice(
                                 dirPort.Query(new directory.QueryRequest()
            {
                QueryRecord = serviceInfo
            }),
                                 delegate(directory.QueryResponse r)
            {
                DssEnvironment.LogInfo("Queried directory!");
                lock (lockObj)
                {
                    if (ranHandler == false && r.RecordList.Length > 0)
                    {
                        new Thread(new ThreadStart(delegate() { handler.Invoke(r.RecordList[0]); })).Start();
                        ranHandler = true;
                    }
                }
            },
                                 delegate(Fault f)
            {
                //lock (lockObj)
                //{
                //    if (ranHandler == false)
                //    {
                //        new Thread(new ThreadStart(delegate() { handler.Invoke(null); })).Start();
                //        ranHandler = true;
                //    }
                //}
                DssEnvironment.LogError("Fault received while querying directory: " + Strings.FromFault(f));
            }));
        }
예제 #17
0
 public NoAdapterFoundException(ServiceInfoType record)
     : base("Could not find an adapter for " + record.Service + ", with contract " + record.Contract)
 {
 }
예제 #18
0
 /// <summary>
 /// See documentation for IAdapterFactory in IAdapter.cs
 /// </summary>
 public IAdapter Create(ServiceInfoType service)
 {
     return new VectorAdapter(service);
 }
예제 #19
0
        IEnumerator<ITask> OnStartServiceHandler(OnStartService onStartService)
        {
            if (onStartService.DriveControl == _driveControl &&
                onStartService.Constructor != null)
            {
                cs.ConstructorPort port = ServiceForwarder<cs.ConstructorPort>(onStartService.Constructor);

                ServiceInfoType request = new ServiceInfoType(onStartService.Contract);
                cs.Create create = new cs.Create(request);

                port.Post(create);

                string service = null;

                yield return Arbiter.Choice(
                    create.ResponsePort,
                    delegate(CreateResponse response)
                    {
                        service = response.Service;
                    },
                    delegate(Fault fault)
                    {
                        LogError(fault);
                    }
                );


                if (service == null)
                {
                    yield break;
                }

                WinFormsServicePort.FormInvoke(
                    delegate()
                    {
                        _driveControl.StartedSickLRF();
                    }
                );
            }
        }
예제 #20
0
파일: Robot.cs 프로젝트: SamLin95/cs3630
        /// <summary>
        /// Helper method that waits for a service to start and runs a handler when it does.
        /// This subscribes to and queries the DSS directory.
        /// </summary>
        /// <param name="serviceInfo"></param>
        /// <param name="handler"></param>
        private static void waitForService(ServiceInfoType serviceInfo, Handler<ServiceInfoType> handler)
        {
            var dirPort = DssEnvironment.ServiceForwarder<directory.DirectoryPort>(new Uri("dssp.tcp://localhost/directory"));
            var notPort = new directory.DirectoryPort();

            // Keep this flag to only run the handler once
            bool ranHandler = false;
            Object lockObj = new Object();

            // Subscribe first, then query, to make sure we don't miss the service registering itself
            DssEnvironment.LogInfo("Subscribing to directory");
            Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Choice(
                dirPort.Subscribe(
                    new directory.SubscribeRequest()
                    {
                        QueryRecordList = new List<ServiceInfoType>() { serviceInfo },
                        NotificationCount = 1
                    },
                    notPort,
                    typeof(directory.Insert)),
                delegate(SubscribeResponseType r)
                {
                    DssEnvironment.LogInfo("Subscribed to directory!");

                    // Run handler if the service starts and we get the subscription notification
                    DssEnvironment.LogInfo("Activating subscription receive");
                    Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Receive<directory.Insert>(false, notPort,
                        delegate(directory.Insert ins)
                        {
                            DssEnvironment.LogInfo("Got subscription notification!");
                            lock (lockObj)
                            {
                                if (ranHandler == false)
                                {
                                    new Thread(new ThreadStart(delegate() { handler.Invoke(ins.Body.Record); })).Start();
                                    ranHandler = true;
                                }
                            }
                        }));
                },
                delegate(Fault f)
                {
                    lock (lockObj)
                    {
                        if (ranHandler == false)
                        {
                            new Thread(new ThreadStart(delegate() { handler.Invoke(null); })).Start();
                            ranHandler = true;
                        }
                    }
                    DssEnvironment.LogError("Fault received while subscribing to directory: " + Strings.FromFault(f));
                }));

            // Query directory, run handler if the service is already started
            DssEnvironment.LogInfo("Querying directory");
            Arbiter.Activate(DssEnvironment.TaskQueue, Arbiter.Choice(
                dirPort.Query(new directory.QueryRequest() { QueryRecord = serviceInfo }),
                delegate(directory.QueryResponse r)
                {
                    DssEnvironment.LogInfo("Queried directory!");
                    lock (lockObj)
                    {
                        if (ranHandler == false && r.RecordList.Length > 0)
                        {
                            new Thread(new ThreadStart(delegate() { handler.Invoke(r.RecordList[0]); })).Start();
                            ranHandler = true;
                        }
                    }
                },
                delegate(Fault f)
                {
                    //lock (lockObj)
                    //{
                    //    if (ranHandler == false)
                    //    {
                    //        new Thread(new ThreadStart(delegate() { handler.Invoke(null); })).Start();
                    //        ranHandler = true;
                    //    }
                    //}
                    DssEnvironment.LogError("Fault received while querying directory: " + Strings.FromFault(f));
                }));

        }
예제 #21
0
파일: Robot.cs 프로젝트: SamLin95/cs3630
 /// <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();
     }
 }
예제 #22
0
 public IAdapter Create(ServiceInfoType service)
 {
     return(new VectorAdapter(service));
 }
예제 #23
0
        public void ReplaceDirectoryList(ServiceInfoType[] list)
        {
            listDirectory.BeginUpdate();
            try
            {
                listDirectory.Tag = list;
                listDirectory.Items.Clear();

                if (list.Length > 0)
                {
                    UriBuilder node = new UriBuilder(list[0].Service);
                    node.Path = null;
                    lblNode.Text = node.Host + ":" + node.Port;
                    txtMachine.Text = node.Host;
                    txtPort.Text = node.Port.ToString();

                    linkDirectory.Enabled = true;
                }
                else
                {
                    lblNode.Text = string.Empty;
                    linkDirectory.Enabled = false;
                }

                foreach (ServiceInfoType info in list)
                {
                    if (info.Contract == sicklrf.Contract.Identifier ||
                        info.Contract == drive.Contract.Identifier ||
                        info.Contract == arm.Contract.Identifier ||
                        info.Contract == pxsonar.Contract.Identifier ||
                        info.Contract == pxbumper.Contract.Identifier ||
                        info.Contract == pxPanTilt.Contract.Identifier ||
                        info.Contract == webcam.Contract.Identifier ||
                        info.Contract == pxGPS.Contract.Identifier )
                        // info.Contract == vision.Contract.Identifier) 

                    {
                        Uri serviceUri = new Uri(info.Service);
                        listDirectory.Items.Add(serviceUri.AbsolutePath);
                    }
                }

                if (ServiceByContract(sicklrf.Contract.Identifier) == null)
                {
                    btnStartLRF.Enabled = true;
                    btnConnectLRF.Enabled = false;
                }
                else
                {
                    btnStartLRF.Enabled = false;
                    btnConnectLRF.Enabled = true;
                }


                if (ServiceByContract(pxsonar.Contract.Identifier) == null)
                {
                    btnStartSonar.Enabled = true;
                    btnConnectSonar.Enabled = false;
                }
                else
                {
                    btnStartSonar.Enabled = false;
                    btnConnectSonar.Enabled = true;
                }

                if (ServiceByContract(webcam.Contract.Identifier) == null)
                {
                    btnCamConnect.Enabled = false;
                    btnCamDisconnect.Enabled = false;
                }
                else
                {
                    btnCamConnect.Enabled = true;                    
                }
                /*
                if (ServiceByContract(vision.Contract.Identifier) == null)
                {
                    btnConnectVision.Enabled = false;
                    btnDisconnectVision.Enabled = false;
                }
                 
                else
                {
                    btnConnectVision.Enabled = true;
                    btnDisconnectVision.Enabled = false;
                }
                */
            }
            finally
            {
                listDirectory.EndUpdate();
            }
        }
예제 #24
0
        public void HttpPostHandler(HttpPost httpPost)
        {
            HttpPostRequestData formData = httpPost.GetHeader <HttpPostRequestData>();

            try
            {
                DsspOperation operation = formData.TranslatedOperation;

                if (operation is DriveDistance)
                {
                    _mainPort.Post((DriveDistance)operation);
                }
                else if (operation is SetDrivePower)
                {
                    _mainPort.Post((SetDrivePower)operation);
                }
                else if (operation is RotateDegrees)
                {
                    _mainPort.Post((RotateDegrees)operation);
                }
                else if (operation is EnableDrive)
                {
                    _mainPort.Post((EnableDrive)operation);
                }
                else if (operation is AllStop)
                {
                    _mainPort.Post((AllStop)operation);
                }
                else if (operation is ResetEncoders)
                {
                    _mainPort.Post((ResetEncoders)operation);
                }
                else
                {
                    NameValueCollection parameters = formData.Parameters;

                    if (parameters["StartDashboard"] != null)
                    {
                        string          Dashboardcontract = "http://schemas.microsoft.com/robotics/2006/01/simpledashboard.user.html";
                        ServiceInfoType info   = new ServiceInfoType(Dashboardcontract);
                        cons.Create     create = new cons.Create(info);
                        create.TimeSpan = DsspOperation.DefaultShortTimeSpan;

                        ConstructorPort.Post(create);
                        Activate(Arbiter.Choice(
                                     create.ResponsePort,
                                     delegate(CreateResponse createResponse) { },
                                     delegate(Fault f) { LogError(f); }
                                     ));
                    }
                    else if (parameters["DrivePower"] != null)
                    {
                        double power = double.Parse(parameters["Power"]);
                        SetDrivePowerRequest drivepower = new SetDrivePowerRequest();
                        drivepower.LeftWheelPower  = power;
                        drivepower.RightWheelPower = power;
                        _mainPort.Post(new SetDrivePower(drivepower));
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }
                }
                HttpPostSuccess(httpPost);
            }
            catch
            {
                HttpPostFailure(httpPost);
            }
        }
예제 #25
0
 /// <summary>
 /// See adapter documentation in the Myro 3 developer manual.
 /// http://wiki.roboteducation.org/Myro_3.0_Developer_Manual
 /// </summary>
 /// <param name="serviceRecord"></param>
 public FlukeControlAdapter(ServiceInfoType service)
 {
     this.ServiceInfo = service;
     opPort           = DssEnvironment.ServiceForwarder <fluke.CamControlOperations>(new Uri(service.Service));
 }
예제 #26
0
 /// <summary>
 /// See documentation for IAdapterFactory in IAdapter.cs
 /// </summary>
 public IAdapter Create(ServiceInfoType service)
 {
     return new DriveAdapter(service);
 }
예제 #27
0
 /// <summary>
 /// See adapter documentation in the Myro 3 developer manual.
 /// http://wiki.roboteducation.org/Myro_3.0_Developer_Manual
 /// </summary>
 /// <param name="serviceRecord"></param>
 public FlukeControlAdapter(ServiceInfoType service)
 {
     this.ServiceInfo = service;
     opPort = DssEnvironment.ServiceForwarder<fluke.CamControlOperations>(new Uri(service.Service));
 }
예제 #28
0
 /// <summary>
 /// See documentation for IAdapterFactory in IAdapter.cs
 /// </summary>
 public IAdapter Create(ServiceInfoType service)
 {
     return new FlukeControlAdapter(service);
 }
예제 #29
0
 public IAdapter Create(ServiceInfoType service)
 {
     return(new WebcamAdapter(service));
 }
예제 #30
0
        public void HttpPostHandler(HttpPost httpPost)
        {
            HttpPostRequestData formData = httpPost.GetHeader<HttpPostRequestData>();

            try
            {
                DsspOperation operation = formData.TranslatedOperation;

                if (operation is DriveDistance)
                {
                    _mainPort.Post((DriveDistance)operation);
                }
                else if (operation is SetDrivePower)
                {
                    _mainPort.Post((SetDrivePower)operation);
                }
                else if (operation is RotateDegrees)
                {
                    _mainPort.Post((RotateDegrees)operation);
                }
                else if (operation is EnableDrive)
                {
                    _mainPort.Post((EnableDrive)operation);
                }
                else if (operation is AllStop)
                {
                    _mainPort.Post((AllStop)operation);
                }
                else
                {
                    NameValueCollection parameters = formData.Parameters;

                    if (parameters["StartDashboard"] != null)
                    {
                        string Dashboardcontract = "http://schemas.microsoft.com/robotics/2006/01/simpledashboard.html";
                        ServiceInfoType info = new ServiceInfoType(Dashboardcontract);
                        cons.Create create = new cons.Create(info);
                        create.TimeSpan = DsspOperation.DefaultShortTimeSpan;

                        ConstructorPort.Post(create);
                        Arbiter.Choice(
                            create.ResponsePort,
                            delegate(CreateResponse createResponse) { },
                            delegate(Fault f) { LogError(f); }
                        );
                    }
                    else if (parameters["DrivePower"] != null)
                    {
                        double power = double.Parse(parameters["Power"]);
                        SetDrivePowerRequest drivepower = new SetDrivePowerRequest();
                        drivepower.LeftWheelPower = power;
                        drivepower.RightWheelPower = power;
                        _mainPort.Post(new SetDrivePower(drivepower));
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }
                }
                HttpPostSuccess(httpPost);
            }
            catch
            {
                HttpPostFailure(httpPost);
            }
        }
예제 #31
0
 public WebcamAdapter(ServiceInfoType serviceInfo)
 {
     ServiceInfo = serviceInfo;
     opPort      = DssEnvironment.ServiceForwarder <webcam.WebCamOperations>(new Uri(serviceInfo.Service));
 }
예제 #32
0
 /// <summary>
 /// See documentation for IAdapterFactory in IAdapter.cs
 /// </summary>
 public IAdapter Create(ServiceInfoType service)
 {
     return new WebcamAdapter(service);
 }
예제 #33
0
        IEnumerator <ITask> InitializeCamera()
        {
            ServiceInfoType info  = null;
            Fault           fault = null;

            yield return(Arbiter.Choice(
                             _blobTrackerPort.DsspDefaultLookup(),
                             delegate(LookupResponse success)
            {
                info = success;
            },
                             delegate(Fault f)
            {
                fault = f;
            }
                             ));

            if (fault != null)
            {
                LogError(null, "Lookup failed on BlobTracker partner", fault);
                yield break;
            }

            PartnerType camera = FindPartner(
                new XmlQualifiedName("WebCam", bt.Contract.Identifier),
                info.PartnerList
                );

            if (camera == null ||
                string.IsNullOrEmpty(camera.Service))
            {
                LogError("No camera partner found for BlobTracker");
                yield break;
            }

            _webCamPort = ServiceForwarder <cam.WebCamOperations>(camera.Service);

            yield return(Arbiter.Choice(
                             _webCamPort.Subscribe(_webCamNotify, typeof(cam.UpdateFrame)),
                             delegate(SubscribeResponseType success) { },
                             delegate(Fault f)
            {
                fault = f;
            }
                             ));

            if (fault != null)
            {
                LogError(null, "Failed to subscribe to webcam", fault);
                yield break;
            }

            yield return(Arbiter.Choice(
                             _blobTrackerPort.Subscribe(_blobTrackerNotify),
                             delegate(SubscribeResponseType success) { },
                             delegate(Fault f)
            {
                fault = f;
            }
                             ));

            if (fault != null)
            {
                LogError(null, "Failed to subscribe to blob tracker", fault);
                yield break;
            }

            RunForm runForm = new RunForm(CreateVisualization);

            WinFormsServicePort.Post(runForm);

            yield return(Arbiter.Choice(
                             runForm.pResult,
                             delegate(SuccessResult success) { },
                             delegate(Exception e)
            {
                fault = Fault.FromException(e);
            }
                             ));

            if (fault != null)
            {
                LogError(null, "Failed to Create Visualization window", fault);
                yield break;
            }

            base.MainPortInterleave.CombineWith(
                Arbiter.Interleave(
                    new TeardownReceiverGroup(),
                    new ExclusiveReceiverGroup(
                        Arbiter.Receive <cam.UpdateFrame>(true, _webCamNotify, CameraUpdateFrameHandler),
                        Arbiter.Receive <bt.ImageProcessed>(true, _blobTrackerNotify, BlobTrackerImageProcessedHandler),
                        Arbiter.Receive <Shutdown>(true, _shutdownPort, ShutdownHandler)
                        ),
                    new ConcurrentReceiverGroup(
                        Arbiter.Receive <bt.DeleteBin>(true, _blobTrackerNotify, EmptyHandler),
                        Arbiter.Receive <bt.InsertBin>(true, _blobTrackerNotify, EmptyHandler),
                        Arbiter.Receive <bt.UpdateBin>(true, _blobTrackerNotify, EmptyHandler)
                        )
                    )
                );
        }
예제 #34
0
 /// <summary>
 /// See adapter documentation in the Myro 3 developer manual.
 /// http://wiki.roboteducation.org/Myro_3.0_Developer_Manual
 /// </summary>
 public WebcamAdapter(ServiceInfoType serviceInfo)
 {
     ServiceInfo = serviceInfo;
     opPort = DssEnvironment.ServiceForwarder<webcam.WebCamOperations>(new Uri(serviceInfo.Service));
 }
예제 #35
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();
            }
        }
예제 #36
0
 public IAdapter Create(ServiceInfoType service)
 {
     return(new DriveAdapter(service));
 }
        /// <summary>
        /// Creates an instance of the LEGO NXT Communications service.
        /// </summary>
        /// <returns>Result PortSet for retrieving service creation response</returns>
        private DsspResponsePort<CreateResponse> CreateNxtCommunicationService()
        {
            DsspResponsePort<CreateResponse> createResponsePort = new DsspResponsePort<CreateResponse>();
            ServiceInfoType si = new ServiceInfoType(comm.Contract.Identifier, null);

            Microsoft.Dss.Services.Constructor.Create create =
                new Microsoft.Dss.Services.Constructor.Create(si, createResponsePort);

            base.ConstructorPort.Post(create);

            return createResponsePort;
        }
예제 #38
0
 public DriveAdapter(ServiceInfoType serviceRecord)
 {
     ServiceInfo = serviceRecord;
     Initialize();
 }
예제 #39
0
 /// <summary>
 /// See adapter documentation in the Myro 3 developer manual.
 /// http://wiki.roboteducation.org/Myro_3.0_Developer_Manual
 /// </summary>
 /// <param name="serviceRecord"></param>
 public DriveAdapter(ServiceInfoType serviceRecord)
 {
     ServiceInfo = serviceRecord;
     Initialize();
 }
예제 #40
0
        IEnumerator<ITask> OnConnectHandler(OnConnect onConnect)
        {
            if (onConnect.DriveControl == _driveControl)
            {
                UriBuilder builder = new UriBuilder(onConnect.Service);
                builder.Scheme = new Uri(ServiceInfo.Service).Scheme;

                ds.DirectoryPort port = ServiceForwarder<ds.DirectoryPort>(builder.Uri);
                // TT Nov-2006 - Changed for new CTP
                // ds.Get get = new ds.Get(GetRequestType.Instance);
                ds.Get get = new ds.Get();

                port.Post(get);
                ServiceInfoType[] list = null;

                yield return Arbiter.Choice(get.ResponsePort,
                    delegate(ds.GetResponseType response)
                    {
                        list = response.RecordList;
                    },
                    delegate(Fault fault)
                    {
                        list = new ServiceInfoType[0];
                        LogError(fault);
                    }
                );

                WinFormsServicePort.FormInvoke(
                    delegate()
                    {
                        _driveControl.ReplaceDirectoryList(list);
                    }
                );
            }
        }
        public IEnumerator<ITask> ConnectToBiclopsService()
        {
            _biclopsConnected = false;

            loadRemoteServiceDirectoryPorts();

            ds.DirectoryPort remoteDir;
            int k;

            List<biclops.BiclopsOperations> PortList = new List<biclops.BiclopsOperations>();

            while (_biclopsConnected == false)
            {
                for (k = 0; k < _remoteHosts.Count; k++)
                {
                    remoteDir = ServiceForwarder<ds.DirectoryPort>(_remoteHosts[k] + "/directory");
                    ServiceInfoType ServiceInfo = new ServiceInfoType(biclops.Contract.Identifier);
                    ds.QueryRequestType ReqBody;
                    ds.Query Query;

                    ReqBody = new ds.QueryRequestType(ServiceInfo);
                    Query = new ds.Query(ReqBody);

                    // Post query
                    remoteDir.Post(Query);
                    yield return Arbiter.Choice(Query.ResponsePort,
                        delegate(ds.QueryResponseType success)
                        {
                            if (success.RecordList != null)
                            {
                                Console.Write("Received {0} biclops service responses from directory\n", success.RecordList.Length);
                                foreach (ServiceInfoType si in success.RecordList)
                                {
                                    _biclopsPort = base.ServiceForwarder<biclops.BiclopsOperations>(si.Service);
                                    _biclopsConnected = true;
                                    break;
                                }
                            }
                        },
                        delegate(Fault f)
                        {
                            LogError(LogGroups.Console, f.ToString());
                        }
                    );
                    if (_biclopsConnected)
                        break;
                    else
                    {
                        Console.WriteLine("BiclopsRightCameraJointConfiguration: cannot to connect to the Biclops Service\nStart one now if it has not been started and add the host/port to the hosts.txt");
                        Thread.Sleep(2000);
                    }
                }

            }

            yield break;
        }
예제 #42
0
 /// <summary>
 /// See documentation for IAdapterFactory in IAdapter.cs
 /// </summary>
 public IAdapter Create(ServiceInfoType service)
 {
     return(new FlukeControlAdapter(service));
 }