public IReadService CreateChannel()
        {
            try
            {
                InstanceContext ic = null;
                HOST =
                    $"{Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "IPAddress", null)}";
                PORT = ushort.Parse(
                    $"{Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "Port", null)}");


                ic = new InstanceContext(new ReadServiceCallbackClient());

                var endPoint =
                    new EndpointAddress(
                        new Uri($"net.Tcp://{HOST}:{PORT}/AdvancedScada/{Driver}"));
                var factory = new DuplexChannelFactory <IReadService>(ic, GetNetTcpBinding(), endPoint);
                Modbusclient = factory.CreateChannel();
            }
            catch (CommunicationException ex)
            {
                var err = new HMIException.ScadaException(GetType().Name, ex.Message);
            }

            return(Modbusclient);
        }
        public bool  GetStartService()
        {
            try
            {
                var xmlFile = objChannelManager.ReadKey(objChannelManager.XML_NAME_DEFAULT);
                if (string.IsNullOrEmpty(xmlFile) || string.IsNullOrWhiteSpace(xmlFile))
                {
                    return(false);
                }

                lock (mutex)
                {
                    objChannelManager.Channels.Clear();
                    TagCollection.Tags.Clear();
                    var channels = objChannelManager.GetChannels(xmlFile);


                    driverHelper.InitializeService(channels);
                    driverHelper.Connect();



                    return(true);
                }
            }
            catch (Exception ex)
            {
                var err = new HMIException.ScadaException(GetType().Name, ex.Message);
            }

            return(true);
        }
        public ServiceHost GetServiceHostHttp()

        {
            ServiceHost Gethost = null;

            Type serviceType = null;

            try
            {
                HOST =
                    $"{Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "IPAddress", null)}";
                PORT = ushort.Parse(
                    $"{Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "Port", null)}");

                serviceType = typeof(ReadService);

                var baseAddresses = new Uri[2]
                {
                    new Uri($"net.Tcp://{HOST}:{PORT}/AdvancedScada/"),
                    new Uri("http://localhost/AdvancedScada")
                };


                Gethost = new ServiceHost(serviceType, baseAddresses);
                var throttle = Gethost.Description.Behaviors.Find <ServiceThrottlingBehavior>();
                if (throttle == null)
                {
                    throttle = new ServiceThrottlingBehavior();
                    throttle.MaxConcurrentCalls     = int.MaxValue;
                    throttle.MaxConcurrentSessions  = int.MaxValue;
                    throttle.MaxConcurrentInstances = int.MaxValue;
                    Gethost.Description.Behaviors.Add(throttle);
                }


                Gethost.AddServiceEndpoint(typeof(IReadService), GetNetTcpBinding(), Driver);
                Gethost.AddServiceEndpoint(typeof(IReadService), GetNetTcpBinding(), CHANNEL);

                ////Enable metadata exchange
                var smb = new ServiceMetadataBehavior();
                smb.HttpGetUrl     = new Uri("http://localhost/AdvancedScada/Driver");
                smb.HttpGetEnabled = true;
                Gethost.Description.Behaviors.Add(smb);
            }
            catch (CommunicationException ex)
            {
                var err = new HMIException.ScadaException(GetType().Name, ex.Message);
            }

            return(Gethost);
        }
 public bool GetStopService()
 {
     try
     {
         lock (mutexStop)
         {
             driverHelper.Disconnect();
         }
     }
     catch (System.Exception ex)
     {
         var err = new HMIException.ScadaException(this.GetType().Name, ex.Message);
     }
     return(true);
 }
