Esempio n. 1
0
        public void OneTimeSetUp()
        {
            IPlc           plc           = Substitute.For <IPlc>();
            ILoggerFactory loggerFactory = Substitute.For <ILoggerFactory>();

            this.isEndValueReadEventCallback                 = false;
            this.isEndValueReadEventStatusCallback           = false;
            this.isFromStartValueToEndValueReadEventCallback = false;
            this.isNotStartValueReadEventCallback            = false;
            this.isValueReadChangedEventCallback             = false;
            this.plcMonitorImp = new PlcMonitorImp(plc, loggerFactory);
            this.address       = new DataAddress
            {
                Name   = "Adddress",
                Type   = DataAddressType.Int,
                Value  = "E0_300",
                Offset = 0
            };

            plc.Initialize();
            plc.Read <int>(address).Returns(
                new int[] { 0 }, new int[] { 0 }, new int[] { 0 }, new int[] { 0 }, new int[] { 0 },
                new int[] { 1 }, new int[] { 1 }, new int[] { 1 }, new int[] { 1 }, new int[] { 1 },
                new int[] { 3 }, new int[] { 3 }, new int[] { 3 }, new int[] { 3 }, new int[] { 3 });
        }
Esempio n. 2
0
        public IEnumerable <TValue> Read <TValue>(DataAddress address)
        {
            if (address.Equals(DataAddress.Empty))
            {
                throw new ApplicationException("地址为空");
            }

            var result = new List <TValue>();

            try
            {
                var opcAddresses = address.Value.Split(DataAddress.ValueSeparator);

                for (int index = 0; index < opcAddresses.Length; index++)
                {
                    var value = client.Read <TValue>(opcAddresses[index]).Value;

                    result.Add(value);
                }
            }
            catch (Exception e)
            {
                Reconnect();

                throw new ApplicationException($"读取失败,地址:{address }", e);
            }

            return(result);
        }
Esempio n. 3
0
        private List <byte> GetBytes(DataAddress address, bool isRam = false)
        {
            var result        = new List <byte>();
            var modbusAddress = ModbusAddress.Parse(address);
            var values        = new ushort[] { };

            if (modbusAddress.IOType == IOType.AO)
            {
                values = master.ReadHoldingRegisters(modbusAddress.SlaveNumber, modbusAddress.StartAddress, modbusAddress.Length);
            }
            if (modbusAddress.IOType == IOType.AI)
            {
                values = master.ReadInputRegisters(modbusAddress.SlaveNumber, modbusAddress.StartAddress, modbusAddress.Length);
            }

            values.ToList().ForEach(e =>
            {
                if (isRam)
                {
                    result.AddRange(BitConverter.GetBytes(e).Reverse());
                }
                else
                {
                    result.AddRange(BitConverter.GetBytes(e));
                }
            });

            return(result);
        }
Esempio n. 4
0
        public DataAddress CreateTisDataAddress()
        {
            ITisDataAddress itda = TisServer.CreateDataAddress();
            DataAddress     da   = itda as DataAddress;

            return(da);
        }
Esempio n. 5
0
        public void Write <TValue>(DataAddress address, IEnumerable <TValue> values)
        {
            if (address.Equals(DataAddress.Empty))
            {
                throw new ApplicationException("地址为空");
            }
            if (values == null || !values.Any())
            {
                throw new ApplicationException($"参数异常,values为null或空");
            }

            var command = ProtocolUpperLinkCommand.GetWriteCommand(address, values);

            byte[] response = { };

            using (new StopwatchWrapper($"写入PLC"))
            {
                response = Send(command);
            }

            if (!response.Any() || !GetString(response).Contains("OK"))
            {
                Reconnect();

                throw new ApplicationException($"写入失败,地址:{address }");
            }
        }
Esempio n. 6
0
        public void Write <TValue>(DataAddress address, IEnumerable <TValue> values)
        {
            if (address.Equals(DataAddress.Empty))
            {
                throw new ApplicationException("地址为空");
            }
            if (values == null || !values.Any())
            {
                throw new ApplicationException($"参数异常,values为null或空");
            }

            try
            {
                var opcAddresses = address.Value.Split(DataAddress.ValueSeparator);
                var allValue     = values.ToArray();

                for (int index = 0; index < opcAddresses.Length; index++)
                {
                    client.Write <TValue>(opcAddresses[index], allValue[index]);
                }
            }
            catch (Exception e)
            {
                Reconnect();

                throw new ApplicationException($"写入失败,地址:{address }", e);
            }
        }
