コード例 #1
0
ファイル: silderbar.xaml.cs プロジェクト: JamborYao/UwpStart
        public async void GenerateCode2()
        {
            byte[] blackPixel = new byte[] { 0, 0, 0, 255 };
            byte[] whitePixel = new byte[] { 255, 255, 255, 255 };

            Random random = new Random();
            Stopwatch watch = new Stopwatch();

            var buffer = new Windows.Storage.Streams.Buffer(40000);
            using (var stream = buffer.AsStream())
            {
                watch.Start();
                await Task.Run(() =>
                {
                    for (var i = 0; i < 10000; i++)
                    {
                        if (random.NextDouble() >= 0.5)
                            stream.Write(blackPixel, 0, 4);
                        else
                            stream.Write(whitePixel, 0, 4);
                    }
                });
                watch.Stop();
                await new MessageDialog(watch.ElapsedMilliseconds.ToString()).ShowAsync();

            }
        }
コード例 #2
0
        private async System.Threading.Tasks.Task FindAndReadFile()
        {
            var filePicker = new FileOpenPicker();
            filePicker.FileTypeFilter.Add(WPL);
            var file = await filePicker.PickSingleFileAsync();
            if (file != null)
            {
                tbxFileName.Text = file.Name;
                using (var fread = await file.OpenReadAsync())
                {
                    var fileSize = (uint)fread.Size;
                    var buffer = new Windows.Storage.Streams.Buffer(fileSize);
                    var results = await fread.ReadAsync(buffer, fileSize, Windows.Storage.Streams.InputStreamOptions.None);

                    var data = System.Text.Encoding.UTF8.GetString(results.ToArray());
                    tbxOriginalPlayList.Text = data;
                }
            }
        }
コード例 #3
0
ファイル: Camera.cs プロジェクト: STUDIO-Artaban/JSunchained
        public void Start(byte device, short width, short height)
        {
            Log.WriteV(this.GetType().Name, String.Format(" - d:{0};w:{1};h:{2}", (int)device, width, height));

            CoreDispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                if (!await Initialize(device, width, height))
                {
                    unchainedCamera(null); // Failed to start camera
                    return;
                }

                // Set the preview source in the UI and mirror it if necessary
                _captureElement.Source        = _mediaCapture;
                _captureElement.FlowDirection = FlowDirection.LeftToRight;

                // Start the preview
                await _mediaCapture.StartPreviewAsync();

                _running     = true;
                _previewTask = new Task(async() =>
                {
                    Windows.Storage.Streams.Buffer data = new Windows.Storage.Streams.Buffer((uint)(width * height * 4));
                    while (_running)
                    {
                        // Create the video frame to request a SoftwareBitmap preview frame
                        var videoFrame = new VideoFrame(BitmapPixelFormat.Rgba8, (int)width, (int)height);

                        using (var currentFrame = await _mediaCapture.GetPreviewFrameAsync(videoFrame))
                        {
                            // Collect the resulting frame
                            currentFrame.SoftwareBitmap.CopyToBuffer(data);
                            MemoryStream memory = new MemoryStream();
                            data.AsStream().CopyTo(memory);

                            unchainedCamera(memory.ToArray());
                        }
                    }
                }, TaskCreationOptions.None);
                _previewTask.Start();
            });
        }
コード例 #4
0
        private async System.Threading.Tasks.Task FindAndReadFile()
        {
            var filePicker = new FileOpenPicker();

            filePicker.FileTypeFilter.Add(WPL);
            var file = await filePicker.PickSingleFileAsync();

            if (file != null)
            {
                tbxFileName.Text = file.Name;
                using (var fread = await file.OpenReadAsync())
                {
                    var fileSize = (uint)fread.Size;
                    var buffer   = new Windows.Storage.Streams.Buffer(fileSize);
                    var results  = await fread.ReadAsync(buffer, fileSize, Windows.Storage.Streams.InputStreamOptions.None);

                    var data = System.Text.Encoding.UTF8.GetString(results.ToArray());
                    tbxOriginalPlayList.Text = data;
                }
            }
        }
コード例 #5
0
        public async Task <byte[]> TakePhotoAsync()
        {
            CameraCaptureUI captureUI = new CameraCaptureUI();

            captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;

            StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

            if (photo == null)
            {
                return(null);
            }

            using (var stream = await photo.OpenReadAsync())
            {
                var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);
                var data   = await stream.ReadAsync(buffer, (uint)stream.Size, Windows.Storage.Streams.InputStreamOptions.None);

                return(data.ToArray());
            }
        }
コード例 #6
0
    private async Task Receive()
    {
        while (true)
        {
            IBuffer inbuffer = new Windows.Storage.Streams.Buffer(4);
            await _socket.InputStream.ReadAsync(inbuffer, 4, InputStreamOptions.None);

            int command = BitConverter.ToInt32(inbuffer.ToArray(), 0);
            //The inbuffer at this point contains: "\u0001\0\0\0", and the BitConverter resolves this to 1

            inbuffer = new Windows.Storage.Streams.Buffer(4);
            await _socket.InputStream.ReadAsync(inbuffer, 4, InputStreamOptions.None);

            int length = BitConverter.ToInt32(inbuffer.ToArray(), 0);
            //The inbuffer now contains: "2\0\0\0", and the BitConverter resolves this to "50"

            inbuffer = new Windows.Storage.Streams.Buffer((uint)length);
            await _socket.InputStream.ReadAsync(inbuffer, (uint)length, InputStreamOptions.Partial);

            string path = Encoding.UTF8.GetString(inbuffer.ToArray());
        }
    }
コード例 #7
0
            /// <summary>
            /// GET_LINE_CODING CDC request.
            /// </summary>
            /// <param name="index">Interface index.</param>
            /// <returns>
            /// The result of Task contains a buffer of Line Coding structure.
            /// </returns>
            private Task <Windows.Storage.Streams.IBuffer> GetLineCoding(
                uint index
                )
            {
                return(Task.Run(async() =>
                {
                    var buffer = new Windows.Storage.Streams.Buffer(Constants.ExpectedResultGetLineCoding);
                    buffer.Length = Constants.ExpectedResultGetLineCoding;

                    var requestType = new UsbControlRequestType();
                    requestType.AsByte = RequestType.Get;

                    var packet = new UsbSetupPacket();
                    packet.RequestType = requestType;
                    packet.Request = RequestCode.GetLineCoding;
                    packet.Value = 0;
                    packet.Length = buffer.Length;
                    packet.Index = index;

                    return await this.device.SendControlInTransferAsync(packet, buffer);
                }));
            }
