/// <summary> /// Sends the telecontrol command. /// </summary> public void SendCommand(ServiceApp serviceApp, TeleCommand cmd) { // initialize command ID and timestamp DateTime utcNow = DateTime.UtcNow; if (cmd.CommandID == 0) { cmd.CommandID = ScadaUtils.GenerateUniqueID(utcNow); } if (cmd.CreationTime == DateTime.MinValue) { cmd.CreationTime = utcNow; } // upload command using (MemoryStream stream = new MemoryStream()) { cmd.Save(stream); stream.Position = 0; string fileName = string.Format("cmd_{0}.dat", cmd.CommandID); UploadFile(stream, new RelativePath(serviceApp, AppFolder.Cmd, fileName), out bool fileAccepted); if (!fileAccepted) { throw new ScadaException(Locale.IsRussian ? "Команда отклонена Агентом." : "Command rejected by Agent."); } } }
/// <summary> /// Sends the telecontrol command. /// </summary> public void SendCommand(TeleCommand command, WriteFlags writeFlags, out CommandResult commandResult) { if (command.CnlNum > 0) { // validate and send command coreLogic.SendCommand(command, writeFlags, out commandResult); } else { // process acknowledgment command that can only be sent by module if (command.CmdCode == ServerCmdCode.AckEvent) { coreLogic.AckEvent(new EventAck { EventID = BitConverter.DoubleToInt64Bits(command.CmdVal), Timestamp = command.CreationTime, UserID = command.UserID }, false, false); } // set command ID and creation time if (command.CommandID <= 0) { DateTime utcNow = DateTime.UtcNow; command.CommandID = ScadaUtils.GenerateUniqueID(utcNow); command.CreationTime = utcNow; } // pass command directly to clients listener.EnqueueCommand(command); commandResult = new CommandResult(true); } }
/// <summary> /// Gets a name for a temporary file and extraction directory. /// </summary> private void GetTempFileName(out string tempFileName, out string extractDir) { string s = AgentConst.DownloadConfigPrefix + ScadaUtils.GenerateUniqueID(); tempFileName = Path.Combine(appDirs.TempDir, s + ".zip"); extractDir = Path.Combine(appDirs.TempDir, s); tempFileNames.Add(tempFileName); extractDirs.Add(extractDir); }
/// <summary> /// Initializes a new instance of the class. /// </summary> public ViewBase(View viewEntity) { ViewEntity = viewEntity ?? throw new ArgumentNullException(nameof(viewEntity)); ViewStamp = ScadaUtils.GenerateUniqueID(); StoredOnServer = true; Args = ParseArgs(); Title = GetTitle(); Resources = null; CnlNumList = new List <int>(); CnlNumSet = new HashSet <int>(); }
/// <summary> /// Initializes a new instance of the class. /// </summary> public ClientBase(ConnectionOptions connectionOptions) { inBuf = new byte[BufferLenght]; outBuf = new byte[BufferLenght]; tcpClient = null; netStream = null; transactionID = 0; connAttemptDT = DateTime.MinValue; responseDT = DateTime.MinValue; ConnectionOptions = connectionOptions ?? throw new ArgumentNullException(nameof(connectionOptions)); ClientID = ScadaUtils.GenerateUniqueID(); ClientMode = 0; CommLog = null; ClientState = ClientState.Disconnected; SessionID = 0; ServerName = ""; UserID = 0; RoleID = 0; }
/// <summary> /// Handles a message received event. /// </summary> private void MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e) { try { string topic = e.ApplicationMessage.Topic; string payload = e.ApplicationMessage.ConvertPayloadToString(); dsLog.WriteAction("{0} {1} = {2}", CommPhrases.ReceiveNotation, topic, payload.GetPreview(MqttUtils.MessagePreviewLength)); // parse and pass command if (topic == commandTopic) { ReceivedCommand command = JsonSerializer.Deserialize <ReceivedCommand>(payload); CommContext.SendCommand(new TeleCommand { CommandID = ScadaUtils.GenerateUniqueID(), CreationTime = DateTime.UtcNow, DeviceNum = command.DeviceNum, CmdCode = command.CmdCode, CmdVal = command.CmdVal, CmdData = ScadaUtils.HexToBytes(command.CmdData, false, true) }, DriverUtils.DriverCode); } } catch (JsonException) { dsLog.WriteError(Locale.IsRussian ? "Ошибка при получении команды из JSON." : "Error parsing command from JSON."); } catch (Exception ex) { dsLog.WriteError(ex, Locale.IsRussian ? "Ошибка при обработке полученного сообщения. Топик: {0}" : "Error handling the received message. Topic: {0}", e?.ApplicationMessage?.Topic); } }
/// <summary> /// Initializes a new instance of the class. /// </summary> public CnlNumList(int[] cnlNums) : this(ScadaUtils.GenerateUniqueID(), cnlNums) { }
/// <summary> /// Raised when the Value attribute is written. /// </summary> private ServiceResult OnSimpleWriteValue(ISystemContext context, NodeState node, ref object value) { string varPath = node.NodeId.ToString(); try { log.WriteAction(Locale.IsRussian ? "Запись переменной {0} = {1}" : "Write variable {0} = {1}", varPath, value?.ToString() ?? ""); if (varByPath.TryGetValue(varPath, out VarItem varItem)) { DeviceTag deviceTag = varItem.DeviceTag; double cmdVal = 0.0; byte[] cmdData = null; switch (deviceTag.DataType) { case TagDataType.Double: if (deviceTag.IsArray) { cmdData = DoubleArrayToCmdData(value as Array, deviceTag.DataLength); } else { cmdVal = Convert.ToDouble(value); } break; case TagDataType.Int64: if (deviceTag.IsArray) { cmdData = Int64ArrayToCmdData(value as Array, deviceTag.DataLength); } else { cmdVal = Convert.ToInt64(value); } break; case TagDataType.ASCII: case TagDataType.Unicode: cmdData = TeleCommand.StringToCmdData(value?.ToString()); break; } commContext.SendCommand(new TeleCommand { CommandID = ScadaUtils.GenerateUniqueID(), CreationTime = DateTime.UtcNow, CmdTypeID = CmdTypeID.Standard, DeviceNum = varItem.DeviceNum, CmdCode = varItem.DeviceTag.Code, CmdVal = cmdVal, CmdData = cmdData }, DriverUtils.DriverCode); } return(ServiceResult.Good); } catch (Exception ex) { log.WriteException(ex, Locale.IsRussian ? "Ошибка при записи переменной {0}" : "Error writing the variable {0}", varPath); return(new ServiceResult(StatusCodes.Bad)); } }
/// <summary> /// Gets a name for a temporary file. /// </summary> private string GetTempFileName() { return(Path.Combine(appDirs.TempDir, AgentConst.UploadConfigPrefix + ScadaUtils.GenerateUniqueID() + ".zip")); }
/// <summary> /// Gets the events. /// </summary> private void GetEvents(ConnectedClient client, DataPacket request) { byte[] buffer = request.Buffer; int index = ArgumentIndex; int archiveBit = GetByte(buffer, ref index); TimeRange timeRange = GetTimeRange(buffer, ref index); long dataFilterID = GetInt64(buffer, ref index); DataFilter dataFilter; if (dataFilterID > 0) { dataFilter = serverCache.DataFilterCache.Get(dataFilterID); if (dataFilter == null) { dataFilterID = 0; } } else { bool useCache = GetBool(buffer, ref index); dataFilter = GetDataFilter(typeof(Event), buffer, ref index); if (useCache) { dataFilterID = ScadaUtils.GenerateUniqueID(); if (!serverCache.DataFilterCache.Add(dataFilterID, dataFilter)) { dataFilterID = 0; } } } List <Event> events = dataFilter == null ? new List <Event>() : archiveHolder.GetEvents(archiveBit, timeRange, dataFilter); int totalEventCount = events.Count; int blockCount = totalEventCount > 0 ? (int)Math.Ceiling((double)totalEventCount / EventBlockCapacity) : 1; int eventIndex = 0; buffer = client.OutBuf; for (int blockNumber = 1; blockNumber <= blockCount; blockNumber++) { ResponsePacket response = new ResponsePacket(request, buffer); index = ArgumentIndex; CopyInt32(blockNumber, buffer, ref index); CopyInt32(blockCount, buffer, ref index); CopyInt64(dataFilterID, buffer, ref index); CopyInt32(totalEventCount, buffer, ref index); int eventCount = Math.Min(totalEventCount - eventIndex, EventBlockCapacity); // events in this block CopyInt32(eventCount, buffer, ref index); for (int i = 0; i < eventCount; i++) { CopyEvent(events[eventIndex], buffer, ref index); eventIndex++; } response.BufferLength = index; client.SendResponse(response); } }