Esempio n. 7
0
        public IEnumerable <TValue> Read <TValue>(DataAddress address)
        {
            if (address.Equals(DataAddress.Empty))
            {
                throw new ApplicationException("地址为空");
            }

            var command = ProtocolUpperLinkCommand.GetReadCommand(address);

            byte[] response = { };

            using (new StopwatchWrapper($"读取PLC"))
            {
                response = Send(command);
            }

            if (!response.Any())
            {
                Reconnect();

                throw new ApplicationException($"读取失败,地址:{address }");
            }

            return(GetValues <TValue>(address, response));
        }
Esempio n. 8
0
        public void Write <TValue>(DataAddress address, IEnumerable <TValue> values)
        {
            if (address.Equals(DataAddress.Empty))
            {
                throw new ApplicationException("地址为空");
            }
            if (values == null || !values.Any())
            {
                throw new ApplicationException($"参数异常,values为null或空");
            }

            try
            {
                var opcAddresses = address.Value.Split(DataAddress.ValueSeparator);
                var allValue     = values.Select(e => (object)e).ToArray();

                client.WriteNodes(opcAddresses, allValue);
            }
            catch (Exception e)
            {
                Reconnect();

                throw new ApplicationException($"写入失败,地址:{address }", e);
            }
        }
Esempio n. 9
0
        public void Write <TValue>(DataAddress address, IEnumerable <TValue> values)
        {
            if (address.Equals(DataAddress.Empty))
            {
                throw new ApplicationException("地址为空");
            }
            if (values == null || !values.Any())
            {
                throw new ApplicationException($"参数异常,values为null或空");
            }

            var command = ProtocolFinsCommand.GetWriteCommand(address, values, pcNode, plcNode);

            byte[] response = { };

            using (new StopwatchWrapper($"写入PLC"))
            {
                response = Send(command);
            }

            if (!response.Any() || GetErrorCode(response) != ErrorCodeOK)
            {
                Reconnect();

                throw new ApplicationException($"写入失败,地址:{address },错误码:{GetErrorCode(response)}");
            }
        }
Esempio n. 10
0
        public IEnumerable <TValue> Read <TValue>(DataAddress address)
        {
            if (address.Equals(DataAddress.Empty))
            {
                throw new ApplicationException("地址为空");
            }

            var command = ProtocolFinsCommand.GetReadCommand(address, pcNode, plcNode);

            byte[] response = { };

            using (new StopwatchWrapper($"读取PLC"))
            {
                response = Send(command);
            }

            if (!response.Any() || GetErrorCode(response) != ErrorCodeOK)
            {
                Reconnect();

                throw new ApplicationException($"读取失败,地址:{address },错误码:{GetErrorCode(response)}");
            }

            return(GetValues <TValue>(address, response));
        }
Esempio n. 11
0
        public IEnumerable <DataAddress> Explore(DataAddress address)
        {
            IEnumerable <Hylasoft.Opc.Common.Node> nodes = client.ExploreFolder(address.Value.Split(DataAddress.ValueSeparator).Single());

            return(nodes.Select(e => new DataAddress()
            {
                Value = e.Tag
            }));
        }
Esempio n. 12
0
        private DbTransaction CreateTransaction(DataAddress baseRoot)
        {
            // Turn it into a transaction object,
            ITransaction transaction = client.CreateTransaction(baseRoot);

            // Check the path is a valid DbTransaction format,
            CheckPathValid(transaction);
            // Wrap it around an DbTransaction object, and return it
            return(new DbTransaction(this, baseRoot, transaction));
        }
        public void Write <TValue>(DataAddress address, IEnumerable <TValue> values)
        {
            var ea = new WritingEventArgs()
            {
                Address = address
            };

            values.ToList().ForEach(e => ea.Values.Add(e));

            Writing(this, ea);
        }
        private static byte[] GetLenghtBytes(DataAddress address)
        {
            int lenght = 2 * 4 + 3 * 3 + 1 + 2 + 1 + 3 + 2 + 2 * BitConverter.ToUInt16(GetItemCountBytes(address).Reverse().ToArray(), 0) + (address.Type == DataAddressType.Boolean ? -1 : 0);
            var bytes  = BitConverter.GetBytes((ushort)lenght);

            return(new byte[] {
                0x00,
                0x00,
                bytes[1],
                bytes[0]
            });
        }
Esempio n. 15
0
        public static ModbusAddress Parse(DataAddress address)
        {
            var values = address.Value.Split(':', ':');

            return(new ModbusAddress()
            {
                SlaveNumber = byte.Parse(values[0]),
                IOType = (IOType)Enum.Parse(typeof(IOType), values[1], true),
                StartAddress = ushort.Parse(values[2]),
                Length = GetLength(address)
            });
        }
