Пример #1
0
 public JPLCConnection(string ipAddress, int rack, int slot)
 {
     IPAddress = ipAddress;
     Rack      = rack;
     Slot      = slot;
     S7Api     = new S7Client();
 }
Пример #2
0
        public ServerClientTestBase() : base()
        {
            client = new S7Client();
            var rc = client.ConnectTo(Localhost, 0, 2);

            rc.ShouldBe(0);
        }
Пример #3
0
 public PlcNetInterface(string ipAddress, int rack, int slot)
 {
     IpAddress = ipAddress;
     Rack      = rack;
     Slot      = slot;
     _s7Plc    = new S7Client();
 }
Пример #4
0
 static bool Check(S7Client a_Client, int Result, string FunctionPerformed)
 {
     Debug.Log("+-----------------------------------------------------\n" +
               "| " + FunctionPerformed + "\n" +
               "+-----------------------------------------------------");
     if (Result == 0)
     {
         int ExecTime = a_Client.ExecTime();
         Debug.Log("| Result         : OK");
         Debug.Log("| Execution time : " + ExecTime.ToString() + " ms"); //+ Client.getex->ExecTime());
         Debug.Log("+-----------------------------------------------------");
     }
     else
     {
         Debug.Log("| ERROR !!! \n");
         if (Result < 0)
         {
             Debug.Log("| Library Error (-1)\n");
         }
         else
         {
             Debug.Log("| " + a_Client.ErrorText(Result));
         }
         Debug.Log("+-----------------------------------------------------\n");
     }
     return(Result == 0);
 }
Пример #5
0
        static void Main(string[] args)
        {
            Server = new S7Server();
            Client = new S7Client();

            Server.RegisterArea(S7Server.srvAreaDB, 1, DB1, DB1.Length);
            Server.RegisterArea(S7Server.srvAreaDB, 2, DB2, DB2.Length);
            Server.RegisterArea(S7Server.srvAreaDB, 3, DB3, DB2.Length);
            int errorcode = Server.Start();

            Client.SetConnectionParams("127.0.0.1", 0, 2);
            Client.Connect();
            Client.DBWrite(2, 0, 4, new byte[] { 1, 2, 3, 4 });
            byte[] b = new byte[4];

            S7Client.S7CpuInfo info = new S7Client.S7CpuInfo();
            Client.GetCpuInfo(ref info);
            Console.WriteLine(info.ASName);
            Console.WriteLine(Client.Connected());
            Console.WriteLine(errorcode);
            byte[] buffer = new byte[4];
            int    i      = Client.DBRead(2, 0, 4, buffer);

            Console.ReadLine();
        }
Пример #6
0
 public S7PlcService()
 {
     _client         = new S7Client();
     _timer          = new System.Timers.Timer();
     _timer.Interval = 100;
     _timer.Elapsed += OnTimerElapsed;
 }
Пример #7
0
        /// <summary>
        /// 自动步骤
        /// </summary>
        /// <param name="client"></param>
        /// <param name="dbNum"></param>
        /// <param name="dbByteLength"></param>
        /// <param name="dbStartElement"></param>
        /// <returns></returns>
        public static string[] ReadAutoStep(S7Client client, int dbNum, int dbByteLength, int dbStartElement)
        {
            // int dbInt;
            // dbInt = S7.GetIntAt(ReadBuffer, Convert.ToInt16(element));
            // value = "" + dbInt;

            //double dbLReal = S7.GetLRealAt(ReadBuffer, 94);//读取Real位置在94
            //txtReadServoPos.Text = dbLReal.ToString();

            result = client.DBRead(dbNum, 0, dbByteLength, ReadBuffer);//dbNum from 0 length dbByteLength byte
            int dbInt = S7.GetIntAt(ReadBuffer, dbStartElement);

            for (int i = 1; i <= strAutoSteps.Length; i++)
            {
                if (i == dbInt)
                {
                    strAutoStep[0] = strAutoSteps[i - 1];//当前步骤
                    if (i == strAutoSteps.Length)
                    {
                        strAutoStep[1] = strAutoSteps[0];                          //下一步骤
                    }
                    else
                    {
                        strAutoStep[1] = strAutoSteps[i];
                    }
                }
            }
            return(strAutoStep);
        }
Пример #8
0
        private void ResetHkConfigLoad()
        {
            S7Client client = new S7Client();

            int restultClient = client.ConnectTo("192.168.0.1", 0, 0);

            if (restultClient == 0)
            {
                Console.WriteLine("Connected to PLC");
            }
            else
            {
                Console.WriteLine(client.ErrorText(restultClient));
            }

            byte[] writeBuffer = new byte[1];
            int    startIndex  = 32;

            S7.SetBitAt(ref writeBuffer, 0, 0, false);

            int result = client.WriteArea(S7Consts.S7AreaDB, 1, startIndex * 8 + 1, 1, S7Consts.S7WLBit, writeBuffer);

            if (result != 0)
            {
                Console.WriteLine("Error: " + client.ErrorText(result));
            }

            client.Disconnect();
        }
