Esempio n. 1
0
        private SimpleService(DispatcherQueue taskQueue)
        {
            // create PortSet instance used by external callers to post items
            _mainPort = new ServicePort();

            // cache dispatcher queue used to schedule tasks
            _taskQueue = taskQueue;
        }
Esempio n. 2
0
        private static async Task GetPreComposeCheck(ServicePort servicePort, ILogger logger)
        {
            var isServiceUp = await PortAvailabilityChecker.IsAvailable(servicePort.Port);

            logger.Log((isServiceUp ? "Warning! " : string.Empty) +
                       $"service {servicePort.Name} on port: {servicePort.Port} was " +
                       (isServiceUp ? string.Empty : "not ") + "occupied before docker compose execution");
        }
Esempio n. 3
0
        private void CreateServicePort(string key, ClientConfig clientConfig)
        {
            //TcpSvr svr = new TcpSvr(clientConfig.p, This_service_Config.ServiceMaxConnectCount, new Coder(Coder.EncodingMothord.UTF8));

            //1 查个数
            int count = ChaGeShu(key);

            if (count == 0)
            {
                // 开端口
                for (int i = 0; i < clientConfig.LAN_list.Count; i++)
                {
                    ServicePort temp = new ServicePort();
                    temp.Key    = key;
                    temp.Client = clientConfig.Session;
                    temp.Lan    = clientConfig.LAN_list[i];

                    ushort port = MakePortForClient(); // 这里要内部做一个分配端口的方法。
                    temp.Port = new TcpSvr(port, 25, new Coder(Coder.EncodingMothord.UTF8));

                    //处理客户端连接数已满事件
                    temp.Port.ServerFull += new NetEvent(clientServerFull);
                    //处理新客户端连接事件
                    temp.Port.ClientConn += new NetEvent(clientClientConn);
                    //处理客户端关闭事件
                    temp.Port.ClientClose += new NetEvent(clientClientClose);
                    //处理接收到数据事件
                    temp.Port.RecvData += new NetEvent(clientRecvData);

                    if (!temp.Port.IsRun)
                    {
                        temp.Port.Start();
                    }

                    PortsForListing.Add(temp);
                }
            }
            else
            {
                //2 对比
                if (count == clientConfig.LAN_list.Count)
                {
                    //不动
                }
                else
                {
                    //清除后,重新开。
                    CloseServicePort(key);
                    CreateServicePort(key, clientConfig);
                }
            }
        }
Esempio n. 4
0
 /*!
  *      Switches the programming mode off or on
  *      of device with individual address "address"
  */
 static void SwitchProgMode(ServicePort servicePort, bool enable)
 {
     try
     {
         Logger.Log(Logger.Level.Information, "Switch Prog Mode");
         Logger.Log(Logger.Level.Information, "================");
         servicePort.SwitchProgMode(address, enable);
     }
     catch (KdriveException e)
     {
         Logger.Log(Logger.Level.Error, "Error in Switch Prog Mode: " + e.Message);
     }
 }
Esempio n. 5
0
 /*!
  *  Reads the programming mode
  *  of device with individual address "address"
  */
 static void ReadProgMode(ServicePort servicePort)
 {
     try
     {
         Logger.Log(Logger.Level.Information, "Read Prog Mode");
         Logger.Log(Logger.Level.Information, "==============");
         bool isOn = servicePort.ReadProgMode(address);
         Logger.Log(Logger.Level.Information, "Programming Mode: " + (isOn ? "on" : "off"));
     }
     catch (KdriveException e)
     {
         Logger.Log(Logger.Level.Error, "Error in Read Prog Mode: " + e.Message);
     }
 }
Esempio n. 6
0
 /*!
  *      Reads the property value from PID_SERIAL_NUMBER
  *      of device with individual address "address"
  */
 static void PropertyValueRead(ServicePort servicePort)
 {
     try
     {
         Logger.Log(Logger.Level.Information, "Property Value Read");
         Logger.Log(Logger.Level.Information, "===================");
         byte[] serialNumber = servicePort.PropertyValueRead(address, 0, 11, 1, 1);
         Logger.Dump(Logger.Level.Information, "Read Serial Number: ", serialNumber);
     }
     catch (KdriveException e)
     {
         Logger.Log(Logger.Level.Error, "Error in Property Value Read: " + e.Message);
     }
 }
