コード例 #1
0
        public void MergeFrom(Sensor other)
        {
            if (other == null)
            {
                return;
            }
            if (other.Pin != 0)
            {
                Pin = other.Pin;
            }
            switch (other.TypeCase)
            {
            case TypeOneofCase.Digital:
                if (Digital == null)
                {
                    Digital = new global::SensorsAndEngines.ProtobufModels.DigitalSensor();
                }
                Digital.MergeFrom(other.Digital);
                break;

            case TypeOneofCase.Analog:
                if (Analog == null)
                {
                    Analog = new global::SensorsAndEngines.ProtobufModels.AnalogSensor();
                }
                Analog.MergeFrom(other.Analog);
                break;
            }

            _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
        }
コード例 #2
0
        /// <summary>
        /// 处理温湿度数据
        /// </summary>
        /// <param name="num">在线数</param>
        /// <param name="index">索引</param>
        /// <param name="data">数据</param>
        /// <param name="type">传感器类型</param>
        /// <returns></returns>
        private int ProcessTemperatureAndHumidity(int num, int index, byte[] data, int type)
        {
            for (int i = 0; i < num; i++)
            {
                Digital digitalWd = new Digital();
                digitalWd.Id = Convert.ToString(data[index++], 16);
                double wd = Convert.ToDouble(data[index++] << 8 | data[index++]) / 10;
                digitalWd.Value        = wd + "℃";
                digitalWd.Name         = "温度";
                digitalWd.Type         = type;
                digitalWd.Online       = wd == 0 ? StateType.Offline : StateType.Online;
                digitalWd.State        = wd == 0 ? StateType.StateClose : StateType.StateOpen;
                digitalWd.Controllable = false;
                Sensors.Add(digitalWd);
                Digital digitalSd = new Digital();
                digitalSd.Id = digitalWd.Id;
                double sd = Convert.ToDouble(data[index++] << 8 | data[index++]) / 10;
                digitalSd.Value        = sd + "%";
                digitalSd.Name         = "湿度";
                digitalSd.Type         = type;
                digitalSd.Online       = sd == 0 ? StateType.Offline : StateType.Online;
                digitalSd.State        = sd == 0 ? StateType.StateClose : StateType.StateOpen;
                digitalSd.Controllable = false;
                Sensors.Add(digitalSd);
            }

            return(index);
        }
コード例 #3
0
        public Resultado <Digital, Falha> IdentificarDigital(byte[] digitalLida, Digital digitalParaComparar)
        {
            var encontrou = false;
            var payload   = new NBioAPI.Type.FIR_PAYLOAD();

            NBioAPI.Type.HFIR digitalLidaConvertida;
            _apiConversor.FDxToNBioBSPEx(digitalLida, (uint)digitalLida.Length, NBioAPI.Type.MINCONV_DATA_TYPE.MINCONV_TYPE_ISO, NBioAPI.Type.FIR_PURPOSE.ENROLL_FOR_IDENTIFICATION_ONLY, out digitalLidaConvertida);

            NBioAPI.Type.HFIR digitalParaCompararConvertida;
            _apiConversor.FDxToNBioBSPEx(digitalParaComparar.TemplateIso, (uint)digitalParaComparar.TemplateIso.Length, NBioAPI.Type.MINCONV_DATA_TYPE.MINCONV_TYPE_ISO, NBioAPI.Type.FIR_PURPOSE.ENROLL_FOR_IDENTIFICATION_ONLY, out digitalParaCompararConvertida);

            var retorno = _api.VerifyMatch(digitalLidaConvertida, digitalParaCompararConvertida, out encontrou, payload);

            if (encontrou)
            {
                var cbInfo = new NBioAPI.IndexSearch.CALLBACK_INFO_0();
                NBioAPI.IndexSearch.FP_INFO[] informacaoBiometria;
                NBioAPI.IndexSearch.FP_INFO   nitgenBiometria;

                var resultadoAddFir = _apiBusca.AddFIR(digitalLidaConvertida, (uint)digitalParaComparar.Id, out informacaoBiometria);
                retorno = _apiBusca.IdentifyData(digitalLidaConvertida, NBioAPI.Type.FIR_SECURITY_LEVEL.HIGHEST, out nitgenBiometria, cbInfo);

                var idEncontrado = nitgenBiometria.ID;
                _apiBusca.RemoveUser((uint)digitalParaComparar.Id);
                if (idEncontrado > 0)
                {
                    return(digitalParaComparar);
                }
            }
            Debug.WriteLine($"digital {digitalParaComparar.Id}");
            return(Falha.Nova(404, "Digital não encontrada"));
        }
コード例 #4
0
        /// <summary>
        /// Calculates a possibly command, in dependence of digital properties,
        /// return true if should command to Simulator.
        /// </summary>
        /// <param name="digital"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        public static bool InitialCommandingForDigital(Digital digital, out CommandTypes command)
        {
            // ovde nema neke velike logike za sada, ali je ideja da kasnije nekad bude ...prosirivo? xD

            command = CommandTypes.OPEN;

            // if previously states was OPENED, OPEN it again
            if (digital.State == States.OPEN)
            {
                command = CommandTypes.OPEN;
                return(true);
            }

            if (digital.State == States.CLOSED && digital.Command == CommandTypes.OPEN)
            {
                command = CommandTypes.OPEN;
                return(true);
            }

            /*
             * if (digital.State==States.OPENED && digital.Command == CommandTypes.CLOSE)
             * {
             *  // to do: ...
             * }*/

            return(false);
        }
コード例 #5
0
        public static bool ValidateDigitalCommand(Digital digital, CommandTypes command)
        {
            bool retVal = true;

            if (digital.ValidCommands.Contains(command))
            {
                switch (command)
                {
                case CommandTypes.CLOSE:

                    //  command is CLOSE, last command was CLOSE, and state is CLOSED -> invalid...
                    if (digital.State == States.CLOSED && digital.Command == CommandTypes.CLOSE)
                    {
                        retVal = false;
                    }

                    // command is CLOSE, last command was CLOSE, but state is OPENED (incident) -> valid

                    break;

                case CommandTypes.OPEN:
                    if (digital.State == States.OPEN && digital.Command == CommandTypes.OPEN)
                    {
                        retVal = false;
                    }

                    break;
                }
            }
            return(retVal);
        }
コード例 #6
0
        public OMSSCADACommon.Responses.Response ReadSingleDigital(string id)
        {
            Digital digital = null;

            OMSSCADACommon.Responses.Response response = new OMSSCADACommon.Responses.Response();

            // getting PV from db
            ProcessVariable pv;

            if (dbContext.GetProcessVariableByName(id, out pv))
            {
                digital = (Digital)pv;
            }

            // does this ID exist in the database
            if (digital == null)
            {
                response.ResultMessage = ResultMessage.INVALID_ID;
                return(response);
            }

            DigitalVariable digitalVariable = new DigitalVariable()
            {
                Id    = id,
                State = digital.State
            };

            response.Variables.Add(digitalVariable);

            return(response);
        }
