Exemplo n.º 1
0
        public override async Task <WriteDataItemsResult> WriteDataItems(string group, IList <DataItemValue> values, Duration?timeout)
        {
            if (!await TryConnect() || connection == null)
            {
                var failed = values.Select(div => new FailedDataItemWrite(div.ID, "No connection to server")).ToArray();
                return(WriteDataItemsResult.Failure(failed));
            }

            var writeMan = new WriteManager <VariableValue, VariableError>(values, request => {
                if (mapId2Info.ContainsKey(request.ID))
                {
                    ItemInfo info = mapId2Info[request.ID];
                    return(VariableValue.Make(info.VarRef, request.Value));
                }
                else
                {
                    throw new Exception("No Address defined");
                }
            });

            try {
                var         dataItemsToWrite = writeMan.GetRefsList();
                WriteResult res = await connection.WriteVariablesSyncIgnoreMissing(dataItemsToWrite, timeout);

                if (!res.IsOK())
                {
                    writeMan.AddWriteErrors(res.FailedVariables, failedVar => {
                        VariableRef v = failedVar.Variable;
                        int idx       = dataItemsToWrite.FindIndexOrThrow(vv => vv.Variable == v);
                        string id     = writeMan.GetWriteRequest(idx).ID;
                        return(new FailedDataItemWrite(id, failedVar.Error));
                    });
                }
            }
            catch (Exception exp) {
                Task      ignored = CloseConnection();
                Exception e       = exp.GetBaseException() ?? exp;
                string    msg     = $"Write exception: {e.Message}";
                LogWarn("WriteExcept", msg, details: e.ToString());
                var failed = values.Select(div => new FailedDataItemWrite(div.ID, msg)).ToArray();
                return(WriteDataItemsResult.Failure(failed));
            }

            return(writeMan.GetWriteResult());
        }