Esempio n. 7
0
 /*!
  *      Writes the property value from PID_PROGMODE
  *      of device with individual address "address"
  */
 static void PropertyValueWrite(ServicePort servicePort)
 {
     try
     {
         Logger.Log(Logger.Level.Information, "Property Value Write");
         Logger.Log(Logger.Level.Information, "===================");
         byte[] data = new byte[1];
         data[0] = 0;
         servicePort.PropertyValueWrite(address, 0, 54, 1, 1, data);
     }
     catch (KdriveException e)
     {
         Logger.Log(Logger.Level.Error, "Error in Property Value Write: " + e.Message);
     }
 }
Esempio n. 8
0
 /*!
  *      Writes the individual address to a device
  *      which are in programming mode.
  */
 static void IndividualAddressProgModeWrite(ServicePort servicePort)
 {
     try
     {
         Logger.Log(Logger.Level.Information, "Individual Address Prog Mode Write");
         Logger.Log(Logger.Level.Information, "================");
         servicePort.IndividualAddressProgModeWrite(0x05F1);
         IndividualAddressProgModeRead(servicePort);
         servicePort.IndividualAddressProgModeWrite(address);
         IndividualAddressProgModeRead(servicePort);
     }
     catch (KdriveException e)
     {
         Logger.Log(Logger.Level.Error, "Error in Individual Address Prog Mode Write: " + e.Message);
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Сохранение настроек в файл конфигурации
        /// </summary>
        public void SaveSettings()
        {
            // создаем объект
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // вносим изменения
            config.AppSettings.Settings["ServicePort"].Value         = ServicePort.ToString();
            config.AppSettings.Settings["LoadLevel"].Value           = LoadLevel.ToString();
            config.AppSettings.Settings["WatchInterval"].Value       = WatchInterval.ToString();
            config.AppSettings.Settings["ApplicationWorkTime"].Value = ApplicationWorkTime.ToString();
            config.AppSettings.Settings["ApplicationPath"].Value     = ApplicationPath;
            config.AppSettings.Settings["IsActive"].Value            = IsActive;
            // сохраняем
            config.Save(ConfigurationSaveMode.Modified);
            // обновялем
            ConfigurationManager.RefreshSection("appSettings");
        }
Esempio n. 10
0
 /*!
  *  Reads the individual addresses of devices
  *      which are in programming mode.
  */
 static void IndividualAddressProgModeRead(ServicePort servicePort)
 {
     try
     {
         Logger.Log(Logger.Level.Information, "Individual Address Prog Mode Read");
         Logger.Log(Logger.Level.Information, "=================================");
         int[] addresses = servicePort.IndividualAddressProgModeRead(500);
         Logger.Log(Logger.Level.Information, "Read " + addresses.Count().ToString() + " Individual Address(es):");
         foreach (int address in addresses)
         {
             string hex = String.Format("0x{0:X04}", address);
             Logger.Log(Logger.Level.Information, hex);
         }
     }
     catch (KdriveException e)
     {
         Logger.Log(Logger.Level.Error, "Error in Individual Address Prog Mode Read: " + e.Message);
     }
 }
Esempio n. 11
0
    public async void Connect()
    {
        if (State == ConnectionState.Connecting || State == ConnectionState.Connected)
        {
            throw new InvalidOperationException("Connection is active");
        }

        State = ConnectionState.Connecting;

        try{
            socket = new StreamSocket();
            socket.Control.KeepAlive                 = true;
            socket.Control.QualityOfService          = SocketQualityOfService.Normal;
            socket.Control.OutboundBufferSizeInBytes = receivingBufferSize;

            Debug.LogFormat("Trying to connect to service {0} {1}", ServiceIPAddress, ServicePort.ToString());

            await socket.ConnectAsync(new HostName(ServiceIPAddress), ServicePort.ToString());

            State = ConnectionState.Connected;
        }
        catch (Exception e)
        {
            Debug.LogFormat("Connecting failed to service {0} {1}, {2}", ServiceIPAddress, ServicePort.ToString(), e.ToString());

            State = ConnectionState.Failed;
            throw e;
        }

        Debug.LogFormat("Connected to service {0} {1}", ServiceIPAddress, ServicePort.ToString());

        // start receiving
        writer = new DataWriter(socket.OutputStream);

        if (tokenSource == null)
        {
            tokenSource = new CancellationTokenSource();
        }

        receivingTask = Task.Factory.StartNew(SocketReceiveHandler, tokenSource.Token);
    }
Esempio n. 12
0
        public Connection(Server server, ServicePort servicePort, Socket socket)
        {
            if (server == null)
                throw new ArgumentNullException("server");
            if(servicePort == null)
                throw new ArgumentNullException("servicePort");
            if (socket == null)
                throw new ArgumentNullException("socket");
            if (!socket.Connected)
                throw new ArgumentException("The socket is not connected.");

            _server = server;
            _servicePort = servicePort;
            _socket = socket;

            _message = new Message(true);
            _sendLock = new object();

            _sendEventArgs = new SocketAsyncEventArgs();
            _sendEventArgs.Completed += SendCallback;

            _remoteAddress = ((IPEndPoint)_socket.RemoteEndPoint).Address.ToString();
            _ipAddress = IPConverter.ToUInt32(_remoteAddress);
        }
Esempio n. 13
0
 public UDPAddress(String hostIP, ServicePort sp)
 {
     HostIP = hostIP;
     Sp = sp;
 }
Esempio n. 14
0
        private async void ServiceDiscovery_Click(object sender, EventArgs e)
        {
            int[] PortRanges = new int[]
            {
                80,  // Only for HTTP
                443, // Only for HTTPS
                5846,
                5847,
                5848,
                5849,
                5850,
                5851,
                5852,
                5853,
                5854,
                5855,
                5856
            };

            string commandString  = string.Empty;
            string responseString = string.Empty;
            string cardServiceURI = string.Empty;

            textBoxCommand.Text    = commandString;
            textBoxResponse.Text   = responseString;
            textBoxCardReader.Text = cardServiceURI;
            textBoxEvent.Text      = string.Empty;

            ServicePort = null;


            foreach (int port in PortRanges)
            {
                try
                {
                    WebSocketState state;
                    using (var socket = new ClientWebSocket())
                    {
                        var cancels = new CancellationTokenSource();
                        cancels.CancelAfter(400);
                        await socket.ConnectAsync(new Uri($"{textBoxServiceURI.Text}:{port}/xfs4iot/v1.0"), cancels.Token);

                        state = socket.State;
                    }

                    if (state == WebSocketState.Open)
                    {
                        ServicePort = port;
                        var Discovery = new XFS4IoTClient.ClientConnection(new Uri($"{textBoxServiceURI.Text}:{ServicePort}/xfs4iot/v1.0"));

                        try
                        {
                            await Discovery.ConnectAsync();
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        var getServiceCommand = new GetServiceCommand(Guid.NewGuid().ToString(), new GetServiceCommand.PayloadData(CommandTimeout));
                        commandString = getServiceCommand.Serialise();
                        await Discovery.SendCommandAsync(getServiceCommand);

                        object cmdResponse = await Discovery.ReceiveMessageAsync();

                        if (cmdResponse is GetServiceCompletion response)
                        {
                            responseString = response.Serialise();
                            var service =
                                (from ep in response.Payload.Services
                                 where ep.ServiceUri.Contains("CardReader")
                                 select ep
                                ).FirstOrDefault()
                                ?.ServiceUri;

                            if (!string.IsNullOrEmpty(service))
                            {
                                cardServiceURI = service;
                            }
                        }
                        break;
                    }
                }
                catch (WebSocketException)
                { }
                catch (System.Net.HttpListenerException)
                { }
                catch (TaskCanceledException)
                { }
            }

            if (ServicePort is null)
            {
                textBoxPort.Text = "";
                MessageBox.Show("Failed on finding services.");
            }
            else
            {
                textBoxPort.Text = ServicePort.ToString();
            }

            textBoxCommand.Text    = commandString;
            textBoxResponse.Text   = responseString;
            textBoxCardReader.Text = cardServiceURI;
        }
Esempio n. 15
0
        public string Upload(int taskId, string fileName, int profileId, int userId, string hdNumber)
        {
            //no need to find and call com server, client should already be directly communicating with the correct imaging server
            var guid = ConfigurationManager.AppSettings["ComServerUniqueId"];

            _thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (_thisComServer == null)
            {
                log.Error($"Com Server With Guid {guid} Not Found");
                return("0");
            }

            var appPath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "private", "apps");

            var task = new ServiceActiveImagingTask().GetTask(taskId);

            if (task == null)
            {
                return("0");
            }

            var imageProfile = new ServiceImageProfile().ReadProfile(profileId);

            var uploadPort = new ServicePort().GetNextPort(task.ComServerId);

            var path = _thisComServer.LocalStoragePath;


            try
            {
                var dir = Path.Combine(path, "images", imageProfile.Image.Name, $"hd{ hdNumber}");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
            catch (Exception ex)
            {
                log.Error("Could Not Create Directory");
                log.Error(ex.Message);
                return("0");
            }

            path = Path.Combine(path, "images", imageProfile.Image.Name, $"hd{hdNumber}", fileName);
            string arguments    = " /c \"";
            var    receiverPath = Path.Combine(appPath, "udp-receiver.exe");

            arguments += $"{receiverPath}\" --portbase {uploadPort}";
            arguments += $" --interface {_thisComServer.ImagingIp} --file {path}";

            var pid = StartReceiver(arguments, imageProfile.Image.Name);
            //use multicast session even though it's not a multicast, uploads still use udpcast
            var activeMulticast = new EntityActiveMulticastSession();

            if (pid != 0)
            {
                activeMulticast.ImageProfileId = imageProfile.Id;
                activeMulticast.Name           = imageProfile.Image.Name;
                activeMulticast.Pid            = pid;
                activeMulticast.Port           = uploadPort;
                activeMulticast.ComServerId    = _thisComServer.Id;
                activeMulticast.UserId         = userId;
                activeMulticast.UploadTaskId   = task.Id;

                var result = new ServiceActiveMulticastSession().AddActiveMulticastSession(activeMulticast);
                if (result)
                {
                    return(uploadPort.ToString());
                }
            }
            return("0");
        }
Esempio n. 16
0
        protected InjectorHostBase(bool forceCanInject = false)
        {
            _forceCanInject = forceCanInject;

            var dtoAssembly = typeof(NewAssemblyMessage).GetTypeInfo().Assembly;

            _messageHub.AdditionalTypeResolutionAssemblies.Add(dtoAssembly);

            // set up the discovery responder
            _servicePublisher = new InjectorServiceDefinition(async() =>
            {
                // get the current interfaces
                var ifs    = await CommsInterface.GetAllInterfacesAsync();
                var usable = ifs.Where(iface => iface.IsUsable && !iface.IsLoopback)
                             .Where(iface => iface.ConnectionStatus == CommsInterfaceStatus.Connected).ToList();

                // if none (how :O), we won't respond. how could we event
                if (!usable.Any())
                {
                    return(null);
                }

                return(new InjectorHostServiceResponse
                {
                    ServiceGuid = ServiceGuid,
                    ServiceName = GetType().FullName,
                    Port = ServicePort,
                    NumConnectedClients = ConnectedClients.Count,
                    RunningAt = ifs.Select(iface => String.Join(":", iface.IpAddress, ServicePort.ToString())).ToList()
                });
            }).CreateServicePublisher();
        }
Esempio n. 17
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;
            }
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            AccessPort  accessPort  = null;
            ServicePort servicePort = null;

            try
            {
                Logger.SetConsoleChannel();
                Logger.SetLevels(Logger.Level.Information);

                // USB (first available USB port)
                accessPort = new AccessPort();
                accessPort.EnumerateUsb();
                accessPort.OpenUsb(0);

                servicePort = new ServicePort(accessPort);

                /*
                 *      Set the device services to connection-oriented or
                 *      connection-less (depending on the value of connection_oriented)
                 */
                servicePort.SetConnectionOriented(isConnectionOriented);

                // read property value : serial number
                PropertyValueRead(servicePort);

                // write property value : programming mode
                PropertyValueWrite(servicePort);

                // switch the programming mode on
                SwitchProgMode(servicePort, true);

                // read the programming mode
                ReadProgMode(servicePort);

                // read the individual address of devices which are in programming mode
                IndividualAddressProgModeRead(servicePort);

                // write the individual address of devices which are in programming mode
                IndividualAddressProgModeWrite(servicePort);

                // switch the programming mode off
                SwitchProgMode(servicePort, false);

                // read the programming mode
                ReadProgMode(servicePort);

                // Close the service port
                servicePort.Close();

                // Close the service port
                accessPort.Close();
            }
            catch (kdrive.KdriveException exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                if (servicePort != null)
                {
                    servicePort.Dispose();
                }
                if (accessPort != null)
                {
                    accessPort.Dispose();
                }
                Logger.Shutdown();
            }
        }