Пример #9
0
        public void WriteCableNok()
        {
            S7Client client = new S7Client();

            int restultClient = client.ConnectTo("192.168.0.1", 0, 0);

            if (restultClient == 0)
            {
                Console.WriteLine("Connected to PLC");
            }
            else
            {
                Console.WriteLine(client.ErrorText(restultClient));
                return;
            }

            byte[] writeBuffer = new byte[1];
            int    startIndex  = 32;

            S7.SetBitAt(ref writeBuffer, 0, 1, true);

            int result = client.WriteArea(S7Consts.S7AreaDB, 1, startIndex * 8 + 4, 1, S7Consts.S7WLBit, writeBuffer);

            if (result != 0)
            {
                Console.WriteLine("Error: " + client.ErrorText(result));
            }

            client.Disconnect();
        }
Пример #10
0
        public override object Read(plcdb_lib.Models.Model.TagsRow t)
        {
            if (!Client.Connected())
            {
                int connResult = Client.ConnectTo(ControllerInfo.Address, (int)ControllerInfo.s7_rack, (int)ControllerInfo.s7_slot);
                if (connResult != 0)
                {
                    Log.Error(GetErrorText(connResult));
                    Client.Disconnect();
                    Client = null;
                    Client = new S7Client();
                    throw new EntryPointNotFoundException("Unable to connect to PLC " + ControllerInfo.Name);
                }
                bgReadThread.DoWork      -= ReadFromPLC;
                bgReadThread.DoWork      += ReadFromPLC;
                RefreshDataTimer.Interval = 1000;
                RefreshDataTimer.Elapsed -= RefreshDataTimer_Elapsed;
                RefreshDataTimer.Elapsed += RefreshDataTimer_Elapsed;
                RefreshDataTimer.Start();
            }

            SiemensTag Tag = ActiveTags.FirstOrDefault(p => p.TagRow.PK == t.PK);

            if (Tag == null)
            {
                Tag = new SiemensTag()
                {
                    TagRow = t
                };
                ActiveTags.Add(Tag);
            }
            return(Tag.TagRow.CurrentValue);
        }
Пример #11
0
        public ReceivedResult Readdata(S7Client p_objClient)
        {
            // DateTime dytNow = NextRequestAt;
            if (NextRequestAt <= DateTime.Now)
            {
                ReceivedResult Result = new ReceivedResult();

                Result.ErrorNumber = p_objClient.ReadArea(ObjectConfigure.AreaOfMemory, ObjectConfigure.DbNumber,
                                                          ObjectConfigure.StartOffset, 1, ObjectConfigure.WorldLen, BufferData);

                ShowResult(Result.ErrorNumber, p_objClient); // debug

                if (Result.ErrorNumber == 0)
                {
                    NextRequestAt     = NextRequestAt.AddMilliseconds(ObjectConfigure.PeriodOfCheck);
                    Result.ResultData = GetValueOfTypeFromPlc();
                    Result.ID_COM     = Id;
                    return(Result);
                }

                ErrorManager(Result.ErrorNumber); // chyba v komunikaci/CPU nebo jiná
            }

            return(null); // ShowResult(LastError, p_objClient); // debug - > null
        }
Пример #12
0
        static void Main(string[] args)
        {
            // Default for S7-1500
            int rack = 0, slot = 1;

            // Get program parameters
            if ((args.Length != 1) && (args.Length != 3))
            {
                Usage();
                return;
            }
            if (args.Length == 3)
            {
                rack = Convert.ToInt32(args[1]);
                slot = Convert.ToInt32(args[2]);
            }

            Client = new S7Client();

            if (PlcConnect(args[0], rack, slot))
            {
                Console.WriteLine("PLC is connected");
                PerformTasks();
                Client.Disconnect();
            }
            else
            {
                Console.WriteLine("Cannot connect");
            }
        }
