예제 #1
0
        public async Task <IActionResult> RawRequest(
            string id,
            [FromBody] RequestFrame requestFrame,
            [FromQuery] string?taskId,
            [FromQuery] int asyncTimeout = PrintJob.DefaultTimeout)
        {
            if (!context.IsReady)
            {
                return(StatusCode(StatusCodes.Status405MethodNotAllowed));
            }
            if (context.Printers.TryGetValue(id, out IFiscalPrinter? printer))
            {
                var result = await context.RunAsync(
                    new PrintJob
                {
                    Printer      = printer,
                    Action       = PrintJobAction.RawRequest,
                    Document     = requestFrame,
                    AsyncTimeout = asyncTimeout,
                    TaskId       = taskId
                });

                return(Ok(result));
            }
            return(NotFound());
        }
예제 #2
0
        /// <summary>
        /// 获取截屏。
        /// </summary>
        /// <exception cref="Exception"></exception>
        /// <returns></returns>
        public async Task <byte[]> StartAsync()
        {
            if (!Started)
            {
                Started = true;

                //发送请求
                RequestFrame frame = new RequestFrame();
                base.GuidFilter = frame.Guid;
                await Send(frame).ConfigureAwait(false);

                //等待结果
                switch (await base.Answers.WaitAsync(Common.Configs.FrameTimeout).ConfigureAwait(false))
                {
                case AnswerFrame answerFrame: return(answerFrame.BytesJpeg);

                case ErrorFrame errorFrame: throw new RemoteErrorException(errorFrame);

                default: throw new InvalidDataException();
                }
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
예제 #3
0
        /// <summary>
        /// 远程启动命令行。
        /// </summary>
        /// <exception cref="Exception"></exception>
        /// <returns></returns>
        public async Task StartAsync(string filename, string arguments, bool hide, bool redirectInput, bool redirectOutput, bool redirectError, DateTime startUtc, DateTime stopUtc)
        {
            if (!Started)
            {
                Started = true;

                RequestFrame frame = new RequestFrame()
                {
                    FileName       = filename,
                    Arguments      = arguments,
                    Hide           = hide,
                    RedirectInput  = redirectInput,
                    RedirectOutput = redirectOutput,
                    RedirectError  = redirectError,
                    StartUtc       = startUtc,
                    StopUtc        = stopUtc,
                };
                base.GuidFilter = frame.Guid;

                HandleAnswers();
                await Send(frame).ConfigureAwait(false);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
예제 #4
0
        public override DeviceStatusWithRawResponse RawRequest(RequestFrame requestFrame)
        {
            if (requestFrame.RawRequest.Length < 2)
            {
                var deviceStatus = new DeviceStatus();
                deviceStatus.AddError("E401", "Request length must be at least 2 characters");
                return(new DeviceStatusWithRawResponse(deviceStatus));
            }
            var(rawResponse, status) = Request(requestFrame.RawRequest);
            var deviceStatusWithRawResponse = new DeviceStatusWithRawResponse(status);

            deviceStatusWithRawResponse.RawResponse = rawResponse;
            return(deviceStatusWithRawResponse);
        }
예제 #5
0
        /// <summary>
        /// 远端从<paramref name="url"/>下载数据并保存到文件<paramref name="file"/>中。
        /// </summary>
        /// <exception cref="Exception"></exception>
        /// <returns></returns>
        public async Task StartAsync(string url, string file)
        {
            if (!Started)
            {
                Started = true;

                //发送请求
                RequestFrame frame = new RequestFrame()
                {
                    Url            = url,
                    File           = file,
                    AnswerInterval = 500,
                };
                base.GuidFilter = frame.Guid;
                await Send(frame).ConfigureAwait(false);

                //接收数据
                while (TransferedSize != Size)
                {
                    switch (await base.Answers.WaitAsync(Common.Configs.FrameTimeout).ConfigureAwait(false))
                    {
                    case AnswerFrame answerFrame:
                    {
                        if (Size != -1 && Size != answerFrame.Size)
                        {
                            throw new InvalidDataException("传输大小在中途更变");
                        }
                        else
                        {
                            Size = answerFrame.Size;
                        }

                        TransferedSize = answerFrame.Offset;
                        Recorder.Record(TransferedSize);
                    }
                    break;

                    case ErrorFrame errorFrame: throw new RemoteErrorException(errorFrame);

                    default: throw new InvalidDataException();
                    }
                }

                Finished = true;
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
        public override DeviceStatusWithRawResponse RawRequest(RequestFrame requestFrame)
        {
            if (requestFrame.RawRequest.Length == 0)
            {
                var deviceStatus = new DeviceStatus();
                deviceStatus.AddError("E401", "Request length must be at least 1 character");
                return(new DeviceStatusWithRawResponse(deviceStatus));
            }
            var cmd  = PrinterEncoding.GetBytes(requestFrame.RawRequest.Substring(0, 1))[0];
            var data = requestFrame.RawRequest.Substring(1);

            var(rawResponse, status) = Request(cmd, data);
            var deviceStatusWithRawResponse = new DeviceStatusWithRawResponse(status);

            deviceStatusWithRawResponse.RawResponse = rawResponse;
            return(deviceStatusWithRawResponse);
        }
예제 #7
0
        protected async Task <AnswerFrame> GatherInformation(RequestFrame req)
        {
            AnswerFrame frame = new AnswerFrame(req.Guid);

            //Version
            frame.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString() + "C" + (Common.Configs.Debug ? " DEBUG" : "");

            //GPU
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var lines = await Utils.ExecuteResultsAsync("wmic", "", new string[] { "path Win32_VideoController get Name", "exit" }, 1000).ConfigureAwait(false);

                if (lines != null && lines.Count > 2)
                {
                    for (int i = 2; i < lines.Count - 1; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(lines[i]))
                        {
                            frame.Gpus.Add(lines[i]);
                        }
                    }
                }
                else
                {
                    frame.Gpus.Add("None");
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                //TODO
                frame.Gpus.Add("Unsupported");
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                //TODO
                frame.Gpus.Add("Unsupported");
            }
            else
            {
                //TODO
                frame.Gpus.Add("Unsupported");
            }

            //CPU
            string cpu = "Unsupported.";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var lines = await Utils.ExecuteResultsAsync("wmic", "", new string[] { "cpu get Name", "exit" }, 1000).ConfigureAwait(false);

                if (lines != null && lines.Count > 2)
                {
                    cpu = lines[2];
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                string cpu0 = await Utils.MatchFileContentAsync("/proc/cpuinfo", new Regex("^model name\\s*:\\s*(.+?)$", RegexOptions.Compiled | RegexOptions.Multiline));

                if (!string.IsNullOrEmpty(cpu0))
                {
                    cpu = cpu0;
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                //TODO
            }

            for (int i = 0; i < Environment.ProcessorCount; i++)
            {
                frame.Cpus.Add(cpu);
            }

            //主机名
            frame.ComputerName = Environment.MachineName;

            //物理内存
            frame.Memory = 0;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var lines = await Utils.ExecuteResultsAsync("wmic", "", new string[] { "memorychip get Capacity", "exit" }, 1000).ConfigureAwait(false);

                if (lines != null && lines.Count > 2)
                {
                    for (int i = 2; i < lines.Count - 1; i++)
                    {
                        ulong memory;
                        if (ulong.TryParse(lines[i], out memory))
                        {
                            frame.Memory += memory;
                        }
                    }
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                string mem = await Utils.MatchFileContentAsync("/proc/meminfo", new Regex("^MemTotal\\s*:\\s*(.+)$", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase));

                if (!string.IsNullOrEmpty(mem))
                {
                    mem = mem.TrimEnd();
                    if (mem.EndsWith("KB", StringComparison.CurrentCultureIgnoreCase))
                    {
                        frame.Memory = ulong.Parse(mem.Substring(0, mem.Length - 2)) * 1024;
                    }
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                //TODO
            }

            //操作系统
            frame.Os = RuntimeInformation.OSDescription;

            //标识符
            try
            {
                using (FileStream fs = new FileStream("id.bin", FileMode.OpenOrCreate))
                {
                    byte[] value = new byte[16];
                    int    count = fs.Read(value, 0, 16);
                    if (count != 16)
                    {
                        value = Guid.NewGuid().ToByteArray();
                        fs.SetLength(16);
                        fs.Position = 0;
                        fs.Write(value);
                    }

                    frame.Identifier = new Guid(value);
                }
            }
            catch
            {
                frame.Identifier = Guid.NewGuid();
            }

            return(frame);
        }
예제 #8
0
 private async void SendStatus(RequestFrame frame, long len, long position)
 {
     await SendFrame(new AnswerFrame(frame.Guid) { Offset = position, Size = len }).ConfigureAwait(false);
 }
예제 #9
0
        protected AnswerFrame GatherInformation(RequestFrame req)
        {
            AnswerFrame frame = new AnswerFrame(req.Guid);

            //Version
            frame.Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + (Common.Configs.Debug ? " DEBUG" : "");

            //GPU
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_VideoController"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    string gpu = obj.GetPropertyValue("Caption") as string;
                    frame.Gpus.Add(gpu);
                }
            }

            //CPU
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name, NumberOfCores FROM Win32_Processor"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    string cpu   = obj.GetPropertyValue("Name") as string;
                    uint   cores = (uint)obj.GetPropertyValue("NumberOfCores");
                    for (int i = 0; i < cores; i++)
                    {
                        frame.Cpus.Add(cpu);
                    }
                }
            }

            //物理内存
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name, TotalPhysicalMemory FROM Win32_ComputerSystem"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    frame.ComputerName = obj.GetPropertyValue("Name") as string;
                    frame.Memory       = (ulong)obj.GetPropertyValue("TotalPhysicalMemory");
                }
            }

            //操作系统
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_OperatingSystem"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    frame.Os = obj.GetPropertyValue("Name") as string;
                    frame.Os = frame.Os.Split('|')[0];
                }
            }

            //标识符
            if (Common.Configs.Debug)
            {
                frame.Identifier = Guid.NewGuid();
            }
            else
            {
                using (RegistryKey key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\" + Assembly.GetExecutingAssembly().GetName().Name))
                {
                    byte[] value = key.GetValue("Identifier") as byte[];
                    if (value == null || value.Length != 16)
                    {
                        value = Guid.NewGuid().ToByteArray();
                        key.SetValue("Identifier", value);
                    }

                    frame.Identifier = new Guid(value);
                }
            }

            return(frame);
        }
예제 #10
0
 public abstract DeviceStatusWithRawResponse RawRequest(RequestFrame requestFrame);