Exemplo n.º 1
0
    public Task StartTakePicture(int intervalMSec, CancellationTokenSource cancelTokenSource)
    {
        if (string.IsNullOrEmpty(photoFileNamePrefix))
        {
            var css    = ConnectionString.Split(";");
            var devdef = css[1].Split("=");
            photoFileNamePrefix = devdef[1];
        }
        lock (this) {
            takePhotoIntervalMSec = intervalMSec;
        }
        var tmpFileName     = photoFileName + photoFileNameExt;
        var photoTakingTask = Task.Factory.StartNew(async() => {
            var capture = OpenCvSharp.VideoCapture.FromCamera(0);
            using (var win = new OpenCvSharp.Window())
                using (var mat = new OpenCvSharp.Mat()) {
                    while (true)
                    {
                        capture.Read(mat);
                        win.ShowImage(mat);
                        var now = DateTime.Now;
                        if (File.Exists(tmpFileName))
                        {
                            File.Delete(tmpFileName);
                        }
                        using (var fs = new FileStream(tmpFileName, FileMode.CreateNew)) {
                            mat.WriteToStream(fs, photoFileNameExt, null);
                        }
                        var fileName = photoFileNamePrefix + now.ToString("yyyyMMddHHmmss") + photoFileNameExt;
                        await UploadFile(fileName, new FileInfo(tmpFileName).FullName);
                        var interval = 0;
                        lock (this) {
                            interval = takePhotoIntervalMSec;
                        }
                        await Task.Delay(interval);
                        if (cancelTokenSource.IsCancellationRequested)
                        {
                            break;
                        }
                    }
                    throw new OperationCanceledException(cancelTokenSource.Token);
                }
        }, cancelTokenSource.Token);

        return(photoTakingTask);
    }