Example #1
0
        private void btConnect_Click(object sender, EventArgs e)
        {
            btConnect.Enabled = false;
            AmsAddress serverAddress = null;             //服务器的ADS地址

            try
            {
                if (tbPort.Text.StartsWith("0x") || tbPort.Text.StartsWith("0X"))
                {
                    string temp = tbPort.Text.Substring(2);
                    serverAddress = new AmsAddress(tbNetID.Text, Int32.Parse(temp, System.Globalization.NumberStyles.HexNumber));
                }
                else
                {
                    serverAddress = new AmsAddress(tbNetID.Text, Int32.Parse(tbPort.Text));
                }
            }
            catch
            {
                MessageBox.Show("ADS Port 或 NetID 输入有误!");
                return;
            }
            try
            {
                _tcClient.Connect(serverAddress.NetId, serverAddress.Port);
                lbOutput.Items.Add("端口" + _tcClient.ClientAddress.Port + "打开成功!");
                lbOutput.SelectedIndex = lbOutput.Items.Count - 1;
            }
            catch
            {
                MessageBox.Show("连接服务器失败!");
            }
        }
Example #2
0
        internal void SwitchTarget()
        {
            AmsAddress address = this._sender;

            this._sender = this._target;
            this._target = address;
        }
        /*
         * Connect the client to the local AMS router
         */

        private void btConnect_Click(object sender, EventArgs e)
        {
            AmsAddress serverAddress = null;

            try
            {
                // check if port is a hex value
                if (tbPort.Text.StartsWith(("0x")) || tbPort.Text.StartsWith(("0X")))
                {
                    string sHexValue = tbPort.Text.Substring(2);
                    serverAddress = new AmsAddress(tbNetId.Text, Int32.Parse(sHexValue, System.Globalization.NumberStyles.HexNumber));
                }
                // interpret as dec value
                else
                {
                    serverAddress = new AmsAddress(tbNetId.Text, Int32.Parse(tbValue.Text));
                }
            }
            catch
            {
                MessageBox.Show("Invalid AMS NetId or Ams port");
                return;
            }

            try
            {
                _tcClient.Connect(serverAddress.NetId, serverAddress.Port);
                lbOutput.Items.Add("Client port " + _tcClient.ClientPort + " opened");
                lbOutput.SelectedIndex = lbOutput.Items.Count - 1;
            }
            catch
            {
                MessageBox.Show("Could not connect client");
            }
        }
Example #4
0
 public TcAdsSyncPort(AmsAddress addr, TcLocalSystem localSystem, INotificationReceiver iNoteReceiver, bool clientCycle, bool synchronize)
 {
     object[] args = new object[] { this._id, addr };
     using (new MethodTrace("Id: {0:d}, Address = {1}", args))
     {
         this._localSystem   = localSystem;
         this._iNoteReceiver = iNoteReceiver;
         if (!base.IsLocalNetId(addr.netId, localSystem.NetId))
         {
             base.address = addr.Clone();
         }
         else
         {
             base.address = new AmsAddress(localSystem.NetId, addr.port);
             this._bLocal = true;
         }
         this._bSynchronize        = synchronize;
         this._bClientCycle        = clientCycle;
         this._adsStateHandle      = 0;
         this._symbolVersionHandle = 0;
         this._symbolTable         = new SymbolTable(this);
         if (synchronize)
         {
             this._routerSyncWindow = new SyncWindow(this);
         }
     }
 }
        private void ServiceRequest(Protocol.AdsContext context)
        {
            Protocol.AdsResponse response = context.Response;
            switch (response.Command)
            {
            case Protocol.AdsCommand.Read:
                base.AdsReadRes(AmsAddress.Parse(context.Route), context.InvokeID, MapError(response.Error), response.Payload == null ? 0 : (uint)response.Payload.Length, response.Payload);
                break;

            case Protocol.AdsCommand.Write:
                base.AdsWriteRes(AmsAddress.Parse(context.Route), context.InvokeID, MapError(response.Error));
                break;

            case Protocol.AdsCommand.ReadWrite:
                base.AdsReadWriteRes(AmsAddress.Parse(context.Route), context.InvokeID, MapError(response.Error), response.Payload == null ? 0 : (uint)response.Payload.Length, response.Payload);
                break;

            default:
                break;
            }
            if (_pendingRequests.ContainsKey(context.InvokeID))
            {
                _pendingRequests.Remove(context.InvokeID);
            }
        }
 public ControllerConnectionFactory(AmsAddress address)
 {
     if (address == null)
     {
         throw new ArgumentNullException();
     }
     _address = address;
 }