コード例 #8
0
ファイル: RestClient.cs プロジェクト: obfan/FanfouUWP
        public async Task <T> PostRequestWithFile <T>(string url, Parameters parameters, string filePara, StorageFile file)
            where T : Item
        {
            using (var client = new HttpClient(protocolFilter))
            {
                string urlStr = baseUrl + "/" + url;

                string oauth = generateOAuthHeader(new Parameters(), url, "POST");
                client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("OAuth", oauth);
                client.DefaultRequestHeaders.AcceptEncoding.Add(new HttpContentCodingWithQualityHeaderValue("GZip"));
                var buff    = new Buffer(1024);
                var content = new HttpMultipartFormDataContent();
                foreach (var item in parameters.Items)
                {
                    var c = new HttpStringContent(item.Value);
                    content.Add(c, item.Key);
                }
                Stream s = await file.OpenStreamForReadAsync();

                var f = new HttpStreamContent(s.AsInputStream());
                f.Headers.ContentType = new HttpMediaTypeHeaderValue(file.ContentType);
                content.Add(f, filePara, file.Name);
                Loading.isLoading = true;
                using (HttpResponseMessage response = await client.PostAsync(new Uri(urlStr), content))
                {
                    string result = await response.Content.ReadAsStringAsync();

                    response.EnsureSuccessStatusCode();
                    var ds = new DataContractJsonSerializer(typeof(T));
                    using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(result)))
                    {
                        var obj = ds.ReadObject(ms) as T;
                        Loading.isLoading = false;
                        return(obj);
                    }
                }
            }
        }
コード例 #9
0
        private void ReadByteOneByOne()
        {
            var dispatcher = this.Dispatcher;
            var buffer     = new Windows.Storage.Streams.Buffer(1);

            buffer.Length = 1;

            System.Threading.Tasks.Task.Run(async() =>
            {
                int count = 0;
                try
                {
                    count = await this.Read(buffer, -1);
                }
                catch (System.OperationCanceledException)
                {
                    return; // StopWatching seems clicked.
                }
                finally
                {
                    this.cancelTokenSrcOpRead = null;
                }

                if (count > 0)
                {
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
                    {
                        var isAscii = this.radioButtonAscii.IsChecked.Value == true;
                        var temp    = this.textBoxReadBulkInLogger.Text;
                        temp       += isAscii ? Util.AsciiBufferToAsciiString(buffer) : Util.BinaryBufferToBinaryString(buffer);
                        this.textBoxReadBulkInLogger.Text = temp;
                    }));
                }

                this.ReadByteOneByOne();
            });
        }
コード例 #10
0
ファイル: MainPage.xaml.cs プロジェクト: PiyushMichael/khukri
        async void Grid_Drop(Object sender, DragEventArgs e)
        {
            if (e.DataView.Contains(StandardDataFormats.StorageItems))
            {
                var items = await e.DataView.GetStorageItemsAsync();

                if (items.Count > 0)
                {
                    StorageFile file = items[0] as StorageFile;
                    if (file != null)
                    {
                        if (items[0].Path.Contains(".csv"))
                        {
                            var x = await file.OpenSequentialReadAsync();

                            var length = (uint)1024 * 64;
                            var str    = new Windows.Storage.Streams.Buffer(length);
                            await x.ReadAsync(str, length, Windows.Storage.Streams.InputStreamOptions.ReadAhead);

                            var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(str);
                            try {
                                var output = dataReader.ReadString(str.Length);
                                GenerateKeywords(output, parsedResult);
                            } catch (Exception) {
                                var messageDialog = new Windows.UI.Popups.MessageDialog("Invalid csv file. Save file as CSV (MS-DOS) (*.csv) format.");
                                await messageDialog.ShowAsync();
                            }
                        }
                        else
                        {
                            var messageDialog = new Windows.UI.Popups.MessageDialog("Invalid file type. Only drop .csv files.");
                            await messageDialog.ShowAsync();
                        }
                    }
                }
            }
        }
コード例 #11
0
ファイル: Scenario2_Read.xaml.cs プロジェクト: mbin/Win81App
        private void ReadByteOneByOne()
        {
            var dispatcher = this.Dispatcher;
            var buffer = new Windows.Storage.Streams.Buffer(1);
            buffer.Length = 1;

            System.Threading.Tasks.Task.Run(async () =>
            {
                int count = 0;
                try
                {
                    count = await this.Read(buffer, -1);
                }
                catch (System.OperationCanceledException)
                {
                    return; // StopWatching seems clicked.
                }
                finally
                {
                    this.cancelTokenSrcOpRead = null;
                }

                if (count > 0)
                {
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
                    {
                        var isAscii = this.radioButtonAscii.IsChecked.Value == true;
                        var temp = this.textBoxReadBulkInLogger.Text;
                        temp += isAscii ? Util.AsciiBufferToAsciiString(buffer) : Util.BinaryBufferToBinaryString(buffer);
                        this.textBoxReadBulkInLogger.Text = temp;
                    }));
                }

                this.ReadByteOneByOne();
            });
        }
コード例 #12
0
ファイル: Scenario2_Read.xaml.cs プロジェクト: mbin/Win81App
        private void buttonReadBulkIn_Click(object sender, RoutedEventArgs e)
        {
            if (buttonReadBulkIn.Content.ToString() == "Read")
            {
                uint bytesToRead = uint.Parse(textBoxBytesToRead.Text);
                if (bytesToRead > 0)
                {
                    // UI status.
                    buttonReadBulkIn.Content = "Stop Read";
                    buttonWatchBulkIn.IsEnabled = false;
                    SDKTemplate.MainPage.Current.NotifyUser("Reading", SDKTemplate.NotifyType.StatusMessage);

                    var buffer = new Windows.Storage.Streams.Buffer(bytesToRead);
                    buffer.Length = bytesToRead;
                    int timeout = int.Parse(textBoxReadTimeout.Text);

                    var dispatcher = this.Dispatcher;
                    Action readAction = async () =>
                    {
                        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () =>
                        {
                            int count = 0;
                            try
                            {
                                count = await this.Read(buffer, timeout);
                            }
                            catch (System.OperationCanceledException)
                            {
                                // cancel.
                                SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                                return;
                            }
                            catch (System.Exception exception)
                            {
                                if (exception.HResult == -2146233088)
                                {
                                    // Device removed.
                                    return;
                                }
                                else
                                {
                                    throw;
                                }
                            }
                            finally
                            {
                                this.cancelTokenSrcOpRead = null;
                            }

                            this.buttonReadBulkIn.Content = "Read";
                            this.buttonWatchBulkIn.IsEnabled = true;

                            if (count < bytesToRead)
                            {
                                // This would be timeout.
                                SDKTemplate.MainPage.Current.NotifyUser("Timeout: read " + count.ToString() + " byte(s)", SDKTemplate.NotifyType.ErrorMessage);
                            }
                            else
                            {
                                SDKTemplate.MainPage.Current.NotifyUser("Completed", SDKTemplate.NotifyType.StatusMessage);
                            }

                            if (count > 0)
                            {
                                var isAscii = this.radioButtonAscii.IsChecked.Value == true;
                                var temp = this.textBoxReadBulkInLogger.Text;
                                temp += isAscii ? Util.AsciiBufferToAsciiString(buffer) : Util.BinaryBufferToBinaryString(buffer);
                                this.textBoxReadBulkInLogger.Text = temp;
                            }
                        }));
                    };
                    readAction.Invoke();
                }
            }
            else
            {
                this.buttonStopWatching_Click(this, null);
                this.buttonReadBulkIn.Content = "Read";
            }
        }
