コード例 #1
0
        public static void Main(string[] args)
        {
            bool running = true;

            // use Ctrl-C to stop the programm
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
                e.Cancel = true;
                running  = false;
            };

            string hostname = "localhost";
            int    tcpPort  = 2404;

            if (args.Length > 0)
            {
                hostname = args [0];
            }

            if (args.Length > 1)
            {
                int.TryParse(args [1], out tcpPort);
            }

            // Setup virtual serial port
            TcpClientVirtualSerialPort port = new TcpClientVirtualSerialPort(hostname, tcpPort);

            port.Start();

            // Setup balanced CS101 master
            LinkLayerParameters llParameters = new LinkLayerParameters();

            llParameters.AddressLength    = 1;
            llParameters.UseSingleCharACK = false;

            CS101Master master = new CS101Master(port, LinkLayerMode.BALANCED, llParameters);

            master.DebugOutput  = false;
            master.OwnAddress   = 1;
            master.SlaveAddress = 2;
            master.SetASDUReceivedHandler(asduReceivedHandler, null);
            master.SetLinkLayerStateChangedHandler(linkLayerStateChanged, null);
            master.SetReceivedRawMessageHandler(rcvdRawMessageHandler, null);

            long lastTimestamp = SystemUtils.currentTimeMillis();

            // This will start a separate thread!
            // alternativley you can you master.Run() inside the loop
            master.Start();

            while (running)
            {
                if ((SystemUtils.currentTimeMillis() - lastTimestamp) >= 5000)
                {
                    lastTimestamp = SystemUtils.currentTimeMillis();

                    if (master.GetLinkLayerState() == lib60870.linklayer.LinkLayerState.AVAILABLE)
                    {
                        master.SendInterrogationCommand(CauseOfTransmission.ACTIVATION, 1, 20);
                    }
                    else
                    {
                        Console.WriteLine("Link layer: " + master.GetLinkLayerState().ToString());
                    }
                }
            }

            master.Stop();

            port.Stop();
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: zhenghongzhi/lib60870.NET
        public static void Main(string[] args)
        {
            bool running = true;

            // use Ctrl-C to stop the programm
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
                e.Cancel = true;
                running  = false;
            };

            string portName = "/dev/ttyUSB3";

            if (args.Length > 0)
            {
                portName = args [0];
            }

            SerialPort port = new SerialPort();

            port.PortName  = portName;
            port.BaudRate  = 9600;
            port.Parity    = Parity.Even;
            port.Handshake = Handshake.None;
            port.Open();
            port.DiscardInBuffer();

            /* set link layer address length */
            LinkLayerParameters llParameters = new LinkLayerParameters();

            llParameters.AddressLength = 1;

            /* unbalanced mode allows multiple slaves on a single serial line */
            CS101Master master = new CS101Master(port, LinkLayerMode.UNBALANCED, llParameters);

            master.DebugOutput = false;
            master.SetASDUReceivedHandler(asduReceivedHandler, null);

            master.SetLinkLayerStateChangedHandler(linkLayerStateChanged, null);

            master.AddSlave(1);
            master.AddSlave(2);

            long lastTimestamp = SystemUtils.currentTimeMillis();

            master.SlaveAddress = 1;
            //master.GetFile (1, 30000, NameOfFile.TRANSPARENT_FILE, new Receiver ());


            while (running)
            {
                master.PollSingleSlave(1);

                master.Run();

                master.PollSingleSlave(2);

                master.Run();

                if ((SystemUtils.currentTimeMillis() - lastTimestamp) >= 5000)
                {
                    lastTimestamp = SystemUtils.currentTimeMillis();

                    try {
                        master.SlaveAddress = 1;
                        master.SendInterrogationCommand(CauseOfTransmission.ACTIVATION, 1, 20);
                    }
                    catch (LinkLayerBusyException) {
                        Console.WriteLine("Slave 1: Link layer busy or not ready");
                    }

                    try {
                        master.SlaveAddress = 2;
                        master.SendInterrogationCommand(CauseOfTransmission.ACTIVATION, 2, 20);
                    }
                    catch (LinkLayerBusyException) {
                        Console.WriteLine("Slave 2: Link layer busy or not ready");
                    }
                }
            }

            port.Close();
        }