Example #7
0
        public AdsErrorCode AdsDelDeviceNotificationRes(AmsAddress rAddr, uint invokeId, AdsErrorCode result)
        {
            TcAdsDelDeviceNotificationResHeader adsHeader = new TcAdsDelDeviceNotificationResHeader {
                _result = result
            };

            return(this.AdsResponse(rAddr, invokeId, 7, 0, adsHeader, null));
        }
Example #8
0
        public AdsErrorCode AdsDelDeviceNotificationReq(AmsAddress rAddr, uint invokeId, uint hNotification)
        {
            TcAdsDelDeviceNotificationReqHeader adsHeader = new TcAdsDelDeviceNotificationReqHeader {
                _notificationHandle = hNotification
            };

            return(this.AdsRequest(rAddr, invokeId, 7, 0, adsHeader, null));
        }
Example #9
0
        public AdsErrorCode AdsWriteRes(AmsAddress rAddr, uint invokeId, AdsErrorCode result)
        {
            TcAdsWriteResHeader adsHeader = new TcAdsWriteResHeader {
                _result = result
            };

            return(this.AdsResponse(rAddr, invokeId, 3, 0, adsHeader, null));
        }
Example #10
0
        protected override void OnBound(IBinder binder)
        {
            IAdsBinder binder2 = binder as IAdsBinder;

            if (binder2 != null)
            {
                this.imageBaseAddress = binder2.ImageBaseAddress;
            }
        }