Esempio n. 16
0
        internal DbTransaction(DbSession session, DataAddress baseRoot, ITransaction transaction)
        {
            this.session     = session;
            this.baseRoot    = baseRoot;
            this.transaction = transaction;

            log      = new List <string>();
            tableMap = new Dictionary <string, DbTable>();

            fileSet  = new Directory(transaction, FileSetProperties, FileSetNamemap, FileSetIndex, 0, 10);
            tableSet = new Directory(transaction, TableSetProperties, TableSetNamemap, TableSetIndex, 0, 11);
        }
Esempio n. 17
0
 public bool CreateAddress(DataAddress Address)
 {
     try
     {
         _context.Address.Add(Address);
         _context.SaveChanges();
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
Esempio n. 18
0
        public PlcBarcodeReader(string name, IPlc plc, DataAddress address, string regex = null)
            : base(name)
        {
            this.plc     = plc;
            this.address = address;
            this.regex   = new Regex(regex ?? string.Empty);
            this.connectionStateChangedEventManager = new ConnectionStateChangedEventManager(name);

            this.plc.ConnectionStateChanged += (s, e) =>
            {
                connectionStateChangedEventManager.OnConnectionStateChanged(ConnectionStateChanged, s, e);
            };
        }
        public IEnumerable <TValue> Read <TValue>(DataAddress address)
        {
            var result = new TValue[] { };
            var re     = new ReadindgEventArgs()
            {
                Address = address
            };

            Readindg(this, re);

            re.ManualResetEvent.WaitOne();

            result = re.Result.Select(e => (TValue)Convert.ChangeType(e, typeof(TValue))).ToArray();

            return(result);
        }
Esempio n. 20
0
        public void Init(IPathConnection connection)
        {
            // Get the current root,
            DataAddress currentRoot = connection.GetSnapshot();
            // Turn it into a transaction
            ITransaction transaction = connection.CreateTransaction(currentRoot);
            // Initialize the magic property set, etc
            IDataFile        df       = transaction.GetFile(DbTransaction.MagicKey, FileAccess.ReadWrite);
            StringDictionary magicSet = new StringDictionary(df);

            magicSet.SetValue("ob_type", "Deveel.Data.CloudBase");
            magicSet.SetValue("version", "1.0");
            // Flush and publish the change
            DataAddress finalRoot = connection.CommitTransaction(transaction);

            connection.Publish(finalRoot);
        }
Esempio n. 21
0
        public DataAddress GetAddress(string customerId, string addressType)
        {
            DataAddress Address = new DataAddress();

            try
            {
                Address = _context.Address.Where(x => x.CustomerId == customerId && x.AddressType == addressType)
                          .First()
                          as DataAddress;

                return(Address);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Esempio n. 22
0
        public void Monitor <TValue>(DataAddress address, Action <TValue, Action> callback)
        {
            client.AddSubscription(address.ToString(), address.Value.Split(DataAddress.ValueSeparator).Single(), (k, mi, ea) =>
            {
                MonitoredItemNotification notification = ea.NotificationValue as MonitoredItemNotification;

                try
                {
                    callback((TValue)notification.Value.WrappedValue.Value, () => client.RemoveSubscription(k));
                }
                catch (Exception e)
                {
                    Reconnect();

                    throw new ApplicationException($"回调失败,地址:{address }", e);
                }
            });
        }
        private static byte GetMemoryAreaCode(DataAddress address)
        {
            MemoryAreaType memoryAreaType = MemoryAreaType.None;
            MemoryAreaCode memoryAreaCode;

            if (address.Value.Contains("_"))//判断是否为EM区地址
            {
                memoryAreaType = (MemoryAreaType)Enum.Parse(typeof(MemoryAreaType), address.Value.Substring(0, 2), true);
            }
            else
            {
                memoryAreaType = (MemoryAreaType)Enum.Parse(typeof(MemoryAreaType), address.Value.Substring(0, 1), true);
            }

            memoryAreaCode = MemoryAreaCode.GetMemoryAreaCode(memoryAreaType);

            return(address.Type == DataAddressType.Boolean ? memoryAreaCode.Bit : memoryAreaCode.Word);
        }
        public static byte[] GetReadCommand(DataAddress address, byte pcNode, byte plcNode)
        {
            var command = new List <byte>();

            command.AddRange(new byte[] { 0x46, 0x49, 0x4E, 0x53 });
            command.AddRange(new byte[] { 0x00, 0x00, 0x00, 0x1A });
            command.AddRange(new byte[] { 0x00, 0x00, 0x00, 0x02 });
            command.AddRange(new byte[] { 0x00, 0x00, 0x00, 0x00 });
            command.AddRange(new byte[] { 0x80, 0x00, 0x02 });
            command.AddRange(new byte[] { 0x00, plcNode, 0x00 });
            command.AddRange(new byte[] { 0x00, pcNode, 0x00 });
            command.AddRange(new byte[] { 0x00 });
            command.AddRange(new byte[] { 0x01, 0x01 });
            command.AddRange(new byte[] { GetMemoryAreaCode(address) });
            command.AddRange(GetBeginingAddressBytes(address));
            command.AddRange(GetItemCountBytes(address));

            return(command.ToArray());
        }
Esempio n. 25
0
        public DbRootAddress PublishToSession(DbSession destSession)
        {
            // Refresh the transaction log with a cleared 'no base root' version.
            // This operation sets up the transaction log appropriately so that the
            // 'commit' process of future transactions will understand that this
            // version is not an iteration of previous versions.
            WriteClearedTransactionLog();

            // The database client,
            NetworkClient dbClient = session.Client;
            // Flush the transaction to the network
            DataAddress toPublish = dbClient.FlushTransaction(transaction);

            try {
                DataAddress published = dbClient.Commit(destSession.PathName, toPublish);
                // Return the root in the destionation session,
                return(new DbRootAddress(destSession, published));
            } catch (CommitFaultException e) {
                // This shouldn't be thrown,
                throw new ApplicationException("Unexpected Commit Fault", e);
            }
        }
        public static byte[] GetReadCommand(DataAddress address)
        {
            var command = new StringBuilder();

            command.Append($"RDS {address.Value }");

            switch (address.Type)
            {
            case DataAddressType.Boolean:
                command.Append($" { 1}");
                break;

            case DataAddressType.Short:
                command.Append($".S {address.Offset + 1}");
                break;

            case DataAddressType.Ushort:
                command.Append($".U {address.Offset + 1}");
                break;

            case DataAddressType.Int:
                command.Append($".L {address.Offset + 1}");
                break;

            case DataAddressType.Float:
                command.Append($".H {(address.Offset + 1) * 2}");
                break;

            case DataAddressType.String:
                command.Append($".H {(int)Math.Ceiling((address.Offset + 1) / 2d)}");
                break;

            default: throw new NotImplementedException();
            }

            command.Append("\r");

            return(Encoding.ASCII.GetBytes(command.ToString()));
        }
Esempio n. 27
0
        private static ushort GetLength(DataAddress address)
        {
            var result = 0;

            switch (address.Type)
            {
            case DataAddressType.Boolean: result = (address.Offset + 1); break;

            case DataAddressType.Short: result = (address.Offset + 1); break;

            case DataAddressType.Ushort: result = (address.Offset + 1); break;

            case DataAddressType.Int: result = 2 * (address.Offset + 1); break;

            case DataAddressType.Float: result = 2 * (address.Offset + 1); break;

            case DataAddressType.String: result = (int)Math.Ceiling((address.Offset + 1) / 2d); break;

            default: throw new NotImplementedException();
            }

            return((ushort)result);
        }
        private static byte[] GetItemCountBytes(DataAddress address)
        {
            int count = 0;

            switch (address.Type)
            {
            case DataAddressType.Boolean: count = 1; break;

            case DataAddressType.Short: count = 1 * (address.Offset + 1); break;

            case DataAddressType.Ushort: count = 1 * (address.Offset + 1); break;

            case DataAddressType.Int: count = 2 * (address.Offset + 1); break;

            case DataAddressType.Float: count = 2 * (address.Offset + 1); break;

            case DataAddressType.String: count = (int)Math.Ceiling((address.Offset + 1) / 2d); break;

            default: throw new NotImplementedException();
            }

            return(BitConverter.GetBytes((ushort)count).Reverse().ToArray());
        }
Esempio n. 29
0
        public IEnumerable <TValue> Read <TValue>(DataAddress address)
        {
            if (address.Equals(DataAddress.Empty))
            {
                throw new ApplicationException("地址为空");
            }

            var result = new List <TValue>();

            try
            {
                var opcAddresses = address.Value.Split(DataAddress.ValueSeparator);

                result = client.ReadNodes <TValue>(opcAddresses);
            }
            catch (Exception e)
            {
                Reconnect();

                throw new ApplicationException($"读取失败,地址:{address }", e);
            }

            return(result);
        }
        private static byte[] GetBeginingAddressBytes(DataAddress address)
        {
            var result = new List <byte>();

            if (address.Value.Contains("_"))//判断是否为E区地址
            {
                result = new List <byte>(BitConverter.GetBytes(ushort.Parse(address.Value.Substring(3))).Reverse());
            }
            else
            {
                result = new List <byte>(BitConverter.GetBytes(ushort.Parse(address.Value.Substring(1))).Reverse());
            }

            if (address.Type == DataAddressType.Boolean)
            {
                result.Add((byte)address.Offset);
            }
            else
            {
                result.Add(0x00);
            }

            return(result.ToArray());
        }
Esempio n. 31
0
 protected virtual void OnTransactionCommitted(string pathName, IPathTransaction transaction, DataAddress dataAddress)
 {
 }