コード例 #3
0
        public static void Main(string[] args)
        {
            bool running = true;

            // use Ctrl-C to stop the programm
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
                e.Cancel = true;
                running  = false;
            };

            string portName = "/dev/ttyUSB1";

            if (args.Length > 0)
            {
                portName = args [0];
            }

            // Setup serial port
            SerialPort port = new SerialPort();

            port.PortName  = portName;
            port.BaudRate  = 9600;
            port.Parity    = Parity.Even;
            port.Handshake = Handshake.None;
            port.Open();
            port.DiscardInBuffer();

            // Setup balanced CS101 master
            LinkLayerParameters llParameters = new LinkLayerParameters();

            llParameters.AddressLength    = 1;
            llParameters.UseSingleCharACK = false;

            CS101Master master = new CS101Master(port, LinkLayerMode.BALANCED, llParameters);

            master.DebugOutput  = false;
            master.OwnAddress   = 1;
            master.SlaveAddress = 2;
            master.SetASDUReceivedHandler(asduReceivedHandler, null);
            master.SetLinkLayerStateChangedHandler(linkLayerStateChanged, null);
            master.SetReceivedRawMessageHandler(rcvdRawMessageHandler, null);

            long lastTimestamp = SystemUtils.currentTimeMillis();

            // This will start a separate thread!
            // alternativley you can you master.Run() inside the loop
            master.Start();

            while (running)
            {
                if ((SystemUtils.currentTimeMillis() - lastTimestamp) >= 5000)
                {
                    lastTimestamp = SystemUtils.currentTimeMillis();

                    if (master.GetLinkLayerState() == lib60870.linklayer.LinkLayerState.AVAILABLE)
                    {
                        master.SendInterrogationCommand(CauseOfTransmission.ACTIVATION, 1, 20);
                    }
                    else
                    {
                        Console.WriteLine("Link layer: " + master.GetLinkLayerState().ToString());
                    }
                }
            }

            master.Stop();

            port.Close();
        }