Exemple #5
0
        public static IReadService CreateChannelTools()
        {
            lock (mutexCreateChannel)
            {
                try
                {
                    if (Channelclient != null)
                    {
                        return(Channelclient);
                    }
                    InstanceContext ic = null;
                    HOST = $"{Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "IPAddress", null)}";
                    if (Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "Port", null) == null)
                    {
                        return(null);
                    }
                    PORT = ushort.Parse(
                        $"{Registry.GetValue("HKEY_CURRENT_USER\\Software\\FormConfiguration", "Port", null)}");

                    ic = new InstanceContext(new ReadServiceCallbackClient());
                    // Create a channel factory.
                    var b = new NetTcpBinding();
                    b.Security.Mode = SecurityMode.Transport;
                    b.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
                    b.Security.Transport.ProtectionLevel      = ProtectionLevel.EncryptAndSign;

                    b.MaxBufferSize          = 1000000;
                    b.MaxBufferPoolSize      = 1000000;
                    b.MaxReceivedMessageSize = 1000000;
                    b.OpenTimeout            = TimeSpan.FromMinutes(2);
                    b.SendTimeout            = TimeSpan.FromMinutes(2);
                    b.ReceiveTimeout         = TimeSpan.FromMinutes(10);

                    var endPoint =
                        new EndpointAddress(
                            new Uri($"net.Tcp://{HOST}:{PORT}/AdvancedScada/{CHANNEL}"));
                    var factory = new DuplexChannelFactory <IReadService>(ic, b, endPoint);
                    Channelclient = factory.CreateChannel();
                }
                catch (CommunicationException ex)
                {
                    var err = new HMIException.ScadaException("ServiceBaseClient", ex.Message);
                }
            }

            return(Channelclient);
        }
        public void Connect()
        {
            try
            {
                IsConnected = true;
                Console.WriteLine("STARTED: {0}", ++COUNTER);
                taskArray = new Task[Channels.Count];
                if (taskArray == null)
                {
                    throw new NullReferenceException("No Data");
                }
                for (var i = 0; i < Channels.Count; i++)
                {
                    taskArray[i] = new Task(chParam =>
                    {
                        FatekCommunication modbus = null;
                        var ch = (Channel)chParam;

                        modbus = mbe[ch.ChannelName];
                        modbus.Connect();
                        IsConnected = modbus.IsConnected;
                        while (IsConnected)
                        {
                            foreach (var dv in ch.Devices)
                            {
                                foreach (var db in dv.DataBlocks)
                                {
                                    if (!IsConnected)
                                    {
                                        break;
                                    }
                                    SendPackage(modbus, dv, db);
                                }
                            }
                        }
                    }, Channels[i]);
                    taskArray[i].Start();
                }
            }
            catch (Exception ex)
            {
                var err = new HMIException.ScadaException(this.GetType().Name, ex.Message);
                IsConnected = false;
            }
        }
        public void InitializeService(Channel ch)
        {
            try
            {
                Channels.Add(ch);



                if (Channels == null)
                {
                    return;
                }



                FatekCommunication modbus = null;
                switch (ch.ConnectionType)
                {
                case "SerialPort":
                    var dis = (DISerialPort)ch;
                    var sp  = new SerialPort(dis.PortName, dis.BaudRate, dis.Parity, dis.DataBits, dis.StopBits);
                    sp.Handshake = dis.Handshake;


                    modbus = new FatekCommunication(sp);
                    mbe.Add(ch.ChannelName, (FatekCommunication)modbus);
                    break;
                }
                foreach (var dv in ch.Devices)
                {
                    foreach (var db in dv.DataBlocks)
                    {
                        foreach (var tg in db.Tags)
                        {
                            TagCollection.Tags.Add(
                                $"{ch.ChannelName}.{dv.DeviceName}.{db.DataBlockName}.{tg.TagName}", tg);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var err = new HMIException.ScadaException(this.GetType().Name, ex.Message);
            }
        }
Exemple #8
0
        public static bool LoadTagCollection()
        {
            lock (mutexStartClient)
            {
                objChannelManager = ChannelManager.GetChannelManager();

                try
                {
                    var xmlFile = objChannelManager.ReadKey(objChannelManager.XML_NAME_DEFAULT);
                    if (string.IsNullOrEmpty(xmlFile) || string.IsNullOrWhiteSpace(xmlFile))
                    {
                        return(false);
                    }

                    objChannelManager.Channels.Clear();
                    TagCollectionClient.Tags.Clear();
                    var channels = objChannelManager.GetChannels(xmlFile);

                    foreach (var ch in channels)
                    {
                        foreach (var dv in ch.Devices)
                        {
                            foreach (var db in dv.DataBlocks)
                            {
                                foreach (var tg in db.Tags)
                                {
                                    TagCollectionClient.Tags.Add(
                                        $"{ch.ChannelName}.{dv.DeviceName}.{db.DataBlockName}.{tg.TagName}", tg);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    var err = new HMIException.ScadaException("ServiceBaseClient", ex.Message);
                }
            }

            return(true);
        }
        private void SendPackage(FatekCommunication modbus, Device dv, DataBlock db)
        {
            try
            {
                SendDone.WaitOne(-1);
                DataType   dataType   = (DataType)Enum.Parse(typeof(DataType), db.DataType);
                MemoryType memoryType = (MemoryType)Enum.Parse(typeof(MemoryType), db.MemoryType);

                switch (db.DataType)
                {
                case "BOOL":
                    bool[] BitRs = null;
                    switch (db.TypeOfRead)
                    {
                    case "ReadCoilStatus":
                        BitRs = modbus.ReadDiscretes((byte)dv.SlaveId, db.Length, memoryType, db.StartAddress, dataType);

                        break;

                    case "ReadInputStatus":
                        //     bitArys = modbus.ReadInputStatus((byte)dv.SlaveId, $"{db.StartAddress}",
                        //db.Length);
                        break;

                    default:
                        break;
                    }

                    if (BitRs.Length > db.Tags.Count)
                    {
                        return;
                    }
                    for (var j = 0; j < db.Tags.Count; j++)
                    {
                        db.Tags[j].Value        = BitRs[j];
                        db.Tags[j].Checked      = BitRs[j];
                        db.Tags[j].Enabled      = BitRs[j];
                        db.Tags[j].Visible      = BitRs[j];
                        db.Tags[j].ValueSelect1 = BitRs[j];
                        db.Tags[j].ValueSelect2 = BitRs[j];
                        db.Tags[j].Timestamp    = DateTime.Now;
                    }
                    break;

                case "INT":
                case "DINT":
                case "WORD":
                case "DWORD":
                case "REAL":
                    object[] wdArys = null;
                    switch (db.TypeOfRead)
                    {
                    case "ReadHoldingRegisters":
                        wdArys = modbus.ReadRegisters((byte)dv.SlaveId, db.Length, memoryType, db.StartAddress, dataType);

                        break;

                    case "ReadInputRegisters":
                        //wdArys = modbus.ReadInputRegisters((byte)dv.SlaveId, $"{db.StartAddress}", db.Length);

                        break;

                    default:
                        break;
                    }

                    if (wdArys.Length > db.Tags.Count)
                    {
                        return;
                    }

                    for (var j = 0; j < wdArys.Length; j++)
                    {
                        db.Tags[j].Value     = wdArys[j];
                        db.Tags[j].Timestamp = DateTime.Now;
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                var err = new HMIException.ScadaException(this.GetType().Name + "   XFATEK.SendPackage", ex.Message);
            }
        }
        public void WriteTag(string TagName, dynamic Value)
        {
            SendDone.Reset();
            try
            {
                var strArrays = TagName.Split('.');
                var str       = $"{strArrays[0]}.{strArrays[1]}.{strArrays[2]}";
                foreach (var ch in Channels)
                {
                    foreach (var dv in ch.Devices)
                    {
                        foreach (var db in dv.DataBlocks)
                        {
                            var bEquals = $"{ch.ChannelName}.{dv.DeviceName}.{db.DataBlockName}".Equals(str);
                            if (bEquals)
                            {
                                FatekCommunication modbusMaster = null;

                                modbusMaster = mbe[ch.ChannelName];
                                var bmodbus = modbusMaster == null;
                                if (bmodbus)
                                {
                                    return;
                                }
                                var        obj        = modbusMaster;
                                DataType   dataType   = (DataType)Enum.Parse(typeof(DataType), TagCollection.Tags[TagName].DataType);
                                MemoryType memoryType = (MemoryType)Enum.Parse(typeof(MemoryType), db.MemoryType);
                                lock (obj)
                                {
                                    switch (TagCollection.Tags[TagName].DataType)
                                    {
                                    case "BOOL":
                                        if (Value == "1")
                                        {
                                            modbusMaster.WriteSingleDiscrete((byte)dv.SlaveId, CommandCode.SINGLE_DISCRETE_CONTROL, RunningCode.Set, memoryType, ushort.Parse(TagCollection.Tags[TagName].Address), dataType);
                                        }

                                        else
                                        {
                                            modbusMaster.WriteSingleDiscrete((byte)dv.SlaveId, CommandCode.SINGLE_DISCRETE_CONTROL, RunningCode.Reset, memoryType, ushort.Parse(TagCollection.Tags[TagName].Address), dataType);
                                        }

                                        break;

                                    case "INT":
                                    case "DINT":
                                    case "WORD":
                                    case "DWORD":
                                    case "REAL":
                                    {
                                        string[] DataAsArray = { Value };
                                        var      dataPacket  = new List <object>();
                                        var      x           = new byte[2];
                                        for (var i = 0; i < DataAsArray.Length; i++)
                                        {
                                            x = BitConverter.GetBytes(Convert.ToInt16(DataAsArray[i]));

                                            dataPacket.Add(x[1]);
                                            dataPacket.Add(x[0]);
                                        }


                                        modbusMaster.WriteMultipeRegisters((byte)dv.SlaveId, 1, memoryType, ushort.Parse(TagCollection.Tags[TagName].Address), dataType, dataPacket.ToArray());

                                        break;
                                    }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var err = new HMIException.ScadaException(this.GetType().Name + "   XModbus.WriteTag", ex.Message);
            }
            finally
            {
                SendDone.Set();
            }
        }