コード例 #13
0
        async Task Init()
        {
            var gpu = new Gpu();

#if DEBUG
            gpu.EnableD3D12DebugLayer();
#endif
            var adapter = await gpu.RequestAdapterAsync();

            Device = await adapter.RequestDeviceAsync();

            TimeBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type           = GpuBufferBindingType.Uniform,
                        MinBindingSize = sizeof(float)
                    }
                }
            }));
            BindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type           = GpuBufferBindingType.Uniform,
                        MinBindingSize = 20
                    }
                }
            }));
            DynamicBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type             = GpuBufferBindingType.Uniform,
                        HasDynamicOffset = true,
                        MinBindingSize   = 20
                    }
                }
            }));

            var pipelineLayout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
            {
                BindGroupLayouts = new GpuBindGroupLayout[] { TimeBindGroupLayout, BindGroupLayout }
            });
            var dynamicPipelineLayout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
            {
                BindGroupLayouts = new GpuBindGroupLayout[] { TimeBindGroupLayout, DynamicBindGroupLayout }
            });

            string shaderCode;
            using (var shaderFileStream = typeof(MainPage).Assembly.GetManifestResourceStream("Animometer.shader.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    shaderCode = shaderStreamReader.ReadToEnd();
                }
            var shader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));

            var pipelineDescriptor = new GpuRenderPipelineDescriptor(new GpuVertexState(shader, "VSMain")
            {
                VertexBuffers = new GpuVertexBufferLayout[]
                {
                    new GpuVertexBufferLayout(2 * Vec4Size, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 0,
                            Offset         = 0,
                            Format         = GpuVertexFormat.Float4
                        },
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 1,
                            Offset         = Vec4Size,
                            Format         = GpuVertexFormat.Float4
                        }
                    })
                    {
                        StepMode = GpuInputStepMode.Vertex
                    }
                }
            })
            {
                Fragment = new GpuFragmentState(shader, "PSMain", new GpuColorTargetState[] { new GpuColorTargetState()
                                                                                              {
                                                                                                  Format = SwapChainFormat
                                                                                              } }),
                Primitive = new GpuPrimitiveState()
                {
                    Topology  = GpuPrimitiveTopology.TriangleList,
                    FrontFace = GpuFrontFace.Ccw,
                    CullMode  = GpuCullMode.None
                }
            };
            pipelineDescriptor.Layout = pipelineLayout;
            Pipeline = Device.CreateRenderPipeline(pipelineDescriptor);
            pipelineDescriptor.Layout = dynamicPipelineLayout;
            DynamicPipeline           = Device.CreateRenderPipeline(pipelineDescriptor);
            VertexBuffer = Device.CreateBuffer(new GpuBufferDescriptor(2 * 3 * Vec4Size, GpuBufferUsageFlags.Vertex)
            {
                MappedAtCreation = true
            });
            float[] vertexData = new float[]
            {
                0, 0.1f, 0, 1, 1, 0, 0, 1,
                -0.1f, -0.1f, 0, 1, 0, 1, 0, 1,
                0.1f, -0.1f, 0, 1, 0, 0, 1, 1
            };
            Windows.Storage.Streams.Buffer verticeCpuBuffer = new Windows.Storage.Streams.Buffer((uint)Buffer.ByteLength(vertexData));
            verticeCpuBuffer.Length = verticeCpuBuffer.Capacity;
            using (var verticeCpuStream = verticeCpuBuffer.AsStream())
            {
                byte[] vertexBufferBytes = new byte[Buffer.ByteLength(vertexData)];
                Buffer.BlockCopy(vertexData, 0, vertexBufferBytes, 0, Buffer.ByteLength(vertexData));
                await verticeCpuStream.WriteAsync(vertexBufferBytes, 0, Buffer.ByteLength(vertexData));
            }
            verticeCpuBuffer.CopyTo(VertexBuffer.GetMappedRange());
            VertexBuffer.Unmap();
        }
コード例 #14
0
            public Configure(GpuDevice device, Settings settings, GpuBindGroupLayout bindGroupLayout, GpuBindGroupLayout dynamicBindGroupLayout, GpuBindGroupLayout timeBindGroupLayout, GpuRenderPipeline pipeline, GpuRenderPipeline dynamicPipeline, GpuBuffer vertexBuffer, GpuTextureFormat swapChainFormat)
            {
                Device          = device;
                Settings        = settings;
                Pipeline        = pipeline;
                DynamicPipeline = dynamicPipeline;
                VertexBuffer    = vertexBuffer;
                SwapChainFormat = swapChainFormat;

                UniformBuffer = Device.CreateBuffer(new GpuBufferDescriptor(Settings.NumTriangles * AlignedUniformBytes + sizeof(float), GpuBufferUsageFlags.Uniform | GpuBufferUsageFlags.CopyDst));
                var uniformCpuBuffer = new Windows.Storage.Streams.Buffer(Settings.NumTriangles * AlignedUniformBytes)
                {
                    Length = Settings.NumTriangles * AlignedUniformBytes
                };

                using (var uniformCpuStream = uniformCpuBuffer.AsStream())
                    using (var uniformCpuWriter = new BinaryWriter(uniformCpuStream))
                    {
                        var rand = new Random();
                        for (var i = 0; i < Settings.NumTriangles; ++i)
                        {
                            uniformCpuWriter.Seek((int)(i * AlignedUniformBytes), SeekOrigin.Begin);
                            float scale = (float)(rand.NextDouble() * 0.2 + 0.2);
                            //scale = 5;
                            float offsetX      = (float)(0.9 * 2 * (rand.NextDouble() - 0.5));
                            float offsetY      = (float)(0.9 * 2 * (rand.NextDouble() - 0.5));
                            float scalar       = (float)(rand.NextDouble() * 1.5 + 0.5);
                            float scalarOffset = (float)(rand.NextDouble() * 10);
                            uniformCpuWriter.Write(scale);        //Scale
                            uniformCpuWriter.Write(offsetX);      //offsetX
                            uniformCpuWriter.Write(offsetY);      //offsetY
                            uniformCpuWriter.Write(scalar);       //scalar
                            uniformCpuWriter.Write(scalarOffset); //scalar offset
                        }
                    }
                BindGroups = new GpuBindGroup[Settings.NumTriangles];
                for (var i = 0; i < Settings.NumTriangles; ++i)
                {
                    BindGroups[i] = Device.CreateBindGroup(new GpuBindGroupDescriptor(bindGroupLayout, new GpuBindGroupEntry[]
                    {
                        new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, 6 * sizeof(float))
                        {
                            Offset = (UInt64)(i * AlignedUniformBytes)
                        })
                    }));
                }
                DynamicBindGroup = Device.CreateBindGroup(new GpuBindGroupDescriptor(dynamicBindGroupLayout, new GpuBindGroupEntry[]
                {
                    new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, 6 * sizeof(float)))
                }));


                TimeBindGroup = Device.CreateBindGroup(new GpuBindGroupDescriptor(timeBindGroupLayout, new GpuBindGroupEntry[]
                {
                    new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, sizeof(float))
                    {
                        Offset = TimeOffset
                    })
                }));
                Device.DefaultQueue.WriteBuffer(UniformBuffer, 0, uniformCpuBuffer);
                var renderBundleEncoder = Device.CreateRenderBundleEncoder(new GpuRenderBundleEncoderDescriptor(new GpuTextureFormat[] { SwapChainFormat }));

                RecordRenderPass(renderBundleEncoder);
                RenderBundle         = renderBundleEncoder.Finish();
                UniformTimeCpuBuffer = new Windows.Storage.Streams.Buffer(sizeof(float))
                {
                    Length = sizeof(float)
                };
            }