コード例 #7
0
ファイル: DigitalEditor.aspx.cs プロジェクト: 690312856/DIS
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request["DigitalID"] != null)  // 修改
            {
                Digital n = new Digital();
                n.DigitalID = Convert.ToInt32(Request["DigitalID"].Trim());

              //  int DigitalID = Convert.ToInt32(Request["DigitalID"].Trim());
                string sql = "select * from Digital where DigitalID=" + n.DigitalID;// +" and NewsState<>'0'";
                var r = DBHelper.INST.ExecuteSqlDR(sql);
                if (!r.Read())
                {
                    Response.Write("内容未通过审核");
                    Response.End();
                }

                n.DigitalTitle = r["DigitalTitle"].ToString();
                n.DigitalContent = r["DigitalContent"].ToString();

                txtTitle.Text = n.DigitalTitle;
                editorContent = n.DigitalContent;
                r.Close();
            }
            else  // 添加
            {
                editorContent = "&lt;p&gt;This is some &lt;strong&gt;sample text&lt;/strong&gt;. ";
            }
        }
    }
コード例 #8
0
 // This is called every update when the tool is equipped for the user that has the tooltip equipped
 public override void Update(float primaryStrength, float2 secondaryAxis, Digital primary, Digital secondary)
 {
     // Pressing the primary button (usually trigger) will increase probability of spawning a cube each frame, up to 10 % when fully pressed
     if (RandomX.Chance(primaryStrength * 0.5f))  // Alternate way of writing: if(RandomX.Value < primaryStrength * 0.1f)
     {
         SpawnCube();
     }
 }
コード例 #9
0
 public static void AssignDigitalInput(string name, Digital input, EventBus.EventBus.EventCallback callback = null) // TODO remove callback argument?
 {
     _mappedDigitalInputs[name] = new Digital[] { input };
     if (callback != null)
     {
         EventBus.EventBus.NewTagListener($"input/{name}", callback);
     }
 }
コード例 #10
0
ファイル: Form1.cs プロジェクト: Unripe01/ArduinoSerialRead
        private void WriteToCom(Digital button)
        {
            SerialPort mySerialPort = new SerialPort(comboBox_COM.SelectedItem.ToString());

            mySerialPort.BaudRate = int.Parse(comboBox_RATE.SelectedItem.ToString());
            mySerialPort.Open();
            mySerialPort.Write(button.ToString());
            mySerialPort.Close();
        }
        public Resultado <Digital, Falha> Executar(IdentificarSocioPorDigitalComando comando)
        {
            var tempoIdentificacao = new Stopwatch();

            tempoIdentificacao.Start();

            if (_identificadoresDeDigital == null)
            {
                _identificadoresDeDigital = new ConcurrentBag <ServicoIdentificacaoDigital>();
            }
            if (_identificadoresDeDigital.Count == 0)
            {
                if (_configuracoesBiometriaRepositorio.Recuperar(comando.Estacao) is var configuracaoBiometria && configuracaoBiometria.EhFalha)
                {
                    return(configuracaoBiometria.Falha);
                }

                if (_fabricaMotorBuscaBiometrica.CriarMotorDeBuscaBiometrica(configuracaoBiometria.Sucesso.ParceiroSdkDigital) is var motorBusca && motorBusca.EhFalha)
                {
                    return(motorBusca.Falha);
                }

                if (_digitaisRepositorio.RecuperarNumeroTotalDigitais() is var quantidadeDigitais && quantidadeDigitais.EhFalha)
                {
                    return(quantidadeDigitais.Falha);
                }

                var digitaisPorPagina = (quantidadeDigitais.Sucesso / configuracaoBiometria.Sucesso.QuantidadeThreadsIdentificacaoDigital) + configuracaoBiometria.Sucesso.QuantidadeThreadsIdentificacaoDigital;
                for (int pagina = 1; pagina <= configuracaoBiometria.Sucesso.QuantidadeThreadsIdentificacaoDigital; pagina++)
                {
                    if (_digitaisRepositorio.RecuperarPagina(pagina, digitaisPorPagina) is var digitais && digitais.EhFalha)
                    {
                        return(digitais.Falha);
                    }
                    if (digitais.Sucesso.Count() > 0)
                    {
                        _identificadoresDeDigital.Add(new ServicoIdentificacaoDigital(motorBusca.Sucesso, digitais.Sucesso));
                    }
                }
            }

            var digital = Digital.NovaNaoEncontrada();

            Parallel.ForEach(_identificadoresDeDigital, async(identificadorDigital, estadoLoop) =>
            {
                var resultado = await identificadorDigital.IdentificarAsync(comando.Template);
                if (resultado.EhSucesso)
                {
                    digital = resultado.Sucesso;
                    estadoLoop.Break();
                }
            });
            tempoIdentificacao.Stop();
            return(digital.Id == 0
                    ? Resultado <Digital, Falha> .NovaFalha(Falha.Nova(404, "Digitão não encontrada"))
                    : Resultado <Digital, Falha> .NovoSucesso(digital));
        }
コード例 #12
0
        private byte[] criaPacoteDados(byte checkSumCabecalho, Digital digital)
        {
            byte[] requisicao = new byte[] { 0x01, 0x20, 0x03 }; // bytes fixos
            String dedoAux    = digital.template1.Substring(6);  // desconsidera os 3 primeiros bytes (fixados acima)

            dedoAux   += digital.template2;
            requisicao = ProtocolUtils.merge(requisicao, Conversor.hexStringToByteArray(dedoAux));
            byte checksum = ProtocolUtils.getChecksum(ProtocolUtils.merge(requisicao, new byte[] { checkSumCabecalho, Convert.ToByte(CommandCodes.END) }));

            requisicao = ProtocolUtils.merge(requisicao, new byte[] { checksum });
            return(requisicao);
        }
コード例 #13
0
 void CreateDigital()
 {
     Digital = new Digital();
     for (int i = 0; i < mCountD; i++)
     {
         int index = (mCountA + i + 2);
         Digital.Add(new DigitalData()
         {
             Data = ReadDigital(i),
             Name = mConfig[index][1]
         });
     }
 }
コード例 #14
0
        public QuantityDimension Invert()
        {
            QuantityDimension qd = new QuantityDimension();

            qd.Mass              = Mass.Invert();
            qd.Length            = Length.Invert();
            qd.Time              = Time.Invert();
            qd.ElectricCurrent   = ElectricCurrent.Invert();
            qd.Temperature       = Temperature.Invert();
            qd.AmountOfSubstance = AmountOfSubstance.Invert();
            qd.LuminousIntensity = LuminousIntensity.Invert();
            qd.Currency          = Currency.Invert();
            qd.Digital           = Digital.Invert();
            return(qd);
        }
コード例 #15
0
        public OMSSCADACommon.Responses.Response ReadAll()
        {
            Console.WriteLine("Response ReadAll");

            // to do:
            // while (!Database.IsConfigurationRunning)

            List <ProcessVariable> pvs = dbContext.GetProcessVariable().ToList();

            OMSSCADACommon.Responses.Response response = new OMSSCADACommon.Responses.Response();

            foreach (ProcessVariable pv in pvs)
            {
                switch (pv.Type)
                {
                case VariableTypes.DIGITAL:
                    Digital digital = (Digital)pv;
                    response.Variables.Add(new DigitalVariable()
                    {
                        VariableType = ResponseVarType.Digital, Id = digital.Name, State = (OMSSCADACommon.States)digital.State
                    });
                    break;

                case VariableTypes.ANALOG:
                    Analog analog = (Analog)pv;
                    // to do: fix this
                    response.Variables.Add(new AnalogVariable()
                    {
                        VariableType = ResponseVarType.Analog, Id = analog.Name, Value = analog.AcqValue, UnitSymbol = "w"
                    });
                    break;


                case VariableTypes.COUNTER:
                    Counter counter = (Counter)pv;
                    response.Variables.Add(new CounterVariable()
                    {
                        VariableType = ResponseVarType.Counter, Id = counter.Name, Value = counter.Value
                    });
                    break;
                }
            }

            response.ResultMessage = ResultMessage.OK;

            return(response);
        }