Пример #13
0
        public int PCtoPLC()
        {
            this.Client   = new S7Client();
            this.dbBuffer = new byte[214];

            int result = this.Client.ConnectTo(plcConnection, Rack, Slot);

            if (result != 0)
            {
                throw new Exception(Client.ErrorText(result));
            }

            S7.SetCharsAt(this.dbBuffer, 0, this.Codice);
            S7.SetCharsAt(this.dbBuffer, 50, this.Articolo);
            S7.SetIntAt(this.dbBuffer, 100, (short)this.PzLotto);
            S7.SetBitAt(ref this.dbBuffer, 104, this.ControlWord, true);
            S7.SetIntAt(this.dbBuffer, 106, (short)this.Velocita);
            S7.SetCharsAt(this.dbBuffer, 108, this.Avviso);
            S7.SetBitAt(ref this.dbBuffer, 208, this.Guasto, true);
            S7.SetIntAt(this.dbBuffer, 212, (short)this.WatchDog);

            result = this.Client.DBWrite(30, 0, this.dbBuffer.Length, this.dbBuffer);
            if (result != 0)
            {
                throw new Exception(Client.ErrorText(result));
            }
            else
            {
                return(200);
            }
        }
Пример #14
0
        public ServerClientTestBase() : base()
        {
            client = new S7Client("Test Plc");
            var rc = client.ConnectTo(Localhost, 0, 2);

            rc.ShouldBe(Sharp7.S7Consts.ResultOK);
        }
Пример #15
0
 public Connetting()
 {
     Rack        = Convert.ToInt32(0);
     Slot        = Convert.ToInt32(1);
     dbBuffer    = new byte[224];
     this.Client = new S7Client();
 }
Пример #16
0
        public void WriteOutput(int startIndex, int offset, bool on)
        {
            try
            {
                S7Client client = new S7Client();

                int restultClient = client.ConnectTo("192.168.0.1", 0, 0);

                if (restultClient == 0)
                {
                    Console.WriteLine("Connected to PLC");
                }
                else
                {
                    Console.WriteLine(client.ErrorText(restultClient));
                    return;
                }

                byte[] writeBuffer = new byte[1];

                S7.SetBitAt(ref writeBuffer, 0, 1, on);

                int result = client.WriteArea(S7Consts.S7AreaDB, 1, startIndex * 8 + offset, 1, S7Consts.S7WLBit, writeBuffer);
                if (result != 0)
                {
                    Console.WriteLine("Error: " + client.ErrorText(result));
                }

                client.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Write output: " + ex.Message);
            }
        }
Пример #17
0
        /// <summary>
        /// Mark sure client is initialized.
        /// </summary>
        /// <param name="component"></param>
        private void CheckClientAndValues(SmartComponent component)
        {
            if (client == null)
            {
                client = new S7Client();
                Disconnect(component);
            }

            int diCount = (int)component.Properties["DI_Number"].Value;

            if (diCount != bDI_AddressIsValid.Length)            // When just loaded array is not initialized
            {
                UpdateDICount(component, diCount);
            }
            int doCount = (int)component.Properties["DO_Number"].Value;

            if (doCount != bDO_AddressIsValid.Length)            // When just loaded array is not initialized
            {
                UpdateDOCount(component, doCount);
            }

            for (int i = 0; i < component.Properties.Count; ++i)
            {
                component.Properties[i].ValidateValue(component.Properties[i].Value);
            }
        }