コード例 #15
0
        async Task Init()
        {
            var adapter = await Gpu.RequestAdapterAsync();

            Device = await adapter.RequestDeviceAsync();

            GpuShaderModule computeShader;

            using (var shaderFileStream = typeof(MainWindow).Assembly.GetManifestResourceStream("ComputeBoidsWpf.compute.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    var shaderCode = await shaderStreamReader.ReadToEndAsync();

                    computeShader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));
                }

            GpuShaderModule drawShader;

            using (var shaderFileStream = typeof(MainWindow).Assembly.GetManifestResourceStream("ComputeBoidsWpf.draw.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    var shaderCode = await shaderStreamReader.ReadToEndAsync();

                    drawShader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));
                }
            RenderPipeline = Device.CreateRenderPipeline(new GpuRenderPipelineDescriptor(new GpuVertexState(drawShader, "VSMain")
            {
                VertexBuffers = new GpuVertexBufferLayout[]
                {
                    new GpuVertexBufferLayout(4 * 4, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            Format         = GpuVertexFormat.Float2,
                            Offset         = 0,
                            ShaderLocation = 0
                        },
                        new GpuVertexAttribute()
                        {
                            Format         = GpuVertexFormat.Float2,
                            Offset         = 2 * 4,
                            ShaderLocation = 1
                        }
                    })
                    {
                        StepMode = GpuInputStepMode.Instance
                    },
                    new GpuVertexBufferLayout(2 * 4, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            Format         = GpuVertexFormat.Float2,
                            Offset         = 0,
                            ShaderLocation = 2
                        }
                    })
                }
            })
            {
                Fragment = new GpuFragmentState(drawShader, "PSMain", new GpuColorTargetState[] { new GpuColorTargetState {
                                                                                                      Format = GpuTextureFormat.BGRA8UNorm, Blend = null, WriteMask = GpuColorWriteFlags.All
                                                                                                  } }),
                Primitive = new GpuPrimitiveState {
                    Topology = GpuPrimitiveTopology.TriangleList, CullMode = GpuCullMode.None, FrontFace = GpuFrontFace.Ccw
                },
                DepthStencilState = new GpuDepthStencilState(GpuTextureFormat.Depth24PlusStencil8)
                {
                    DepthWriteEnabled = true,
                    DepthCompare      = GpuCompareFunction.Less,
                }
            });
            var computeBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Compute,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type             = GpuBufferBindingType.Uniform,
                        HasDynamicOffset = false,
                        MinBindingSize   = (ulong)(SimParamData.Length * sizeof(float))
                    }
                },
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 1,
                    Visibility = GpuShaderStageFlags.Compute,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type             = GpuBufferBindingType.ReadOnlyStorage,
                        HasDynamicOffset = false,
                        MinBindingSize   = NumParticles * 16
                    }
                },
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 2,
                    Visibility = GpuShaderStageFlags.Compute,
                    Buffer     = new GpuBufferBindingLayout()
                    {
                        Type             = GpuBufferBindingType.Storage,
                        HasDynamicOffset = false,
                        MinBindingSize   = NumParticles * 16
                    }
                }
            }));

            ComputePipeline = Device.CreateComputePipeline(new GpuComputePipelineDescriptor(new GpuProgrammableStage(computeShader, "main"))
            {
                Layout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
                {
                    BindGroupLayouts = new GpuBindGroupLayout[] { computeBindGroupLayout }
                }),
            });

            VerticesBuffer = Device.CreateBuffer(new GpuBufferDescriptor((ulong)(sizeof(float) * VertexBufferData.Length), GpuBufferUsageFlags.Vertex)
            {
                MappedAtCreation = true
            });
            using (var stream = VerticesBuffer.GetMappedRange().AsStream())
                using (var binaryWriter = new BinaryWriter(stream))
                {
                    for (int i = 0; i < VertexBufferData.Length; ++i)
                    {
                        binaryWriter.Write(VertexBufferData[i]);
                    }
                }
            VerticesBuffer.Unmap();

            var simParamBuffer = Device.CreateBuffer(new GpuBufferDescriptor((ulong)(sizeof(float) * SimParamData.Length), GpuBufferUsageFlags.Uniform)
            {
                MappedAtCreation = true
            });

            using (var stream = simParamBuffer.GetMappedRange().AsStream())
                using (var writer = new BinaryWriter(stream))
                {
                    for (int i = 0; i < SimParamData.Length; ++i)
                    {
                        writer.Write(SimParamData[i]);
                    }
                }
            simParamBuffer.Unmap();

            float[] initialParticleData = new float[NumParticles * 4];
            Random  random = new Random();

            for (var i = 0; i < NumParticles; ++i)
            {
                initialParticleData[4 * i + 0] = (float)(2 * (random.NextDouble() - 0.5f));
                initialParticleData[4 * i + 1] = (float)(2 * (random.NextDouble() - 0.5f));
                initialParticleData[4 * i + 2] = (float)(2 * (random.NextDouble() - 0.5f) * 0.1);
                initialParticleData[4 * i + 3] = (float)(2 * (random.NextDouble() - 0.5f) * 0.1);
            }
            Windows.Storage.Streams.Buffer initialParticleDataBuffer = new Windows.Storage.Streams.Buffer((uint)(sizeof(float) * initialParticleData.Length))
            {
                Length = (uint)(sizeof(float) * initialParticleData.Length)
            };
            using (var stream = initialParticleDataBuffer.AsStream())
                using (var writer = new BinaryWriter(stream))
                {
                    for (int i = 0; i < initialParticleData.Length; ++i)
                    {
                        writer.Write(initialParticleData[i]);
                    }
                }

            ParticleBuffers = new GpuBuffer[2];
            for (int i = 0; i < 2; ++i)
            {
                ParticleBuffers[i] = Device.CreateBuffer(new GpuBufferDescriptor(initialParticleDataBuffer.Length, GpuBufferUsageFlags.Vertex | GpuBufferUsageFlags.Storage)
                {
                    MappedAtCreation = true
                });
                initialParticleDataBuffer.CopyTo(ParticleBuffers[i].GetMappedRange());
                ParticleBuffers[i].Unmap();
            }
            ParticleBindGroups = new GpuBindGroup[2];
            for (var i = 0; i < 2; ++i)
            {
                ParticleBindGroups[i] = Device.CreateBindGroup(new GpuBindGroupDescriptor(computeBindGroupLayout, new GpuBindGroupEntry[]
                {
                    new GpuBindGroupEntry(0, new GpuBufferBinding(simParamBuffer, simParamBuffer.Size)),
                    new GpuBindGroupEntry(1, new GpuBufferBinding(ParticleBuffers[i], ParticleBuffers[i].Size)),
                    new GpuBindGroupEntry(2, new GpuBufferBinding(ParticleBuffers[(i + 1) % 2], ParticleBuffers[(i + 1) % 2].Size))
                }));
            }
            T = 0;
        }