コード例 #16
0
        /// <summary>
        /// 处理光照传感器数据
        /// </summary>
        /// <param name="num">在线数</param>
        /// <param name="index">索引</param>
        /// <param name="data">数据</param>
        /// <param name="type">传感器类型</param>
        /// <returns></returns>
        private int ProcessIllumination(int num, int index, byte[] data, int type)
        {
            for (int i = 0; i < num; i++)
            {
                Digital digital = new Digital();
                digital.Id = Convert.ToString(data[index++], 16);
                double value = data[index++] << 8 | data[index++];
                digital.Value        = value + " lx";
                digital.Name         = "光照";
                digital.Type         = type;
                digital.Online       = value == 0 ? StateType.Offline : StateType.Online;
                digital.State        = value != 0 ? StateType.StateOpen : StateType.StateClose;
                digital.Controllable = false;
                Sensors.Add(digital);
            }

            return(index);
        }
コード例 #17
0
 // Up中したか
 protected virtual bool innerHoldUp(Digital d)
 {
     if (d == Digital.LL && !Input.GetKey(KeyCode.LeftArrow))
     {
         return(true);
     }
     else if (d == Digital.LR && !Input.GetKey(KeyCode.RightArrow))
     {
         return(true);
     }
     else if (d == Digital.LU && !Input.GetKey(KeyCode.UpArrow))
     {
         return(true);
     }
     else if (d == Digital.LD && !Input.GetKey(KeyCode.DownArrow))
     {
         return(true);
     }
     return(true);
 }
コード例 #18
0
        public static ReadData BurstRFFE(NIDigital niDigital, RegisterData regData, string pinName,
                                         RFFECommand rffeCommand, TriggerConfiguration triggerConfig)
        {
            //Check data is valid
            rffeCommand.ValidateLogic(regData);

            //Create source and capture waveforms in driver
            CreateRFFEWaveforms(niDigital, pinName, rffeCommand);

            //Create dynamic source waveform data for selected command
            rffeCommand.CreateSourceData(regData, out uint[] sourceData, out int byteCount);
            niDigital.SourceWaveforms.WriteBroadcast(rffeCommand.SourceName, sourceData);

            //reg0 set based on amount of bytes used
            niDigital.PatternControl.WriteSequencerRegister("reg0", byteCount);

            //Burst pattern based on the input trigger settings
            Digital.InitiatePatternGeneration(niDigital, rffeCommand.SourceName, triggerConfig);

            //On read calls only, return capture data
            return(new ReadData());
        }
コード例 #19
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (typeCase_ == TypeOneofCase.Digital)
            {
                hash ^= Digital.GetHashCode();
            }
            if (typeCase_ == TypeOneofCase.Analog)
            {
                hash ^= Analog.GetHashCode();
            }
            if (Pin != 0)
            {
                hash ^= Pin.GetHashCode();
            }
            hash ^= (int)typeCase_;
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
コード例 #20
0
    // Start is called before the first frame update
    void Start()
    {
        consolas = new Consolas[8];

        consolas[0] = new Ps4("Playstation 4 - ", Ps4.Type.Playstation_4, 1800);

        consolas[1] = new Ps4("Playstation 1 - ", Ps4.Type.Playstation_1, 340);

        consolas[2] = new Ps4("Playstation 2 - ", Ps4.Type.Playstation_2, 1000);

        consolas[3] = new Xbox("Xbox 360 - ", Xbox.Type.Xbox_360, 1000);

        consolas[4] = new Xbox("Xbox One - ", Xbox.Type.Xbox_one, 1036);

        consolas[5] = new Nintendo("Nintendo 64 - ", Nintendo.Type.Nintendo_64, 130);

        consolas[6] = new Nintendo("Nintendo 3DS - ", Nintendo.Type.Nintendo_3DS, 278);

        consolas[7] = new Nintendo("Nintendo switch - ", Nintendo.Type.Nintendo_Switch, 1500);

        juegos = new Juegos[6];

        juegos[0] = new Digital("Assasins Creed 3 - ", Digital.Plataforma.Playstation_Store, 130);

        juegos[1] = new Fisico("Dragon ball - ", Fisico.Local.MasGamer, 150);

        juegos[2] = new Digital("Animal Crossing - ", Digital.Plataforma.Eshop, 200);

        juegos[3] = new Fisico("Smash - ", Fisico.Local.Phantom, 150);

        juegos[4] = new Digital("Halo - ", Digital.Plataforma.Xbox_Store, 150);

        juegos[5] = new Fisico("Halo 2 - ", Fisico.Local.MasGamer, 160);


        Loop();
    }
コード例 #21
0
 public bool holdDown(Digital d)
 {
     return(innerHoldDown(wired_[d]));
 }