Example #11
0
        public AdsErrorCode AdsAddDeviceNotificationRes(AmsAddress rAddr, uint invokeId, AdsErrorCode result, uint handle)
        {
            TcAdsAddDeviceNotificationResHeader adsHeader = new TcAdsAddDeviceNotificationResHeader {
                _result             = result,
                _notificationHandle = handle
            };

            return(this.AdsResponse(rAddr, invokeId, 6, 0, adsHeader, null));
        }
        private void btnLoad_Click(object sender, System.EventArgs e)
        {
            treeViewSymbols.Nodes.Clear();
            //check adr info
            AmsAddress serverAddress = null;

            try
            {
                // check if port is a hex value
                if (tbAdsPort.Text.StartsWith(("0x")) || tbAdsPort.Text.StartsWith(("0X")))
                {
                    string sHexValue = tbAdsPort.Text.Substring(2);
                    serverAddress = new AmsAddress(tbNetID.Text, Int32.Parse(sHexValue, System.Globalization.NumberStyles.HexNumber));
                }
                // interpret as dec value
                else
                {
                    serverAddress = new AmsAddress(tbNetID.Text, Int32.Parse(tbAdsPort.Text));
                }
            }
            catch
            {
                MessageBox.Show("Invalid AMS NetId " + tbNetID.Text + " or Ams port " + tbAdsPort.Text + "!");
                return;
            }
            //connect
            try
            {
                //orig for just 127.0...: adsClient.Connect(Convert.ToInt32(tbAdsPort.Text));
                adsClient.Connect(serverAddress.NetId, serverAddress.Port);
                symbolLoader = adsClient.CreateSymbolInfoLoader();

                if (!cbFlat.Checked)
                {
                    TcAdsSymbolInfo symbol = symbolLoader.GetFirstSymbol(true);
                    while (symbol != null)
                    {
                        treeViewSymbols.Nodes.Add(CreateNewNode(symbol));
                        symbol = symbol.NextSymbol;
                    }
                }
                else
                {
                    foreach (TcAdsSymbolInfo symbol in symbolLoader)
                    {
                        TreeNode node = new TreeNode(symbol.Name);
                        node.Tag = symbol;
                        treeViewSymbols.Nodes.Add(node);
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
Example #13
0
 internal TcAmsHeader(TcMarshallableAmsHeader mHeader)
 {
     this._target     = new AmsAddress(mHeader.targetNetId, mHeader.targetPort);
     this._sender     = new AmsAddress(mHeader.senderNetId, mHeader.senderPort);
     this._commandId  = mHeader.cmdId;
     this._stateFlags = mHeader.stateFlags;
     this._cbData     = mHeader.cbData;
     this._errCode    = mHeader.errCode;
     this._hUser      = mHeader.hUser;
 }
Example #14
0
        public AdsErrorCode AdsReadReq(AmsAddress rAddr, uint invokeId, uint indexGroup, uint indexOffset, uint cbLength)
        {
            TcAdsReadReqHeader adsHeader = new TcAdsReadReqHeader {
                _indexGroup  = indexGroup,
                _indexOffset = indexOffset,
                _cbLength    = cbLength
            };

            return(this.AdsRequest(rAddr, invokeId, 2, 0, adsHeader, null));
        }
Example #15
0
        public AdsErrorCode AdsReadStateRes(AmsAddress rAddr, uint invokeId, AdsErrorCode result, AdsState adsState, ushort deviceState)
        {
            TcAdsReadStateResHeader adsHeader = new TcAdsReadStateResHeader {
                _result      = result,
                _adsState    = (ushort)adsState,
                _deviceState = deviceState
            };

            return(this.AdsResponse(rAddr, invokeId, 4, 0, adsHeader, null));
        }
Example #16
0
        private void ConnectAds()
        {
            _tcClient = new TcAdsClient();

            string     netid         = "5.39.221.128.1.1";
            int        net_port      = 0x8888;
            AmsAddress serverAddress = new AmsAddress(netid, net_port); //配置服务端地址

            _tcClient.Connect(serverAddress.NetId, serverAddress.Port); //连接服务端
        }
Example #17
0
        public AdsErrorCode AdsDeviceNotificationReq(AmsAddress rAddr, uint invokeId, uint numStampHeaders, TcAdsStampHeader[] notificationHeaders)
        {
            TcAdsDeviceNotificationReqHeader adsHeader = new TcAdsDeviceNotificationReqHeader {
                _numStamps = numStampHeaders
            };

            byte[] adsData = TcAdsParser.BuildDeviceNotificationBuffer(notificationHeaders);
            adsHeader._cbData = (uint)adsData.Length;
            return(this.AdsRequest(rAddr, invokeId, 8, (uint)adsData.Length, adsHeader, adsData));
        }
Example #18
0
 internal TcAmsHeader(AmsAddress target, AmsAddress sender, ushort commandId, ushort stateFlags, uint cbData, uint errCode, uint hUser)
 {
     this._target     = target;
     this._sender     = sender;
     this._commandId  = commandId;
     this._stateFlags = stateFlags;
     this._cbData     = cbData;
     this._errCode    = errCode;
     this._hUser      = hUser;
 }
Example #19
0
        public ADSClient(String AMSAddress, Boolean IsBeckhoff, int NumberOfKids)
        {
            Client.Timeout = 1000;
            AmsAddress g = new AmsAddress(AMSAddress, 851);

            try
            {
                Client.Connect(AMSAddress, 851);
                // TcAdsSymbolInfoLoader ld = Client.CreateSymbolInfoLoader();

                TimeOutSwitch = Client.CreateVariableHandle("MAIN.TimeOutSwitch");
                DeadMan       = Client.CreateVariableHandle("MAIN.Joystick1DeadMan");
                FaultReset    = Client.CreateVariableHandle("Main.GlobalReset");
                GlobalEstop   = Client.CreateVariableHandle("Main.GlobalEstopActive");
                //MomControl = Client.CreateVariableHandle("MAIN.Execute");
                Connected = true;
                // TcADSSI = Client.CreateSymbolInfoLoader().GetSymbols(true);
                //    ROS = Client.CreateSymbolLoader(TwinCAT.SymbolsLoadMode.Flat).Symbols;
            }
            catch
            {
                Connected = false;
                throw;
            }
            Client.Timeout = 500;
            Kids           = new AdsKid[NumberOfKids];

            for (int x = 1; x <= NumberOfKids; x++)
            {
                Kids[x - 1] = new AdsKid(Client, x);
            }

            //   TcAdsSymbolInfoCollection ADSSI = Client.CreateSymbolInfoLoader().GetSymbols(false);
            // DeviceInfo DI = Client.ReadDeviceInfo();
            //StateInfo SI = Client.ReadState();



            this.IsBeckhoff = IsBeckhoff;


            ParamHandles = new int[]
            {
                TargetX,
                TargetY,
                PosAccel,
                //PosDecel,
                PosVel,
                //MotCmd,
                //StartBit,
                CurX,
                CurY,
                CurSpeed
            };
        }
Example #20
0
        private async Task <Unit> SendNotification(AmsAddress target, AmsAddress sender, byte[] data)
        {
            await server.AmsSendAsync(
                new AmsCommand(
                    new AmsHeader(target, sender, AdsCommandId.Notification,
                                  AmsStateFlags.MaskAdsRequest, (uint)data.Length, 0, notificationCounter),
                    new ReadOnlyMemory <byte>(data)), CancellationToken.None);

            notificationCounter++;
            return(Unit.Default);
        }
Example #21
0
        private AdsErrorCode AdsRequest(AmsAddress rAddr, uint invokeId, ushort serviceId, uint cbLength, ITcAdsHeader adsHeader, byte[] adsData)
        {
            uint num = 0;

            if (adsHeader != null)
            {
                num = (uint)Marshal.SizeOf(adsHeader);
            }
            TcAmsHeader amsHeader = new TcAmsHeader(rAddr, this.Address, serviceId, 4, num + cbLength, 0, invokeId);

            return(this._amsServer.Send(new TcAmsCommand(amsHeader, TcAdsParser.BuildAdsBuffer(adsHeader, adsData))));
        }
Example #22
0
        public AdsErrorCode AdsReadDeviceInfoRes(AmsAddress rAddr, uint invokeId, AdsErrorCode result, string name, AdsVersion version)
        {
            TcAdsReadDeviceInfoResHeader adsHeader = new TcAdsReadDeviceInfoResHeader {
                _result       = result,
                _majorVersion = version.Version,
                _minorVersion = version.Revision,
                _versionBuild = (ushort)version.Build,
                _deviceName   = Encoding.ASCII.GetBytes(name.ToCharArray(), 0, (name.Length < 0x10) ? name.Length : 0x10)
            };

            return(this.AdsResponse(rAddr, invokeId, 1, 0, adsHeader, null));
        }
Example #23
0
        public AdsErrorCode AdsAddDeviceNotificationReq(AmsAddress rAddr, uint invokeId, uint indexGroup, uint indexOffset, uint cbLength, AdsTransMode transMode, uint maxDelay, uint cycleTime)
        {
            TcAdsAddDeviceNotificationReqHeader adsHeader = new TcAdsAddDeviceNotificationReqHeader {
                _indexGroup  = indexGroup,
                _indexOffset = indexOffset,
                _cbLength    = cbLength,
                _transMode   = transMode,
                _maxDelay    = maxDelay,
                _cycleTime   = cycleTime
            };

            return(this.AdsRequest(rAddr, invokeId, 6, 0, adsHeader, null));
        }
Example #24
0
        private void CreateNotification(int handler, NotificationRequest request, AmsAddress target, AmsAddress sender)
        {
            var cycleTime  = TimeSpan.FromMilliseconds(100);
            var disposable = Observable.Timer(TimeSpan.FromMilliseconds(10), cycleTime)
                             .Select(_ => memory.GetData(request.IndexGroup, request.IndexOffset, request.Length))
                             .DistinctUntilChanged(new ByteEqualityComparer())
                             .Select(data => CreateNotificationStream(handler, data))
                             .SelectMany(data => SendNotification(target, sender, data))
                             .Subscribe()
            ;

            Notifications.Add(handler, disposable);
        }
Example #25
0
 internal AdsValueAccessor(IAdsConnection connection, ValueAccessMode accessMethod, IAccessorValueFactory valueFactory, NotificationSettings defaultSettings) : base(valueFactory, connection, defaultSettings)
 {
     this._converter                  = new DynamicValueConverter();
     this._syncNotification           = new object();
     this._accessMethod               = ValueAccessMode.IndexGroupOffsetPreferred;
     this._notificationTable          = new AdsNotificationCache();
     this._notificationStream         = new AdsStream();
     this._address                    = connection.Address;
     this._accessMethod               = accessMethod;
     base._notificationSettings       = defaultSettings;
     connection.AdsNotification      += new AdsNotificationEventHandler(this.adsClient_AdsNotification);
     connection.AdsNotificationError += new AdsNotificationErrorEventHandler(this.adsClient_AdsNotificationError);
 }
Example #26
0
 internal TcAmsHeader(BinaryReader reader)
 {
     byte[] buffer = new byte[6];
     reader.Read(buffer, 0, 6);
     this._target = new AmsAddress(buffer, reader.ReadUInt16());
     reader.Read(buffer, 0, 6);
     this._sender     = new AmsAddress(buffer, reader.ReadUInt16());
     this._commandId  = reader.ReadUInt16();
     this._stateFlags = reader.ReadUInt16();
     this._cbData     = reader.ReadUInt32();
     this._errCode    = reader.ReadUInt32();
     this._hUser      = reader.ReadUInt32();
 }
 public override void AdsReadWriteInd(AmsAddress rAddr, uint invokeId, uint indexGroup, uint indexOffset, uint cbReadLength, uint cbWriteLength, byte[] data)
 {
     if (OnClientReadWriteRequest != null)
     {
         _pendingRequests.Add(
             invokeId,
             Task.Factory.StartNew(() => {
             Protocol.AdsContext context = new Protocol.AdsContext(rAddr.ToString(), Protocol.AdsCommand.ReadWrite, invokeId, indexGroup, indexOffset, cbReadLength, data);
             OnClientReadWriteRequest(context);
             ServiceRequest(context);
         }, _cancellationSource.Token)
             );
     }
 }
Example #28
0
        /// <summary>
        /// Constructor - establishes connection and creates symbol loader
        /// </summary>
        /// <param name="AmsNetId">ADS Client AMS Net Id "x.x.x.x.x.x:port" (127.0.0.1.1.1:851)</param>
        public AdsConnection(string AmsNetId)
        {
            _client = new TcAdsClient();

            // connect ADS client
            _client.Connect(AmsAddress.Parse(AmsNetId));

            if (_client.IsConnected)
            {
                // create symbol loader
                _symbolLoader = SymbolLoaderFactory.Create(_client,
                                                           new SymbolLoaderSettings(SymbolsLoadMode.VirtualTree));
            }
        }
Example #29
0
        public AdsErrorCode AdsReadWriteRes(AmsAddress rAddr, uint invokeId, AdsErrorCode result, uint cbLength, byte[] data)
        {
            TcAdsReadWriteResHeader adsHeader = new TcAdsReadWriteResHeader {
                _result = result,
                _cbData = cbLength
            };
            uint length = 0;

            if (data != null)
            {
                length = (uint)data.Length;
            }
            return(this.AdsResponse(rAddr, invokeId, 9, length, adsHeader, data));
        }
Example #30
0
        private PLCConnection(string beckhoffAddress, int port, int bufferSize = 1000)
        {
            _dataStream = new AdsStream(bufferSize);
            _binReader  = new BinaryReader(_dataStream);
            _tcClient   = new TcAdsClient();
            AmsAddress serverAddress = new AmsAddress(beckhoffAddress, 851);

            _tcClient.Connect(serverAddress.NetId, serverAddress.Port);

            foreach (var item in Enum.GetNames(typeof(X)))
            {
                var en = item.CastToEnum <X>().Value;
                RegisterParameter(en);
            }
        }