コード例 #16
0
        async Task Init()
        {
            var gpu = new Gpu();

#if DEBUG
            gpu.EnableD3D12DebugLayer();
#endif
            Device = await(await gpu.RequestAdapterAsync()).RequestDeviceAsync();

            Windows.Storage.Streams.Buffer verticeCpuBuffer = new Windows.Storage.Streams.Buffer((uint)Buffer.ByteLength(Cube.CubeVertexArray));
            verticeCpuBuffer.Length = verticeCpuBuffer.Capacity;
            using (var verticeCpuStream = verticeCpuBuffer.AsStream())
            {
                byte[] vertexBufferBytes = new byte[Buffer.ByteLength(Cube.CubeVertexArray)];
                Buffer.BlockCopy(Cube.CubeVertexArray, 0, vertexBufferBytes, 0, Buffer.ByteLength(Cube.CubeVertexArray));
                await verticeCpuStream.WriteAsync(vertexBufferBytes, 0, Buffer.ByteLength(Cube.CubeVertexArray));
            }
            VerticesBuffer = Device.CreateBuffer(new GpuBufferDescriptor((ulong)Buffer.ByteLength(Cube.CubeVertexArray), GpuBufferUsageFlags.Vertex)
            {
                MappedAtCreation = true
            });
            verticeCpuBuffer.CopyTo(VerticesBuffer.GetMappedRange());
            VerticesBuffer.Unmap();
            string shaderCode;
            using (var shaderFileStream = typeof(MainPage).Assembly.GetManifestResourceStream("RotatingCube.shader.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    shaderCode = shaderStreamReader.ReadToEnd();
                }
            var shader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));

            //var shader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, ))

            var vertexState = new GpuVertexState(shader, "VSMain")
            {
                VertexBuffers = new GpuVertexBufferLayout[] { new GpuVertexBufferLayout(Cube.CubeVertexSize, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 0,
                            Format         = GpuVertexFormat.Float4,
                            Offset         = Cube.CubePositionOffset
                        },
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 1,
                            Format         = GpuVertexFormat.Float4,
                            Offset         = Cube.CubeColorOffset
                        }
                    }) }
            };
            var fragmentState = new GpuFragmentState(shader, "PSMain", new GpuColorTargetState[] { new GpuColorTargetState {
                                                                                                       Format = GpuTextureFormat.BGRA8UNorm, Blend = null, WriteMask = GpuColorWriteFlags.All
                                                                                                   } });
            var primitiveState = new GpuPrimitiveState
            {
                Topology         = GpuPrimitiveTopology.TriangleList,
                FrontFace        = GpuFrontFace.Ccw,
                CullMode         = GpuCullMode.Back,
                StripIndexFormat = null
            };
            var depthState = new GpuDepthStencilState(GpuTextureFormat.Depth24PlusStencil8)
            {
                DepthWriteEnabled = true,
                DepthCompare      = GpuCompareFunction.Less,
            };
            var uniformBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout
                    {
                        Type             = GpuBufferBindingType.Uniform,
                        HasDynamicOffset = false,
                        MinBindingSize   = UniformBufferSize
                    }
                }
            }));
            var pipelineLayout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
            {
                BindGroupLayouts = new GpuBindGroupLayout[]
                {
                    uniformBindGroupLayout
                }
            });

            Pipeline = Device.CreateRenderPipeline(new GpuRenderPipelineDescriptor(vertexState)
            {
                Fragment          = fragmentState,
                Primitive         = primitiveState,
                DepthStencilState = depthState,
                Layout            = pipelineLayout
            });

            UniformBuffer           = Device.CreateBuffer(new GpuBufferDescriptor(UniformBufferSize, GpuBufferUsageFlags.Uniform | GpuBufferUsageFlags.CopyDst));
            UniformCpuBuffer        = new Windows.Storage.Streams.Buffer(4 * 4 * sizeof(float));
            UniformCpuBuffer.Length = UniformCpuBuffer.Capacity;
            UniformBindGroup        = Device.CreateBindGroup(new GpuBindGroupDescriptor(uniformBindGroupLayout, new GpuBindGroupEntry[]
            {
                new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, UniformBufferSize))
            }));
        }