コード例 #22
0
        public void SerializeScadaModel(string serializationTarget = "ScadaModel.xml")
        {
            string target = Path.Combine(basePath, serializationTarget);

            XElement scadaModel = new XElement("ScadaModel");

            XElement rtus     = new XElement("RTUS");
            XElement digitals = new XElement("Digitals");
            XElement analogs  = new XElement("Analogs");
            XElement counters = new XElement("Counters");

            var rtusSnapshot = dbContext.Database.RTUs.ToArray();

            foreach (var rtu in rtusSnapshot)
            {
                if (rtu.Value.Protocol == IndustryProtocols.ModbusTCP)
                {
                    XElement rtuEl = new XElement(
                        "RTU",
                        new XElement("Address", rtu.Value.Address),
                        new XElement("Name", rtu.Value.Name),
                        new XElement("FreeSpaceForDigitals", rtu.Value.FreeSpaceForDigitals),
                        new XElement("FreeSpaceForAnalogs", rtu.Value.FreeSpaceForAnalogs),
                        new XElement("Protocol", Enum.GetName(typeof(IndustryProtocols), rtu.Value.Protocol)),
                        new XElement("DigOutStartAddr", rtu.Value.DigOutStartAddr),
                        new XElement("DigInStartAddr", rtu.Value.DigInStartAddr),
                        new XElement("AnaOutStartAddr", rtu.Value.AnaOutStartAddr),
                        new XElement("AnaInStartAddr", rtu.Value.AnaInStartAddr),
                        new XElement("CounterStartAddr", rtu.Value.CounterStartAddr),
                        new XElement("NoDigOut", rtu.Value.NoDigOut),
                        new XElement("NoDigIn", rtu.Value.NoDigIn),
                        new XElement("NoAnaIn", rtu.Value.NoAnaIn),
                        new XElement("NoAnaOut", rtu.Value.NoAnaOut),
                        new XElement("NoCnt", rtu.Value.NoCnt),
                        new XElement("AnaInRawMin", rtu.Value.AnaInRawMin),
                        new XElement("AnaInRawMax", rtu.Value.AnaInRawMax),
                        new XElement("AnaOutRawMin", rtu.Value.AnaOutRawMin),
                        new XElement("AnaOutRawMax", rtu.Value.AnaOutRawMax)
                        );

                    rtus.Add(rtuEl);
                }
            }

            var pvsSnapshot = dbContext.Database.ProcessVariablesName.ToArray().OrderBy(pv => pv.Value.RelativeAddress);

            foreach (var pv in pvsSnapshot)
            {
                var rtu = rtusSnapshot.Where(kp => kp.Key == pv.Value.ProcContrName).FirstOrDefault();

                if (rtu.Value.Protocol == IndustryProtocols.ModbusTCP)
                {
                    switch (pv.Value.Type)
                    {
                    case VariableTypes.DIGITAL:

                        Digital dig = pv.Value as Digital;

                        XElement validCommands = new XElement("ValidCommands");
                        XElement validStates   = new XElement("ValidStates");

                        foreach (var state in dig.ValidStates)
                        {
                            validStates.Add(new XElement("State", Enum.GetName(typeof(States), state)));
                        }

                        foreach (var command in dig.ValidCommands)
                        {
                            validCommands.Add(new XElement("Command", Enum.GetName(typeof(CommandTypes), command)));
                        }

                        XElement digEl = new XElement(
                            "Digital",
                            new XElement("Name", dig.Name),
                            new XElement("State", dig.State),
                            new XElement("Command", dig.Command),
                            new XElement("ProcContrName", dig.ProcContrName),
                            new XElement("RelativeAddress", dig.RelativeAddress),
                            new XElement("Class", Enum.GetName(typeof(DigitalDeviceClasses), dig.Class)),
                            validCommands,
                            validStates
                            );

                        digitals.Add(digEl);

                        break;

                    case VariableTypes.ANALOG:
                        Analog analog = pv.Value as Analog;

                        XElement anEl = new XElement(
                            "Analog",
                            new XElement("Name", analog.Name),
                            new XElement("NumOfRegisters", analog.NumOfRegisters),
                            new XElement("AcqValue", analog.AcqValue),
                            new XElement("CommValue", analog.CommValue),
                            new XElement("MaxValue", analog.MaxValue),
                            new XElement("MinValue", analog.MinValue),
                            new XElement("ProcContrName", analog.ProcContrName),
                            new XElement("RelativeAddress", analog.RelativeAddress),
                            new XElement("UnitSymbol", Enum.GetName(typeof(UnitSymbol), analog.UnitSymbol))
                            );

                        analogs.Add(anEl);

                        break;
                    }
                }
            }

            scadaModel.Add(rtus);
            scadaModel.Add(digitals);
            scadaModel.Add(analogs);
            scadaModel.Add(counters);

            var xdocument = new XDocument(scadaModel);

            try
            {
                xdocument.Save(target);
                Console.WriteLine("Serializing ScadaModel succeed.");
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #23
0
        public bool DeserializeScadaModel(string deserializationSource = "ScadaModel.xml")
        {
            // to do
            Database.IsConfigurationFinished = false;

            string message           = string.Empty;
            string configurationName = deserializationSource;
            string source            = Path.Combine(basePath, configurationName);

            if (Database.Instance.RTUs.Count != 0)
            {
                Database.Instance.RTUs.Clear();
            }

            if (Database.Instance.ProcessVariablesName.Count != 0)
            {
                Database.Instance.ProcessVariablesName.Clear();
            }

            try
            {
                XElement xdocument = XElement.Load(source);

                // access RTUS, DIGITALS, ANALOGS, COUNTERS from ScadaModel root
                IEnumerable <XElement> elements = xdocument.Elements();

                var rtus     = xdocument.Element("RTUS").Elements("RTU").ToList();
                var digitals = (from dig in xdocument.Element("Digitals").Elements("Digital")
                                orderby(int) dig.Element("RelativeAddress")
                                select dig).ToList();

                var analogs = (from dig in xdocument.Element("Analogs").Elements("Analog")
                               orderby(int) dig.Element("RelativeAddress")
                               select dig).ToList();

                var counters = (from dig in xdocument.Element("Counters").Elements("Counter")
                                orderby(int) dig.Element("RelativeAddress")
                                select dig).ToList();
                // parsing RTUS
                if (rtus.Count != 0)
                {
                    foreach (var rtu in rtus)
                    {
                        RTU    newRtu;
                        string uniqueName = (string)rtu.Element("Name");

                        // if RTU with that name does not already exist?
                        if (!dbContext.Database.RTUs.ContainsKey(uniqueName))
                        {
                            byte address = (byte)(int)rtu.Element("Address");

                            bool freeSpaceForDigitals = (bool)rtu.Element("FreeSpaceForDigitals");
                            bool freeSpaceForAnalogs  = (bool)rtu.Element("FreeSpaceForAnalogs");

                            string            stringProtocol = (string)rtu.Element("Protocol");
                            IndustryProtocols protocol       = (IndustryProtocols)Enum.Parse(typeof(IndustryProtocols), stringProtocol);

                            int digOutStartAddr  = (int)rtu.Element("DigOutStartAddr");
                            int digInStartAddr   = (int)rtu.Element("DigInStartAddr");
                            int anaInStartAddr   = (int)rtu.Element("AnaInStartAddr");
                            int anaOutStartAddr  = (int)rtu.Element("AnaOutStartAddr");
                            int counterStartAddr = (int)rtu.Element("CounterStartAddr");

                            int digOutCount  = (int)rtu.Element("NoDigOut");
                            int digInCount   = (int)rtu.Element("NoDigIn");
                            int anaInCount   = (int)rtu.Element("NoAnaIn");
                            int anaOutCount  = (int)rtu.Element("NoAnaOut");
                            int counterCount = (int)rtu.Element("NoCnt");

                            ushort anaInRawMin  = (ushort)(int)rtu.Element("AnaInRawMin");
                            ushort anaInRawMax  = (ushort)(int)rtu.Element("AnaInRawMax");
                            ushort anaOutRawMin = (ushort)(int)rtu.Element("AnaOutRawMin");
                            ushort anaOutRawMax = (ushort)(int)rtu.Element("AnaOutRawMax");

                            if (digOutCount != digInCount)
                            {
                                message = string.Format("Invalid config: RTU - {0}: Value of DigOutCount must be the same as Value of DigInCount", uniqueName);
                                Console.WriteLine(message);
                                return(false);
                            }

                            newRtu = new RTU()
                            {
                                Name    = uniqueName,
                                Address = address,
                                FreeSpaceForDigitals = freeSpaceForDigitals,
                                FreeSpaceForAnalogs  = freeSpaceForAnalogs,
                                Protocol             = protocol,

                                DigOutStartAddr  = digOutStartAddr,
                                DigInStartAddr   = digInStartAddr,
                                AnaInStartAddr   = anaInStartAddr,
                                AnaOutStartAddr  = anaOutStartAddr,
                                CounterStartAddr = counterStartAddr,

                                NoDigOut = digOutCount,
                                NoDigIn  = digInCount,
                                NoAnaIn  = anaInCount,
                                NoAnaOut = anaOutCount,
                                NoCnt    = counterCount,

                                AnaInRawMin  = anaInRawMin,
                                AnaInRawMax  = anaInRawMax,
                                AnaOutRawMin = anaOutRawMin,
                                AnaOutRawMax = anaOutRawMax
                            };

                            dbContext.AddRTU(newRtu);
                        }
                        else
                        {
                            // to do: bacati exception mozda
                            message = string.Format("Invalid config: There is multiple RTUs with Name={0}!", uniqueName);
                            Console.WriteLine(message);
                            return(false);
                        }
                    }
                }
                else
                {
                    message = string.Format("Invalid config: file must contain at least 1 RTU!");
                    Console.WriteLine(message);
                    return(false);
                }

                //parsing DIGITALS. ORDER OF RELATIVE ADDRESSES IS IMPORTANT
                if (digitals.Count != 0)
                {
                    foreach (var d in digitals)
                    {
                        string procContr = (string)d.Element("ProcContrName");

                        // does RTU exists?
                        RTU associatedRtu;
                        if ((associatedRtu = dbContext.GetRTUByName(procContr)) != null)
                        {
                            Digital newDigital = new Digital();

                            // SETTING ProcContrName
                            newDigital.ProcContrName = procContr;

                            string uniqueName = (string)d.Element("Name");

                            // variable with that name does not exists in db?
                            if (!dbContext.Database.ProcessVariablesName.ContainsKey(uniqueName))
                            {
                                // SETTING Name
                                newDigital.Name = uniqueName;

                                // SETTING State
                                string stringCurrentState = (string)d.Element("State");
                                States stateValue         = (States)Enum.Parse(typeof(States), stringCurrentState);
                                newDigital.State = stateValue;

                                // SETTING Command parameter - for initializing Simulator with last command
                                string       lastCommandString = (string)d.Element("Command");
                                CommandTypes command           = (CommandTypes)Enum.Parse(typeof(CommandTypes), lastCommandString);

                                // SETTING Class
                                string digDevClass            = (string)d.Element("Class");
                                DigitalDeviceClasses devClass = (DigitalDeviceClasses)Enum.Parse(typeof(DigitalDeviceClasses), digDevClass);
                                newDigital.Class = devClass;

                                // SETTING RelativeAddress
                                ushort relativeAddress = (ushort)(int)d.Element("RelativeAddress");
                                newDigital.RelativeAddress = relativeAddress;

                                var hasCommands = d.Element("ValidCommands");
                                if (hasCommands.HasElements)
                                {
                                    var validCommands = hasCommands.Elements("Command").ToList();

                                    // SETTING ValidCommands
                                    foreach (var xElementCommand in validCommands)
                                    {
                                        string       stringCommand = (string)xElementCommand;
                                        CommandTypes validCommand  = (CommandTypes)Enum.Parse(typeof(CommandTypes), stringCommand);
                                        newDigital.ValidCommands.Add(validCommand);
                                    }
                                }
                                else
                                {
                                    message = string.Format("Invalid config: Variable = {0} does not contain commands.", uniqueName);
                                    Console.WriteLine(message);
                                    return(false);
                                }

                                var hasStates = d.Element("ValidStates");
                                if (hasStates.HasElements)
                                {
                                    var validStates = hasStates.Elements("State").ToList();

                                    // SETTING ValidStates
                                    foreach (var xElementState in validStates)
                                    {
                                        string stringState = (string)xElementState;
                                        States state       = (States)Enum.Parse(typeof(States), stringState);
                                        newDigital.ValidStates.Add(state);
                                    }
                                }
                                else
                                {
                                    message = string.Format("Invalid config: Variable = {0} does not contain states.", uniqueName);
                                    Console.WriteLine(message);
                                    return(false);
                                }

                                ushort calculatedRelativeAddres;
                                if (associatedRtu.TryMap(newDigital, out calculatedRelativeAddres))
                                {
                                    if (relativeAddress == calculatedRelativeAddres)
                                    {
                                        if (associatedRtu.MapProcessVariable(newDigital))
                                        {
                                            dbContext.AddProcessVariable(newDigital);
                                        }
                                    }
                                    else
                                    {
                                        message = string.Format("Invalid config: Variable = {0} RelativeAddress = {1} is not valid.", uniqueName, relativeAddress);
                                        Console.WriteLine(message);
                                        return(false);
                                    }
                                }
                            }
                            else
                            {
                                message = string.Format("Invalid config: Name = {0} is not unique. Variable already exists", uniqueName);
                                Console.WriteLine(message);
                                return(false);
                            }
                        }
                        else
                        {
                            message = string.Format("Invalid config: Parsing Digitals, ProcContrName = {0} does not exists.", procContr);
                            Console.WriteLine(message);
                            return(false);
                        }
                    }
                }

                // parsing ANALOGS. ORDER OF RELATIVE ADDRESSES IS IMPORTANT
                if (analogs.Count != 0)
                {
                    foreach (var a in analogs)
                    {
                        string procContr = (string)a.Element("ProcContrName");

                        // does RTU exists?
                        RTU associatedRtu;
                        if ((associatedRtu = dbContext.GetRTUByName(procContr)) != null)
                        {
                            Analog newAnalog = new Analog();

                            // SETTING ProcContrName
                            newAnalog.ProcContrName = procContr;

                            string uniqueName = (string)a.Element("Name");

                            // variable with that name does not exists in db?
                            if (!dbContext.Database.ProcessVariablesName.ContainsKey(uniqueName))
                            {
                                // SETTING Name
                                newAnalog.Name = uniqueName;

                                // SETTING NumOfRegisters
                                ushort numOfReg = (ushort)(int)a.Element("NumOfRegisters");
                                newAnalog.NumOfRegisters = numOfReg;

                                // SETTING AcqValue
                                ushort acqValue = (ushort)(float)a.Element("AcqValue");
                                newAnalog.AcqValue = acqValue;

                                // SETTING CommValue
                                ushort commValue = (ushort)(float)a.Element("CommValue");
                                newAnalog.CommValue = commValue;

                                // SETTING MinValue
                                float minValue = (float)a.Element("MinValue");
                                newAnalog.MinValue = minValue;

                                // SETTING MaxValue
                                float maxValue = (float)a.Element("MaxValue");
                                newAnalog.MaxValue = maxValue;

                                // SETTING UnitSymbol
                                string     stringUnitSymbol = (string)a.Element("UnitSymbol");
                                UnitSymbol unitSymbolValue  = (UnitSymbol)Enum.Parse(typeof(UnitSymbol), stringUnitSymbol, true);
                                newAnalog.UnitSymbol = unitSymbolValue;

                                // SETTING RelativeAddress
                                ushort relativeAddress = (ushort)(int)a.Element("RelativeAddress");
                                newAnalog.RelativeAddress = relativeAddress;

                                // svejedno je uzeli AnaInRawMin ili AnaOutRawMin -> isti su trenutni,
                                // sve dok imamo samo Analog.cs a ne AnaIn.cs + AnaOut.cs (dok je kao za digital)
                                newAnalog.RawBandLow  = associatedRtu.AnaInRawMin;
                                newAnalog.RawBandHigh = associatedRtu.AnaInRawMax;

                                // SETTING RawAcqValue and RawCommValue
                                AnalogProcessor.EGUToRawValue(newAnalog);

                                ushort calculatedRelativeAddres;
                                if (associatedRtu.TryMap(newAnalog, out calculatedRelativeAddres))
                                {
                                    if (relativeAddress == calculatedRelativeAddres)
                                    {
                                        if (associatedRtu.MapProcessVariable(newAnalog))
                                        {
                                            dbContext.AddProcessVariable(newAnalog);
                                        }
                                    }
                                    else
                                    {
                                        message = string.Format("Invalid config: Analog Variable = {0} RelativeAddress = {1} is not valid.", uniqueName, relativeAddress);
                                        Console.WriteLine(message);
                                        return(false);
                                    }
                                }
                            }
                            else
                            {
                                message = string.Format("Invalid config: Name = {0} is not unique. Analog Variable already exists", uniqueName);
                                Console.WriteLine(message);
                                return(false);
                            }
                        }
                        else
                        {
                            message = string.Format("Invalid config: Parsing Analogs, ProcContrName = {0} does not exists.", procContr);
                            Console.WriteLine(message);
                            return(false);
                        }
                    }
                }

                // to do:
                if (counters.Count != 0)
                {
                }

                Console.WriteLine("Configuration passed successfully.");
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
                return(false);
            }
            catch (XmlException e)
            {
                Console.WriteLine(e.Message);
                return(false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(false);
            }

            Database.IsConfigurationFinished = true;
            return(true);
        }
コード例 #24
0
 // キーアサインを変更する
 //  pressedBtn    : 押したキー
 //  targetBtn     : ターゲットキー
 public void wire(Digital pressedBtn, Digital targetBtn)
 {
     wireKeys_[pressedBtn] = targetBtn;
 }
コード例 #25
0
        public List <Digital> MapStatus(IList <string> data, Dictionary <string, string> Messages, HashSet <string> groups)
        {
            var FieldLength = StatusFields.Fields.Length;
            var digital     = new List <Digital>();

            try
            {
                for (int i = 0; i < data.Count; i += FieldLength)
                {
                    if (groups.Contains(data[i + 3]))
                    {
                        var status = new Digital();
                        status.LegacyName         = data[i + 30];
                        status.NewName            = data[i];
                        status.Remote             = data[i + 1];
                        status.dataset            = data[i + 2];
                        status.Group              = data[i + 3];
                        status.Station            = data[i + 4];
                        status.Message            = data[i + 5];
                        status.PriorityDisplay    = data[i + 6];
                        status.SafetyRelatedPoint = data[i + 7];
                        status.NumberOfInputBits  = Convert.ToInt32(data[i + 8]);
                        status.CoordinatesBit1    = data[i + 9];
                        status.BitNumberBit1      = Convert.ToInt32(data[i + 10]);
                        status.NormallyOpenBit1   = data[i + 11];
                        status.CoordinatesBit2    = data[i + 12];
                        status.BitNumberBit2      = Convert.ToInt32(data[i + 13]);
                        status.NormallyOpenBit2   = data[i + 14];
                        status.HasOutput          = data[i + 15];
                        status.HasInput           = data[i + 16];
                        status.OutputCoordinates1 = data[i + 17];
                        if (data[i + 15].Equals("yes"))
                        {
                            if (data[i + 29].Equals(""))
                            {
                                status.CommandType1 = Helper.ReturnValFromDictionary(data[i + 5] + "1", Messages);
                                status.CommandType2 = Helper.ReturnValFromDictionary(data[i + 5] + "2", Messages);
                            }
                            else
                            {
                                status.CommandType1 = Helper.ReturnValFromDictionary(data[i + 29] + "1", Messages);
                                status.CommandType2 = Helper.ReturnValFromDictionary(data[i + 29] + "2", Messages);
                            }
                        }
                        status.OutputType1        = data[i + 18];
                        status.Command1           = data[i + 19];
                        status.Timeout1           = Convert.ToInt32(data[i + 20]);
                        status.OutputCoordinates2 = data[i + 21];
                        status.OutputType2        = data[i + 22];
                        status.Command2           = data[i + 23];
                        status.Timeout2           = Convert.ToInt32(data[i + 24]);
                        status.Description        = data[i + 25];
                        status.ScanBlock          = Convert.ToInt16(data[i + 26]);
                        status.CIP              = data[i + 27];
                        status.ABCIPDataType    = data[i + 28];
                        status.OutputMessage    = data[i + 29];
                        status.DisplayOrder     = Convert.ToInt32(data[i + 31]);
                        status.ShortDescription = data[i + 32];

                        digital.Add(status);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return(digital);
        }
コード例 #26
0
 // 丁度Upした?
 public bool justUp(Digital d)
 {
     return(innerJustUp(wired_[d]));
 }
コード例 #27
0
        /// <summary>
        /// Processing answers from Simulator - Process Controller
        /// </summary>
        public void ProcessPCAnwers(TimeSpan timeout, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                bool           isSuccessful;
                IORequestBlock answer = IORequests.DequeueAnswer(out isSuccessful, timeout);

                if (isSuccessful)
                {
                    bool isChange = false;
                    RTU  rtu;
                    // sporno
                    //while (!Database.IsConfigurationRunning)

                    if ((rtu = dbContext.GetRTUByName(answer.ProcessControllerName)) != null)
                    {
                        switch (rtu.Protocol)
                        {
                        case IndustryProtocols.ModbusTCP:

                            ModbusHandler mdbHandler = new ModbusHandler();
                            try
                            {
                                mdbHandler.UnpackData(answer.RcvBuff, answer.RcvMsgLength);
                                switch (mdbHandler.Response.FunCode)
                                {
                                case FunctionCodes.ReadDiscreteInput:
                                {
                                    BitReadResponse response        = (BitReadResponse)mdbHandler.Response;
                                    var             responsePVCount = answer.Flags;

                                    ushort varAddr = answer.ReqAddress;
                                    for (int i = 0; i < responsePVCount; i++, varAddr++)
                                    {
                                        ProcessVariable pv;

                                        if (rtu.GetProcessVariableByAddress(varAddr, out pv))
                                        {
                                            Digital target = (Digital)pv;

                                            try
                                            {
                                                bool isOpened = response.BitValues[i];
                                                if (target.State != target.ValidStates[isOpened ? 1 : 0])
                                                {
                                                    isChange     = true;
                                                    target.State = target.ValidStates[isOpened ? 1 : 0];
                                                    Console.WriteLine(" CHANGE! Digital variable {0}, state: {1}", target.Name, target.State);

                                                    DMSClient dMSClient = new DMSClient();
                                                    dMSClient.ChangeOnSCADADigital(target.Name, target.State);
                                                }
                                            }
                                            catch
                                            {
                                                Console.WriteLine("Digital variable {0}, state: INVALID", target.Name);
                                            }
                                        }
                                    }
                                    if (isChange)
                                    {
                                        ScadaModelParser parser = new ScadaModelParser();
                                        parser.SerializeScadaModel();
                                    }
                                }

                                break;

                                // analog input
                                case FunctionCodes.ReadInputRegisters:
                                {
                                    RegisterReadResponse response = (RegisterReadResponse)mdbHandler.Response;
                                    var responsePVCount           = answer.Flags;

                                    ushort varAddr = answer.ReqAddress;
                                    for (int i = 0; i < responsePVCount; i++, varAddr++)
                                    {
                                        ProcessVariable pv;

                                        if (rtu.GetProcessVariableByAddress(varAddr, out pv))
                                        {
                                            Analog target = (Analog)pv;

                                            try
                                            {
                                                ushort newRawAcqValue = response.RegValues[target.RelativeAddress];
                                                float  newAcqValue;
                                                AnalogProcessor.RawValueToEGU(target, newRawAcqValue, out newAcqValue);

                                                if (target.AcqValue != newAcqValue)
                                                {
                                                    isChange = true;

                                                    target.RawAcqValue = newRawAcqValue;
                                                    target.AcqValue    = newAcqValue;
                                                    Console.WriteLine(" CHANGE! Analog variable {0}, AcqValue: {1}", target.Name, target.AcqValue);

                                                    //to do: propagacija analogih promena(ako se secate Pavlica je prvo rekao da nam to ne treba da samo jednom zakucamo vrednost na pocetku) xD
                                                    DMSClient dMSClient = new DMSClient();
                                                    dMSClient.ChangeOnSCADAAnalog(target.Name, target.AcqValue);
                                                }
                                            }
                                            catch
                                            {
                                                // Console.WriteLine("Digital variable {0}, state: INVALID", target.Name);
                                            }
                                        }
                                    }
                                    if (isChange)
                                    {
                                        ScadaModelParser parser = new ScadaModelParser();
                                        parser.SerializeScadaModel();
                                    }
                                }

                                break;
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                            break;
                        }
                    }
                }
            }

            Console.WriteLine("ProcessPCAnswers.shutdown=true");
            return;
        }
コード例 #28
0
        /// <summary>
        /// Send Commands to simulator, to make its state consistent with RTDB
        /// </summary>
        public void InitializeSimulator()
        {
            // ovo probati sa taskovima, za svaki od rtu-ova. ipak ne, jer nekim promenljivim komandujes, nekim ne
            // var rtus = dbContext.GettAllRTUs();

            //Parallel.ForEach(rtus, (currentRtu, state) =>
            //{
            //    Console.WriteLine("InitSim Parallel.foreach RTU name = {0}, Therad id = {1} started", currentRtu.Key, Thread.CurrentThread.ManagedThreadId);
            //    IIndustryProtocolHandler IProtHandler = null;
            //    RTU rtu = dbContext.GetRTUByName(currentRtu.Key);
            //    if (currentRtu.Value != null)
            //    {
            //        IORequestBlock iorb = new IORequestBlock()
            //        {
            //            RequestType = RequestType.SEND,
            //            ProcessControllerName = currentRtu.Key
            //        };

            //        switch (rtu.Protocol)
            //        {
            //            case IndustryProtocols.ModbusTCP:
            //                IProtHandler = new ModbusHandler()
            //                {
            //                    Header = new ModbusApplicationHeader
            //                    {
            //                        TransactionId = 0,
            //                        ProtocolId = (ushort)IndustryProtocols.ModbusTCP,
            //                        DeviceAddress = rtu.Address,
            //                        Length = 5
            //                    },
            //                    Request = new WriteRequest()
            //                };
            //                break;
            //        }

            //        //to do. praviti nove iorbove
            //        // za svaku varijablu trebas imati should command ili ne i u zavisnosti od toga puniti data, racunati length  zahtvea i ostalo
            //        //-------------analogs---------------
            //        var analogs = dbContext.GetProcessVariable().Where(pv => pv.Type == VariableTypes.ANALOG && pv.IsInit == false &&
            //                                                            pv.ProcContrName.Equals(currentRtu.Key)).OrderBy(pv => pv.RelativeAddress);
            //        int requestCount = analogs.ToList().Count();
            //        if (requestCount != 0)
            //        {
            //            ProcessVariable firstPV = analogs.FirstOrDefault();
            //            iorb.ReqAddress = (ushort)rtu.GetAcqAddress(firstPV);

            //            if (IProtHandler != null)
            //            {
            //                switch (rtu.Protocol)
            //                {
            //                    case IndustryProtocols.ModbusTCP:


            //                        for(int i = 0; i < requestCount; i++)
            //                        {

            //                        }
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).FunCode = FunctionCodes.ReadInputRegisters;
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).Quantity = (ushort)requestCount;
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).StartAddr = iorb.ReqAddress;
            //                        break;
            //                }

            //                iorb.Flags = requestCount;
            //                iorb.SendBuff = IProtHandler.PackData();
            //                iorb.SendMsgLength = iorb.SendBuff.Length;
            //                IORequests.EnqueueRequest(iorb);
            //            }
            //        }

            //        //-------------digitals---------------(to do: add init flag...)
            //        var digitals = dbContext.GetProcessVariable().Where(pv => pv.Type == VariableTypes.DIGITAL &&
            //                                                            pv.ProcContrName.Equals(currentRtu.Key)).OrderBy(pv => pv.RelativeAddress);
            //        requestCount = digitals.ToList().Count();
            //        if (requestCount != 0)
            //        {
            //            ProcessVariable firstPV = digitals.FirstOrDefault();
            //            iorb.ReqAddress = (ushort)rtu.GetAcqAddress(firstPV);

            //            if (IProtHandler != null)
            //            {
            //                switch (rtu.Protocol)
            //                {
            //                    case IndustryProtocols.ModbusTCP:

            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).FunCode = FunctionCodes.ReadDiscreteInput;
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).Quantity = (ushort)requestCount;
            //                        ((ReadRequest)((ModbusHandler)IProtHandler).Request).StartAddr = iorb.ReqAddress;
            //                        break;
            //                }

            //                iorb.Flags = requestCount;
            //                iorb.SendBuff = IProtHandler.PackData();
            //                iorb.SendMsgLength = iorb.SendBuff.Length;
            //                IORequests.EnqueueRequest(iorb);
            //            }
            //        }
            //    }
            //});

            List <ProcessVariable> pvs = dbContext.GetProcessVariable().ToList();

            if (pvs.Count != 0)
            {
                foreach (ProcessVariable pv in pvs)
                {
                    IORequestBlock iorb = new IORequestBlock()
                    {
                        RequestType           = RequestType.SEND,
                        ProcessControllerName = pv.ProcContrName
                    };

                    RTU rtu;
                    if ((rtu = dbContext.GetRTUByName(pv.ProcContrName)) != null)
                    {
                        iorb.ReqAddress = (ushort)rtu.GetCommandAddress(pv);
                        bool shouldCommand = false;

                        switch (rtu.Protocol)
                        {
                        case IndustryProtocols.ModbusTCP:

                            ModbusHandler mdbHandler = new ModbusHandler();
                            mdbHandler.Header = new ModbusApplicationHeader()
                            {
                                TransactionId = 0,
                                Length        = 5,
                                ProtocolId    = (ushort)IndustryProtocols.ModbusTCP,
                                DeviceAddress = rtu.Address
                            };

                            mdbHandler.Request = new WriteRequest()
                            {
                                StartAddr = (ushort)rtu.GetCommandAddress(pv)
                            };

                            switch (pv.Type)
                            {
                            // initialy, on simulator all digitals are set to 0 -> closed state
                            case VariableTypes.DIGITAL:
                                Digital digital = (Digital)pv;

                                CommandTypes comm;
                                if (shouldCommand = CommandValidator.InitialCommandingForDigital(digital, out comm))
                                {
                                    mdbHandler.Request.FunCode = FunctionCodes.WriteSingleCoil;
                                    ((WriteRequest)mdbHandler.Request).Value = (ushort)comm;
                                }
                                break;

                            case VariableTypes.ANALOG:
                                Analog analog = (Analog)pv;

                                if (shouldCommand = AnalogProcessor.InitialWorkPointAnalog(analog))
                                {
                                    mdbHandler.Request.FunCode = FunctionCodes.WriteSingleRegister;
                                    ((WriteRequest)mdbHandler.Request).Value = (ushort)analog.RawCommValue;
                                }
                                analog.IsInit = true;
                                break;

                            case VariableTypes.COUNTER:
                                Counter counter = (Counter)pv;

                                break;
                            }

                            if (shouldCommand)
                            {
                                iorb.SendBuff      = mdbHandler.PackData();
                                iorb.SendMsgLength = iorb.SendBuff.Length;
                                //if (pv.Name == "MEAS_AN_1")
                                //    Console.WriteLine(BitConverter.ToString(iorb.SendBuff, 0, 12));
                            }

                            break;
                        }

                        if (shouldCommand)
                        {
                            IORequests.EnqueueRequest(iorb);
                        }
                    }
                    else
                    {
                        // izbrisati omdah te procesne varijable sa rtu-om tog imena?
                        Console.WriteLine("Invalid config: ProcContrName = {0} does not exists.", pv.ProcContrName);
                        continue;
                    }
                }
            }
        }
コード例 #29
0
        public virtual TaskMonitorModel Run(String Id)
        {
            TaskModel Task = tasks[Id];

            if (Task != null)
            {
                PCRTaskSettingsModel Settings = Task.Settings as PCRTaskSettingsModel;
                TaskMonitorModel     Monitor  = new TaskMonitorModel(Task);
                Digital Detector = new Digital();

                try
                {
                    Detector.Port = Settings.SerialPortNumer;
                    Detector.Open();
                    Detector.Connect();
                    if (Detector.IsConnected)
                    {
                        Task.State = TaskState.RUNNING;
                        Monitor.Logs.Add(new LogRecordModel("Connect successfully", LogLevel.INFO));
                        Monitor.Logs.Add(new LogRecordModel("Board SN:" + Detector.BoardSN, LogLevel.INFO));
                        Monitor.Logs.Add(new LogRecordModel("Board temperature:" + Detector.BoardTemperature, LogLevel.INFO));
                        Detector.MethodType       = Settings.MethodType;
                        Detector.MethodCycles     = Settings.MethodCycles;
                        Detector.MethodCycletime  = Settings.MethodCycleTime;
                        Detector.MethodDarkSignal = Settings.MethodDarkSignal;
                        Detector.StartMethod();

                        Monitor.StartTime = DateTime.Now;
                        Monitor.Logs.Add(new LogRecordModel("Task Started", LogLevel.INFO));
                        while (Detector.IsMethodRunning)
                        {
                            StringBuilder values = new StringBuilder();
                            values.Append("OnValue1:" + Detector.OnValue1 + ",OffValue1:" + Detector.OffValue1);
                            values.Append(";OnValue2:" + Detector.OnValue2 + ",OffValue2:" + Detector.OffValue2);
                            values.Append(";OnValue3:" + Detector.OnValue3 + ",OffValue3:" + Detector.OffValue3);
                            Monitor.Logs.Add(new LogRecordModel(values.ToString(), LogLevel.INFO));
                        }
                        Detector.StopMethod();
                        Task.State      = TaskState.DONE;
                        Monitor.EndTime = DateTime.Now;
                        Monitor.Logs.Add(new LogRecordModel("Task finished", LogLevel.INFO));
                    }
                    else
                    {
                        Monitor.Logs.Add(new LogRecordModel("Can not connect to device", LogLevel.ERROR));
                        Task.State = TaskState.ERROR;
                    }
                }
                catch (Exception e)
                {
                    Monitor.Logs.Add(new LogRecordModel("Task failed due to:" + e.Message, LogLevel.ERROR));
                    Task.State = TaskState.ERROR;
                }
                finally
                {
                    Detector.Disconnect();
                    Detector.Close();
                }
                return(Monitor);
            }
            return(null);
        }
コード例 #30
0
        public OMSSCADACommon.Responses.Response WriteSingleDigital(string id, CommandTypes command)
        {
            Console.WriteLine("WriteSingleDigital!");

            Digital digital = null;

            OMSSCADACommon.Responses.Response response = new OMSSCADACommon.Responses.Response();

            // sporno
            //while (!Database.IsConfigurationRunning)

            // getting PV from db
            ProcessVariable pv;

            if (dbContext.GetProcessVariableByName(id, out pv))
            {
                digital = (Digital)pv;
            }

            // does this ID exist in the database
            if (digital == null)
            {
                response.ResultMessage = ResultMessage.INVALID_ID;
                return(response);
            }

            // is this a valid command for this digital device
            if (!CommandValidator.ValidateDigitalCommand(digital, command))
            {
                response.ResultMessage = ResultMessage.INVALID_DIG_COMM;
                return(response);
            }


            RTU rtu;

            if ((rtu = dbContext.GetRTUByName(digital.ProcContrName)) != null)
            {
                IORequestBlock iorb = new IORequestBlock()
                {
                    RequestType           = RequestType.SEND,
                    ProcessControllerName = digital.ProcContrName
                };

                iorb.ReqAddress = (ushort)rtu.GetCommandAddress(digital);

                switch (rtu.Protocol)
                {
                case IndustryProtocols.ModbusTCP:

                    ModbusHandler mdbHandler = new ModbusHandler
                    {
                        Header = new ModbusApplicationHeader()
                        {
                            TransactionId = 0,
                            Length        = 5,
                            ProtocolId    = (ushort)IndustryProtocols.ModbusTCP,
                            DeviceAddress = rtu.Address
                        },

                        Request = new WriteRequest()
                        {
                            FunCode   = FunctionCodes.WriteSingleCoil,
                            StartAddr = (ushort)rtu.GetCommandAddress(digital),
                            Value     = (ushort)command
                        }
                    };

                    iorb.SendBuff      = mdbHandler.PackData();
                    iorb.SendMsgLength = iorb.SendBuff.Length;
                    break;
                }

                IORequests.EnqueueRequest(iorb);
                Console.WriteLine("enqued {0}", BitConverter.ToString(iorb.SendBuff, 0, 12));

                digital.Command = command;

                response.ResultMessage = ResultMessage.OK;
            }
            else
            {
                // rtu does not exist
            }

            return(response);
        }
コード例 #31
0
ファイル: MainWindow.xaml.cs プロジェクト: Szandal/Szyfrator
        private void DecryptButton_Click(object sender, RoutedEventArgs e)
        {
            string inputText;

            if (inputField.IsEnabled == false)
            {
                inputText = fileContent;
            }
            else
            {
                inputText = inputField.Text.ToString();
            }
            string outText = string.Empty;

            switch (chooseType.Text)
            {
            case "Cezar":
                Cesar cesar = new Cesar();
                int   shift = GetShiftValue();
                if (shift == -1)
                {
                    break;
                }
                outText = cesar.Encryption(inputText, -shift);
                break;

            case "Kaczor":
                Kaczor duck = new Kaczor();
                outText = duck.Decryption(inputText);
                break;

            case "Morse'a":
                Morse morse = new Morse();
                outText = morse.Decrytption(inputText);
                break;

            case "Liczbowy":
                Numeric numeric = new Numeric();
                outText = numeric.Decrytption(inputText);
                break;

            case "Cyfrowy":
                Digital digital    = new Digital();
                int     shiftDigit = GetShiftValue();
                if (shiftDigit == -1)
                {
                    break;
                }
                string password;
                var    dialog = new InputBoxForNumericPass("Podaj hasło numeryczne");
                if (dialog.ShowDialog() == true)
                {
                    password = dialog.answer.Text.ToString();
                }
                else
                {
                    break;
                }
                outText = digital.Decryption(inputText, GetShiftValue(), password);
                break;

            case "Zamiennikowy":
                Zamiennikowy zamiennikowy = new Zamiennikowy();
                string       key          = GetEncryptKeyFromComboBox();
                if (key.Equals("Wybierz Klucz..."))
                {
                    break;
                }
                outText = zamiennikowy.Encryption(inputText, key);
                break;
            }
            if (inputField.IsEnabled != false)
            {
                outputField.Text = outText;
            }
            else
            {
                EncryptFile encryptFile = new EncryptFile();
                encryptFile.SaveNewFile(outText);
                SetEnableTextBox();
            }
        }