Пример #18
0
        public void WriteData(byte type, byte datatype, int DBNumber, int Start, int Length, ref byte [] WriteData)// 主进程用
        {
            int Result;
            int SizeRead = 0;

            Client = new S7Client();
            // UserConfig 是配置config.cs 里面的读取函数
            UserConfig.ReadAppSettings("IP", out string IP);
            {
                Result = Client.ConnectTo(IP, 0, 0);
                try
                {
                    // Result = Client.WriteArea(S7Consts.S7AreaDB, address, start, lenth, S7Consts.S7WLReal, WriteData, ref SizeRead);
                    Result = Client.WriteArea(type, DBNumber, Start, Length, datatype, WriteData, ref SizeRead);

                    if (Result == 0)
                    {
                        MessageBox.Show("写入成功");
                    }
                    else
                    {
                        MessageBox.Show(Client.ErrorText(Result));
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    //TxtDump.Text = "ok2";
                }
            }
        }
Пример #19
0
 /// <summary>
 /// 清除气缸信号颜色
 /// </summary>
 /// <param name="ellipses"></param>
 /// <param name="client"></param>
 public static void ClearValveSignals(S7Client client, ref Ellipse[] ellipses)
 {
     for (int i = 0; i < listEllipse.Count; i++)
     {
         listEllipse[i].Fill = gray;
     }
 }
Пример #20
0
        public void PlcHasNoIp()
        {
            var client = new S7Client();

            client.PLCIpAddress.ShouldBeNull();
            string.IsNullOrEmpty(client.PLCIpAddress).ShouldBeTrue();
        }
Пример #21
0
        public static double ReadWeldingCurrent(S7Client client)
        {
            result = client.DBRead(1024, 0, 8, ReadBuffer);
            double dbCurrent = S7.GetDIntAt(ReadBuffer, 4);

            return(dbCurrent);
        }
Пример #22
0
        public void PlcToStringWithNameAndIp()
        {
            var client = new S7Client("Test");

            client.SetConnectionParams("1.2.3.4", 0, 0);
            client.ToString().ShouldBe("PLC [email protected]");
        }
Пример #23
0
        public MainStan()
        {
            InitializeComponent();

            clientStan = new S7Client();
            StatusStan = ClientStatus.cStopped;
        }
Пример #24
0
        public void PlcHasNoName()
        {
            var client = new S7Client();

            client.Name.ShouldBeNull();
            string.IsNullOrEmpty(client.Name).ShouldBeTrue();
        }
Пример #25
0
    //-------------------------------------------------------------------------
    // Main
    //-------------------------------------------------------------------------
    public static void Main(string[] args)
    {
        int Rack = 0, Slot = 2; // default for S7300

        // Uncomment next line if you are not able to see
        // the entire test text. (Note : Doesn't work in Mono 2.10)

        // Console.SetBufferSize(80, Int16.MaxValue-1);

        // Get Progran args
        if ((args.Length != 1) && (args.Length != 3))
        {
            Usage();
            return;
        }
        if (args.Length == 3) // only address without rack and slot
        {
            Rack = Convert.ToInt32(args[1]);
            Slot = Convert.ToInt32(args[2]);
        }
        // Client creation
        Client = new S7Client();
        // Try Connection
        if (PlcConnect(args[0], Rack, Slot))
        {
            PerformTests();
            Client.Disconnect();
        }
        // Prints a short summary
        Summary();
        Console.ReadKey();
    }
Пример #26
0
 public BufferedPLCConnector(S7Client client, int aluminiumProp, int seconds)
 {
     _client        = client;
     _aluminiumProp = aluminiumProp;
     _seconds       = seconds;
     _bufferDb      = new byte[455];
 }
Пример #27
0
        //protected S7PlcClient(S7Client s7Client, bool autoReconnect = true)
        //{
        //    //TODO: The ip address, rack and slot are missing when the object creating from here.
        //    _s7Client = s7Client;
        //    if (autoReconnect)
        //    {
        //        _plcReconnector = new PlcAutoConnector(this);
        //    }
        //}

        public bool Connect()
        {
            try
            {
                _s7Client             = new S7Client(Name);
                _s7Client.ConnTimeout = 1000;
                _s7Client.RecvTimeout = 1000;
                _s7Client.SendTimeout = 1000;

                if (_s7Client.ConnectTo(IpAddress, Rack, Slot) == S7Consts.ResultOK)
                {
                    Connected = true;
                    return(true);
                }
                else
                {
                    Disconnect();
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Disconnect();
                return(false);
            }
        }
Пример #28
0
        public Task InitializeAsync()
        {
            try
            {
                sharp7         = new S7Client();
                sharp7.PLCPort = this.port;

                var subscription =
                    ConnectionState
                    .Where(state => state == Enums.ConnectionState.ConnectionLost)
                    .Take(1)
                    .SelectMany(_ => Reconnect())
                    .RepeatAfterDelay(ReconnectDelay)
                    .LogAndRetry(Logger, "Error while reconnecting to S7.")
                    .Subscribe();

                disposables.Add(subscription);
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex, StringResources.StrErrorS7DriverCouldNotBeInitialized);
            }

            return(Task.FromResult(true));
        }
Пример #29
0
        public void Connection()
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                //-------------- Create and connect the client
                client = new S7Client();
                int result = client.ConnectTo(IP, Rack, Slot);
                if (result == 0)
                {
                    Console.WriteLine("Connected to 127.0.0.1");
                    _IsConnected = true;
                }
                else
                {
                    _IsConnected = false;
                    Console.WriteLine(client.ErrorText(result));

                    return;
                }

                stopwatch.Stop();
            }
            catch (SocketException ex)
            {
                stopwatch.Stop();

                EventscadaException?.Invoke(this.GetType().Name, string.Format("Could Not Connect to Server : {0} Time: {1}", ex.SocketErrorCode,
                                                                               stopwatch.ElapsedTicks));
            }
        }
Пример #30
0
        static void Main(string[] args)
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);


            //-------------- Create and connect the client
            var client  = new S7Client();
            int result1 = client.ConnectTo("192.168.11.95", 0, 1);

            if (result1 == 0)
            {
                Console.WriteLine("Connected to 192.168.11.95");
            }
            else
            {
                Console.WriteLine(client.ErrorText(result1));
                Console.ReadKey();
                return;
            }

            //ReadDB1005(client);
            //Console.WriteLine("----------------");
            ReadInput(client);

            //client.Disconnect();



            Console.ReadLine();
        }