コード例 #17
0
        async Task Init()
        {
            var gpu = new Gpu();

#if DEBUG
            gpu.EnableD3D12DebugLayer();
#endif
            Device = await(await gpu.RequestAdapterAsync()).RequestDeviceAsync();

            Windows.Storage.Streams.Buffer verticeCpuBuffer = new Windows.Storage.Streams.Buffer((uint)Buffer.ByteLength(Cube.CubeVertexArray));
            verticeCpuBuffer.Length = verticeCpuBuffer.Capacity;
            using (var verticeCpuStream = verticeCpuBuffer.AsStream())
            {
                byte[] vertexBufferBytes = new byte[Buffer.ByteLength(Cube.CubeVertexArray)];
                Buffer.BlockCopy(Cube.CubeVertexArray, 0, vertexBufferBytes, 0, Buffer.ByteLength(Cube.CubeVertexArray));
                await verticeCpuStream.WriteAsync(vertexBufferBytes, 0, Buffer.ByteLength(Cube.CubeVertexArray));
            }
            VerticesBuffer = Device.CreateBuffer(new GpuBufferDescriptor((ulong)Buffer.ByteLength(Cube.CubeVertexArray), GpuBufferUsageFlags.Vertex)
            {
                MappedAtCreation = true
            });
            verticeCpuBuffer.CopyTo(VerticesBuffer.GetMappedRange());
            VerticesBuffer.Unmap();

            string shaderCode;
            using (var shaderFileStream = typeof(MainPage).Assembly.GetManifestResourceStream("TexturedCube.shader.hlsl"))
                using (var shaderStreamReader = new StreamReader(shaderFileStream))
                {
                    shaderCode = shaderStreamReader.ReadToEnd();
                }
            var shader = Device.CreateShaderModule(new GpuShaderModuleDescriptor(GpuShaderSourceType.Hlsl, shaderCode));

            var vertexState = new GpuVertexState(shader, "VSMain")
            {
                VertexBuffers = new GpuVertexBufferLayout[] { new GpuVertexBufferLayout(Cube.CubeVertexSize, new GpuVertexAttribute[]
                    {
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 0,
                            Format         = GpuVertexFormat.Float4,
                            Offset         = Cube.CubePositionOffset
                        },
                        new GpuVertexAttribute()
                        {
                            ShaderLocation = 1,
                            Format         = GpuVertexFormat.Float2,
                            Offset         = Cube.CubeUVOffset
                        }
                    }) }
            };
            var fragmentState = new GpuFragmentState(shader, "PSMain", new GpuColorTargetState[] { new GpuColorTargetState {
                                                                                                       Format = GpuTextureFormat.BGRA8UNorm, Blend = null, WriteMask = GpuColorWriteFlags.All
                                                                                                   } });
            var primitiveState = new GpuPrimitiveState
            {
                Topology         = GpuPrimitiveTopology.TriangleList,
                FrontFace        = GpuFrontFace.Ccw,
                CullMode         = GpuCullMode.Back,
                StripIndexFormat = null
            };
            var depthState = new GpuDepthStencilState(GpuTextureFormat.Depth24PlusStencil8)
            {
                DepthWriteEnabled = true,
                DepthCompare      = GpuCompareFunction.Less,
            };
            var uniformBindGroupLayout = Device.CreateBindGroupLayout(new GpuBindGroupLayoutDescriptor(new GpuBindGroupLayoutEntry[]
            {
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 0,
                    Visibility = GpuShaderStageFlags.Vertex,
                    Buffer     = new GpuBufferBindingLayout
                    {
                        Type             = GpuBufferBindingType.Uniform,
                        HasDynamicOffset = false,
                        MinBindingSize   = UniformBufferSize
                    }
                },
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 1,
                    Visibility = GpuShaderStageFlags.Fragment,
                    Sampler    = new GpuSamplerBindingLayout()
                    {
                        Type = GpuSamplerBindingType.Filtering
                    }
                },
                new GpuBindGroupLayoutEntry()
                {
                    Binding    = 2,
                    Visibility = GpuShaderStageFlags.Fragment,
                    Texture    = new GpuTextureBindingLayout()
                    {
                        SampleType    = GpuTextureSampleType.Float,
                        ViewDimension = GpuTextureViewDimension._2D,
                        Multisampled  = false
                    }
                }
            }));
            var pipelineLayout = Device.CreatePipelineLayout(new GpuPipelineLayoutDescriptor()
            {
                BindGroupLayouts = new GpuBindGroupLayout[]
                {
                    uniformBindGroupLayout
                }
            });
            Pipeline = Device.CreateRenderPipeline(new GpuRenderPipelineDescriptor(vertexState)
            {
                Fragment          = fragmentState,
                Primitive         = primitiveState,
                DepthStencilState = depthState,
                Layout            = pipelineLayout
            });
            UniformBuffer           = Device.CreateBuffer(new GpuBufferDescriptor(UniformBufferSize, GpuBufferUsageFlags.Uniform | GpuBufferUsageFlags.CopyDst));
            UniformCpuBuffer        = new Windows.Storage.Streams.Buffer(4 * 4 * sizeof(float));
            UniformCpuBuffer.Length = UniformCpuBuffer.Capacity;

            var imgDecoder = await BitmapDecoder.CreateAsync(typeof(MainPage).Assembly.GetManifestResourceStream("TexturedCube.Di_3d.png").AsRandomAccessStream());

            var imageBitmap = await imgDecoder.GetSoftwareBitmapAsync();

            var cubeTexture = Device.CreateTexture(new GpuTextureDescriptor(new GpuExtend3DDict {
                Width = (uint)imageBitmap.PixelWidth, Height = (uint)imageBitmap.PixelHeight, Depth = 1
            }, GpuTextureFormat.BGRA8UNorm, GpuTextureUsageFlags.Sampled | GpuTextureUsageFlags.CopyDst));
            Device.DefaultQueue.CopyImageBitmapToTexture(new GpuImageCopyImageBitmap(imageBitmap), new GpuImageCopyTexture(cubeTexture), new GpuExtend3DDict {
                Width = (uint)imageBitmap.PixelWidth, Height = (uint)imageBitmap.PixelHeight, Depth = 1
            });
            var sampler = Device.CreateSampler(new GpuSamplerDescriptor()
            {
                MagFilter = GpuFilterMode.Linear,
                MinFilter = GpuFilterMode.Linear
            });
            UniformBindGroup = Device.CreateBindGroup(new GpuBindGroupDescriptor(uniformBindGroupLayout, new GpuBindGroupEntry[]
            {
                new GpuBindGroupEntry(0, new GpuBufferBinding(UniformBuffer, UniformBufferSize)),
                new GpuBindGroupEntry(1, sampler),
                new GpuBindGroupEntry(2, cubeTexture.CreateView())
            }));
        }