コード例 #4
0
        public static void Main(string[] args)
        {
            Log("{json:scada} IEC60870-5-101 Driver - Copyright 2020 RLO");
            Log("Driver version " + DriverVersion);
            Log("Using lib60870.NET version " +
                LibraryCommon.GetLibraryVersionString());

            if (args.Length > 0) // first argument in number of the driver instance
            {
                int  num;
                bool res = int.TryParse(args[0], out num);
                if (res)
                {
                    ProtocolDriverInstanceNumber = num;
                }
            }
            if (args.Length > 1) // second argument is logLevel
            {
                int  num;
                bool res = int.TryParse(args[1], out num);
                if (res)
                {
                    LogLevel = num;
                }
            }

            string fname = JsonConfigFilePath;

            if (args.Length > 2) // third argument is config file name
            {
                if (File.Exists(args[2]))
                {
                    fname = args[2];
                }
            }
            if (!File.Exists(fname))
            {
                fname = JsonConfigFilePathAlt;
            }
            if (!File.Exists(fname))
            {
                Log("Missing config file " + JsonConfigFilePath);
                Environment.Exit(-1);
            }

            Log("Reading config file " + fname);
            string json = File.ReadAllText(fname);

            JSConfig = JsonSerializer.Deserialize <JSONSCADAConfig>(json);
            if (
                JSConfig.mongoConnectionString == "" ||
                JSConfig.mongoConnectionString == null
                )
            {
                Log("Missing MongoDB connection string in JSON config file " +
                    fname);
                Environment.Exit(-1);
            }
            // Log("MongoDB connection string: " + JSConfig.mongoConnectionString);
            if (
                JSConfig.mongoDatabaseName == "" ||
                JSConfig.mongoDatabaseName == null
                )
            {
                Log("Missing MongoDB database name in JSON config file " +
                    fname);
                Environment.Exit(-1);
            }
            Log("MongoDB database name: " + JSConfig.mongoDatabaseName);
            if (JSConfig.nodeName == "" || JSConfig.nodeName == null)
            {
                Log("Missing nodeName parameter in JSON config file " +
                    fname);
                Environment.Exit(-1);
            }
            Log("Node name: " + JSConfig.nodeName);

            // connect to MongoDB Database server
            var Client = ConnectMongoClient(JSConfig);
            var DB     = Client.GetDatabase(JSConfig.mongoDatabaseName);

            // read and process instances configuration
            var collinsts =
                DB
                .GetCollection
                <protocolDriverInstancesClass
                >(ProtocolDriverInstancesCollectionName);
            var instances =
                collinsts
                .Find(inst =>
                      inst.protocolDriver == ProtocolDriverName &&
                      inst.protocolDriverInstanceNumber ==
                      ProtocolDriverInstanceNumber &&
                      inst.enabled == true)
                .ToList();
            var foundInstance = false;

            foreach (protocolDriverInstancesClass inst in instances)
            {
                if (
                    ProtocolDriverName == inst.protocolDriver &&
                    ProtocolDriverInstanceNumber ==
                    inst.protocolDriverInstanceNumber
                    )
                {
                    foundInstance = true;
                    if (!inst.enabled)
                    {
                        Log("Driver instance [" +
                            ProtocolDriverInstanceNumber.ToString() +
                            "] disabled!");
                        Environment.Exit(-1);
                    }
                    Log("Instance: " +
                        inst.protocolDriverInstanceNumber.ToString());
                    var nodefound = false;
                    foreach (var name in inst.nodeNames)
                    {
                        if (JSConfig.nodeName == name)
                        {
                            nodefound = true;
                        }
                    }
                    if (!nodefound)
                    {
                        Log("Node '" +
                            JSConfig.nodeName +
                            "' not found in instances configuration!");
                        Environment.Exit(-1);
                    }
                    DriverInstance = inst;
                    break;
                }
                break; // process just first result
            }
            if (!foundInstance)
            {
                Log("Driver instance [" +
                    ProtocolDriverInstanceNumber +
                    "] not found in configuration!");
                Environment.Exit(-1);
            }

            // read and process connections configuration for this driver instance
            var collconns =
                DB
                .GetCollection
                <IEC10X_connection>(ProtocolConnectionsCollectionName);
            var conns =
                collconns
                .Find(conn =>
                      conn.protocolDriver == ProtocolDriverName &&
                      conn.protocolDriverInstanceNumber ==
                      ProtocolDriverInstanceNumber &&
                      conn.enabled == true)
                .ToList();

            foreach (IEC10X_connection isrv in conns)
            {
                IEC10Xconns.Add(isrv);
                Log(isrv.name.ToString() + " - New Connection");
            }
            if (IEC10Xconns.Count == 0)
            {
                Log("No connections found!");
                Environment.Exit(-1);
            }

            // start thread to process redundancy control
            Thread thrMongoRedundacy =
                new Thread(() =>
                           ProcessRedundancyMongo(JSConfig));

            thrMongoRedundacy.Start();

            // start thread to update acquired data to database
            Thread thrMongo =
                new Thread(() =>
                           ProcessMongo(JSConfig));

            thrMongo.Start();

            // start thread to watch for commands in the database using a change stream
            Thread thrMongoCmd =
                new Thread(() =>
                           ProcessMongoCmd(JSConfig));

            thrMongoCmd.Start();

            Log("Setting up IEC Connections & ASDU handlers...");
            int cntIecSrv = 0;

            foreach (IEC10X_connection srv in IEC10Xconns)
            {
                TcpClientVirtualSerialPort virtualPort = null;
                SerialPort port = null;
                if (srv.portName.Contains(":"))
                {
                    var hostport = srv.portName.Split(":");
                    virtualPort = new TcpClientVirtualSerialPort(hostport[0], System.Convert.ToInt32(hostport[1]));
                    if (LogLevel >= LogLevelDebug)
                    {
                        virtualPort.DebugOutput = true;
                    }
                    virtualPort.Start();
                }
                else
                {
                    port          = new SerialPort();
                    port.PortName = srv.portName;
                    port.BaudRate = srv.baudRate;
                    switch (srv.parity.ToLower())
                    {
                    default:     // Even is the starndard parity for 101
                    case "even":
                        port.Parity = Parity.Even;
                        break;

                    case "none":
                        port.Parity = Parity.None;
                        break;

                    case "odd":
                        port.Parity = Parity.Odd;
                        break;

                    case "mark":
                        port.Parity = Parity.Mark;
                        break;

                    case "space":
                        port.Parity = Parity.Space;
                        break;
                    }
                    switch (srv.stopBits.ToLower())
                    {
                    default:
                    case "one":
                        port.StopBits = StopBits.One;
                        break;

                    case "one5":
                    case "onepointfive":
                        port.StopBits = StopBits.OnePointFive;
                        break;

                    case "two":
                        port.StopBits = StopBits.Two;
                        break;
                    }
                    switch (srv.handshake.ToLower())
                    {
                    default:
                    case "none":
                        port.Handshake = Handshake.None;
                        break;

                    case "xon":
                    case "xonxoff":
                        port.Handshake = Handshake.XOnXOff;
                        break;

                    case "rts":
                    case "requesttosend":
                        port.Handshake = Handshake.RequestToSend;
                        break;

                    case "rtsxon":
                    case "requesttosendxonxoff":
                        port.Handshake = Handshake.RequestToSendXOnXOff;
                        break;
                    }
                    port.Open();
                    port.DiscardInBuffer();
                }

                LinkLayerParameters llParameters = new LinkLayerParameters();
                llParameters.AddressLength    = srv.sizeOfLinkAddress;
                llParameters.TimeoutForACK    = srv.timeoutForACK;
                llParameters.TimeoutRepeat    = srv.timeoutRepeat;
                llParameters.UseSingleCharACK = srv.useSingleCharACK;

                ApplicationLayerParameters alpars = new ApplicationLayerParameters();
                alpars.SizeOfCOT = srv.sizeOfCOT;
                alpars.SizeOfCA  = srv.sizeOfCA;
                alpars.SizeOfIOA = srv.sizeOfIOA;
                alpars.OA        = srv.localLinkAddress;

                CS101Master master;
                if (port != null)
                {
                    Log("Serial Port: " + srv.portName);
                    master =
                        new CS101Master(port,
                                        LinkLayerMode.UNBALANCED,
                                        llParameters,
                                        alpars);
                }
                else
                {
                    Log("Virtual Serial Port: " + srv.portName);
                    master =
                        new CS101Master(virtualPort,
                                        LinkLayerMode.UNBALANCED,
                                        llParameters,
                                        alpars);
                }
                // master.OwnAddress = srv.localLinkAddress;
                master.SetTimeouts(srv.timeoutMessage, srv.timeoutCharacter);
                master.AddSlave(srv.remoteLinkAddress);
                master.SlaveAddress = srv.remoteLinkAddress;

                srv.master         = master;
                srv.CntGI          = srv.giInterval - 5;
                srv.CntTestCommand = srv.testCommandInterval - 2;
                srv.CntTimeSync    = srv.timeSyncInterval;
                if (LogLevel >= LogLevelDebug)
                {
                    master.DebugOutput = true;
                }
                master.SetASDUReceivedHandler(AsduReceivedHandlerPre, cntIecSrv);
                master.SetLinkLayerStateChangedHandler(linkLayerStateChanged, cntIecSrv);
                master.SetReceivedRawMessageHandler(rcvdRawMessageHandler, cntIecSrv);
                master.Start();

                // create timer to increment counters each second
                srv.TimerCnt          = new System.Timers.Timer();
                srv.TimerCnt.Interval = 1000;
                srv.TimerCnt.Elapsed += (sender, e) => MyElapsedMethod(sender, e, srv);