コード例 #18
0
        private void buttonReadBulkIn_Click(object sender, RoutedEventArgs e)
        {
            if (buttonReadBulkIn.Content.ToString() == "Read")
            {
                uint bytesToRead = uint.Parse(textBoxBytesToRead.Text);
                if (bytesToRead > 0)
                {
                    // UI status.
                    buttonReadBulkIn.Content    = "Stop Read";
                    buttonWatchBulkIn.IsEnabled = false;
                    SDKTemplate.MainPage.Current.NotifyUser("Reading", SDKTemplate.NotifyType.StatusMessage);

                    var buffer = new Windows.Storage.Streams.Buffer(bytesToRead);
                    buffer.Length = bytesToRead;
                    int timeout = int.Parse(textBoxReadTimeout.Text);

                    var    dispatcher = this.Dispatcher;
                    Action readAction = async() =>
                    {
                        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async() =>
                        {
                            int count = 0;
                            try
                            {
                                count = await this.Read(buffer, timeout);
                            }
                            catch (System.OperationCanceledException)
                            {
                                // cancel.
                                SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                                return;
                            }
                            catch (System.Exception exception)
                            {
                                if (exception.HResult == -2146233088)
                                {
                                    // Device removed.
                                    return;
                                }
                                else
                                {
                                    throw;
                                }
                            }
                            finally
                            {
                                this.cancelTokenSrcOpRead = null;
                            }

                            this.buttonReadBulkIn.Content    = "Read";
                            this.buttonWatchBulkIn.IsEnabled = true;

                            if (count < bytesToRead)
                            {
                                // This would be timeout.
                                SDKTemplate.MainPage.Current.NotifyUser("Timeout: read " + count.ToString() + " byte(s)", SDKTemplate.NotifyType.ErrorMessage);
                            }
                            else
                            {
                                SDKTemplate.MainPage.Current.NotifyUser("Completed", SDKTemplate.NotifyType.StatusMessage);
                            }

                            if (count > 0)
                            {
                                var isAscii = this.radioButtonAscii.IsChecked.Value == true;
                                var temp    = this.textBoxReadBulkInLogger.Text;
                                temp       += isAscii ? Util.AsciiBufferToAsciiString(buffer) : Util.BinaryBufferToBinaryString(buffer);
                                this.textBoxReadBulkInLogger.Text = temp;
                            }
                        }));
                    };
                    readAction.Invoke();
                }
            }
            else
            {
                this.buttonStopWatching_Click(this, null);
                this.buttonReadBulkIn.Content = "Read";
            }
        }
コード例 #19
0
            /// <summary>
            /// GET_LINE_CODING CDC request.
            /// </summary>
            /// <param name="index">Interface index.</param>
            /// <returns>
            /// The result of Task contains a buffer of Line Coding structure.
            /// </returns>
            private Task<Windows.Storage.Streams.IBuffer> GetLineCoding(
                uint index
            )
            {
                return Task.Run(async () =>
                {
                    var buffer = new Windows.Storage.Streams.Buffer(Constants.ExpectedResultGetLineCoding);
                    buffer.Length = Constants.ExpectedResultGetLineCoding;

                    var requestType = new UsbControlRequestType();
                    requestType.AsByte = RequestType.Get;

                    var packet = new UsbSetupPacket();
                    packet.RequestType = requestType;
                    packet.Request = RequestCode.GetLineCoding;
                    packet.Value = 0;
                    packet.Length = buffer.Length;
                    packet.Index = index;
            
                    return await this.device.SendControlInTransferAsync(packet, buffer);
                });
            }
コード例 #20
0
ファイル: Scenario4_Loopback.xaml.cs プロジェクト: ckc/WinApp
        private Windows.Foundation.IAsyncOperation <int> Read(UsbCdcControlAccess.UsbSerialPort port, Windows.Storage.Streams.Buffer buffer, int timeout)
        {
            port.ReadTimeout = timeout;

            if (this.cancelTokenSrcOpRead != null)
            {
                this.cancelTokenSrcOpRead.Dispose();
            }
            var source = this.cancelTokenSrcOpRead = new System.Threading.CancellationTokenSource();

            return(port.Read(buffer, 0, buffer.Length, source.Token));
        }
コード例 #21
0
ファイル: Scenario4_Loopback.xaml.cs プロジェクト: ckc/WinApp
        private void buttonLoopbackTest_Click(object sender, RoutedEventArgs e)
        {
            // Unicode to ASCII.
            String textToSend = this.textBoxForLoopback.Text;
            var    encoder = System.Text.Encoding.UTF8.GetEncoder();
            var    utf8bytes = new byte[textToSend.Length];
            int    bytesUsed, charsUsed;
            bool   completed;

            encoder.Convert(textToSend.ToCharArray(), 0, textToSend.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed);

            var writer = new Windows.Storage.Streams.DataWriter();

            writer.WriteBytes(utf8bytes);
            writer.WriteByte(0x00); // NUL
            var buffer = writer.DetachBuffer();

            this.buttonLoopbackTest.IsEnabled = false;
            this.buttonStopLoopback.IsEnabled = true;
            SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.StatusMessage);

            var dispatcher = this.Dispatcher;

            ((Action)(async() =>
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async() =>
                {
                    // serialport1 to serialport2

                    var readBuffer = new Windows.Storage.Streams.Buffer(buffer.Length);
                    readBuffer.Length = buffer.Length;

                    var writeTask = this.SerialPortInfo1.Port.Write(buffer, 0, buffer.Length).AsTask();
                    var readTask = this.Read(this.SerialPortInfo2.Port, readBuffer, Constants.InfiniteTimeout).AsTask();

                    try
                    {
                        await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask });
                        readBuffer.Length = (uint)readTask.Result;
                    }
                    catch (System.OperationCanceledException)
                    {
                        // canceled.
                        SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                        this.buttonLoopbackTest.IsEnabled = true;
                        this.buttonStopLoopback.IsEnabled = false;
                        return;
                    }
                    finally
                    {
                        this.cancelTokenSrcOpRead = null;
                        writeTask.AsAsyncAction().Cancel(); // just in case.
                        readTask.AsAsyncAction().Cancel();  // just in case.
                    }

                    var isSame = Util.CompareTo(buffer, readBuffer) == 0;
                    String statusMessage = "";
                    if (isSame)
                    {
                        statusMessage += "CDC device 2 received \"" + textToSend + "\" from CDC device 1. ";
                    }
                    else
                    {
                        statusMessage += "Loopback failed: CDC device 1 to CDC device 2. ";
                    }

                    // serialport2 to serialport1

                    readBuffer.Length = buffer.Length;

                    writeTask = this.SerialPortInfo2.Port.Write(buffer, 0, buffer.Length).AsTask();
                    readTask = this.Read(this.SerialPortInfo1.Port, readBuffer, Constants.InfiniteTimeout).AsTask();

                    try
                    {
                        await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask });
                        readBuffer.Length = (uint)readTask.Result;
                    }
                    catch (System.OperationCanceledException)
                    {
                        // canceled.
                        SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                        this.buttonLoopbackTest.IsEnabled = true;
                        this.buttonStopLoopback.IsEnabled = false;
                        return;
                    }
                    finally
                    {
                        this.cancelTokenSrcOpRead = null;
                        writeTask.AsAsyncAction().Cancel(); // just in case.
                        readTask.AsAsyncAction().Cancel();  // just in case.
                    }

                    isSame = Util.CompareTo(buffer, readBuffer) == 0;
                    if (isSame)
                    {
                        statusMessage += "CDC device 1 received \"" + textToSend + "\" from CDC device 2. ";
                    }
                    else
                    {
                        statusMessage += "Loopback failed: CDC device 2 to CDC device 1. ";
                    }

                    this.buttonLoopbackTest.IsEnabled = true;
                    this.buttonStopLoopback.IsEnabled = false;
                    SDKTemplate.MainPage.Current.NotifyUser(statusMessage, SDKTemplate.NotifyType.StatusMessage);
                }));
            }
                      )).Invoke();
        }
コード例 #22
0
        private void buttonLoopbackTest_Click(object sender, RoutedEventArgs e)
        {
            // Unicode to ASCII.
            String textToSend = this.textBoxForLoopback.Text;                    
            var encoder = System.Text.Encoding.UTF8.GetEncoder();
            var utf8bytes = new byte[textToSend.Length];
            int bytesUsed, charsUsed;
            bool completed;
            encoder.Convert(textToSend.ToCharArray(), 0, textToSend.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed);

            var writer = new Windows.Storage.Streams.DataWriter();
            writer.WriteBytes(utf8bytes);
            writer.WriteByte(0x00); // NUL
            var buffer = writer.DetachBuffer();

            this.buttonLoopbackTest.IsEnabled = false;
            this.buttonStopLoopback.IsEnabled = true;
            SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.StatusMessage);

            var dispatcher = this.Dispatcher;
            ((Action)(async () =>
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () =>
                {
                    // serialport1 to serialport2

                    var readBuffer = new Windows.Storage.Streams.Buffer(buffer.Length);
                    readBuffer.Length = buffer.Length;

                    var writeTask = this.SerialPortInfo1.Port.Write(buffer, 0, buffer.Length).AsTask();
                    var readTask = this.Read(this.SerialPortInfo2.Port, readBuffer, Constants.InfiniteTimeout).AsTask();

                    try
                    {
                        await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] {writeTask, readTask});
                        readBuffer.Length = (uint)readTask.Result;
                    }
                    catch (System.OperationCanceledException)
                    {
                        // canceled.
                        SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                        this.buttonLoopbackTest.IsEnabled = true;
                        this.buttonStopLoopback.IsEnabled = false;
                        return;
                    }
                    finally
                    {
                        this.cancelTokenSrcOpRead = null;
                        writeTask.AsAsyncAction().Cancel(); // just in case.
                        readTask.AsAsyncAction().Cancel(); // just in case.
                    }

                    var isSame = Util.CompareTo(buffer, readBuffer) == 0;
                    String statusMessage = "";
                    if (isSame)
                    {
                        statusMessage += "CDC device 2 received \"" + textToSend + "\" from CDC device 1. ";
                    }
                    else
                    {
                        statusMessage += "Loopback failed: CDC device 1 to CDC device 2. ";
                    }

                    // serialport2 to serialport1

                    readBuffer.Length = buffer.Length;

                    writeTask = this.SerialPortInfo2.Port.Write(buffer, 0, buffer.Length).AsTask();
                    readTask = this.Read(this.SerialPortInfo1.Port, readBuffer, Constants.InfiniteTimeout).AsTask();

                    try
                    {
                        await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask });
                        readBuffer.Length = (uint)readTask.Result;
                    }
                    catch (System.OperationCanceledException)
                    {
                        // canceled.
                        SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                        this.buttonLoopbackTest.IsEnabled = true;
                        this.buttonStopLoopback.IsEnabled = false;
                        return;
                    }
                    finally
                    {
                        this.cancelTokenSrcOpRead = null;
                        writeTask.AsAsyncAction().Cancel(); // just in case.
                        readTask.AsAsyncAction().Cancel(); // just in case.
                    }

                    isSame = Util.CompareTo(buffer, readBuffer) == 0;
                    if (isSame)
                    {
                        statusMessage += "CDC device 1 received \"" + textToSend + "\" from CDC device 2. ";
                    }
                    else
                    {
                        statusMessage += "Loopback failed: CDC device 2 to CDC device 1. ";
                    }

                    this.buttonLoopbackTest.IsEnabled = true;
                    this.buttonStopLoopback.IsEnabled = false;
                    SDKTemplate.MainPage.Current.NotifyUser(statusMessage, SDKTemplate.NotifyType.StatusMessage);
                }));
            }
            )).Invoke();
        }
コード例 #23
0
        private async Task ReadJSON(SerialDevice device)
        {
            var   currentStr = "";
            State state      = State.Outside_of_object;
            var   buffer     = new Windows.Storage.Streams.Buffer(bufferSize);

            while (true)
            {
                try
                {
                    var result = await device.InputStream.ReadAsync(buffer, bufferSize, Windows.Storage.Streams.InputStreamOptions.None);

                    if (result.Length > 0)
                    {
                        lock (lockObj)
                        {
                            totalBytesReadFromSerial += result.Length;
                            if (bPauseDataRead)
                            {
                                continue;
                            }
                        }

                        this.state.serialWire.Update(WireState.Solid);
                        this.state.serialWire.Update(DataFlow.Active);

                        var str = System.Text.Encoding.ASCII.GetString(result.ToArray());
                        //Debug.WriteLine(string.Format("[{0}]", str));
                        foreach (var c in str)
                        {
                            switch (c)
                            {
                            case '{':
                                switch (state)
                                {
                                case State.Outside_of_object:
                                    currentStr = c.ToString();
                                    state      = State.Inside_object;
                                    break;

                                case State.Inside_object:
                                    // throw new NotSupportedException("Nested JSON valued are not supported");
                                    // We got into a weird state. Get out.
                                    currentStr = c.ToString();
                                    state      = State.Inside_object;
                                    break;
                                }
                                break;

                            case '}':
                                switch (state)
                                {
                                case State.Outside_of_object:
                                    // we started reading mid-stream, but now we're truly outside
                                    break;

                                case State.Inside_object:
                                    currentStr += c;
                                    cq.Enqueue(currentStr);
                                    await HandleJSONObject(currentStr);

                                    // Nested are not supported
                                    state      = State.Outside_of_object;
                                    currentStr = "";
                                    break;
                                }
                                break;

                            case '\n':
                                //noop
                                break;

                            default:
                                switch (state)
                                {
                                case State.Outside_of_object:
                                    // skip this char
                                    break;

                                case State.Inside_object:
                                    // accumulate it:
                                    currentStr += c;
                                    break;
                                }
                                break;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    this.state.serialWire.Update(DataFlow.Stopped);
                    this.state.serialWire.Update(WireState.Cut);
                    device.Dispose();
                    break;
                }
            }
        }