Ejemplo n.º 1
0
 public void AddCoil(Coil coil)
 {
     if (!activeCoils.Contains(coil))
     {
         activeCoils.Add(coil);
     }
 }
Ejemplo n.º 2
0
 public void RemoveCoil(Coil coil)
 {
     if (activeCoils.Contains(coil))
     {
         activeCoils.Remove(coil);
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WriteEventArgs"/> class using a single coil.
 /// </summary>
 /// <param name="deviceId">The device id.</param>
 /// <param name="coil">The coil.</param>
 public WriteEventArgs(byte deviceId, Coil coil)
 {
     DeviceId = deviceId;
     Coils    = new List <Coil> {
         coil
     };
 }
Ejemplo n.º 4
0
        public async Task ClientWriteSingleCoilTest()
        {
            // Function Code 0x05

            byte[] expectedRequest = new byte[] { 0, 0, 0, 6, 1, 5, 0, 173, 255, 0 };

            using var server = new MiniTestServer
                  {
                      RequestHandler = (request, clientIp) =>
                      {
                          CollectionAssert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect");
                          Console.WriteLine("Server sending response");
                          return(request);
                      }
                  };
            server.Start();

            using var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger());
            await client.Connect();

            Assert.IsTrue(client.IsConnected);

            var coil = new Coil
            {
                Address   = 173,
                BoolValue = true
            };
            bool success = await client.WriteSingleCoil(1, coil);

            Assert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError);
            Assert.IsTrue(success);
        }
Ejemplo n.º 5
0
        //加载末端库框架配载图
        private void loadFrameLayout10(string sFrameID)
        {
            string    sql = "select Location,CLH,RKB,SteelDiameter from FrameLayout where FrameID='" + sFrameID + "' and Mold='10'";
            DataTable dt  = SqlCe.ExecuteQuery(sql);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["Location"].ToString().Length == 7)
                {
                    string clh = dt.Rows[i]["CLH"].ToString();
                    if (!clh.Equals(""))
                    {
                        CoilPoint p = new CoilPoint(sFrameID, dt.Rows[i]["Location"].ToString());
                        if (clh.Length > 8)
                        {
                            dtFrame.Rows[p.row][p.col] = clh.Substring(clh.Length - 8, 8);
                        }
                        else
                        {
                            dtFrame.Rows[p.row][p.col] = clh;
                        }
                        Coil coil = new Coil(p, clh);
                        coil.kb       = dt.Rows[i]["RKB"].ToString();
                        coil.diameter = dt.Rows[i]["SteelDiameter"].ToString();
                        Global.coils.Add(p, coil);
                    }
                }
            }
            dt.Dispose();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 发送线圈消息-同步
        /// </summary>
        /// <param name="coil">线圈</param>
        /// <param name="Press">是否按下 值【0:False;1:True】</param>
        internal bool CoilMsgSync(Coil coil, bool Press)
        {
            lock (WaitSync)
            {
                try
                {
                    InputModule input = new InputModule();
                    input.bySlaveID   = m_SlaveID;
                    input.byFunction  = Modbus.byWRITE_SINGLE_COIL;
                    input.nStartAddr  = coil.Addr;
                    input.nDataLength = Coil.Size;
                    input.byWriteData = new byte[] { Press ? (byte)255 : (byte)0, 0x00 };

                    return(SendListMsg(input));
                }
                catch (Exception ex)
                {
                    log.AddERRORLOG("同步消息发送异常:" + ex.Message);
                    return(false);
                }
                finally
                {
                }
            }
        }
Ejemplo n.º 7
0
 void LoadCoilData(SavedCoilData savedCoilData, Coil coil)
 {
     if (coil)
     {
         coil.UpdateType((Coil.Type)savedCoilData.coilType);
         coil.UpdateDelay(savedCoilData.delay);
     }
 }
Ejemplo n.º 8
0
        public void FindInterceptionTest()
        {
            //|     x1             x2     y1   |
            //|--+--[ ]--[OSR]--+--[/]----( )--|
            //|  |  y1    x3    |              |
            //|  +--[ ]---[ ]---+              |
            //

            Rung TestRung = new Rung();

            var Y1 = new Coil();

            Y1.Name = "1";
            var X1 = new Contact();

            X1.Name = "1";
            var X2 = new Contact();

            X2.Name       = "2";
            X2.IsInverted = true;
            var X3 = new Contact();

            X3.Name       = "2";
            X3.IsInverted = true;

            var Y1C = new Contact();

            Y1C.Name = "1";
            Y1C.Type = Contact.ContactType.OutputPin;

            TestRung.Add(Y1);
            TestRung.InsertBefore(X2, Y1);
            TestRung.Add(X1);
            TestRung.InsertUnder(Y1C, X1);
            TestRung.InsertAfter(new OSR(), X1);
            TestRung.InsertAfter(X3, Y1C);

            Tuple <Node, Node> temp;

            temp = TestRung.FindInterception(Y1C, X3);
            Assert.IsNull(temp);

            temp = TestRung.FindInterception(Y1C, X2);
            Assert.IsNull(temp);

            temp = TestRung.FindInterception(Y1C, Y1);
            Assert.IsNull(temp);

            temp = TestRung.FindInterception(Y1C, X1);
            Assert.AreEqual(temp.Item1, X1.LeftLide);
            Assert.AreEqual(temp.Item2, X3.RightLide);

            temp = TestRung.FindInterception(X3, X1);
            Assert.AreEqual(temp.Item1, X1.LeftLide);
            Assert.AreEqual(temp.Item2, X3.RightLide);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Writes a single coil status to the Modbus device. (Modbus function 5)
        /// </summary>
        /// <param name="deviceId">The id to address the device (slave).</param>
        /// <param name="coil">The coil to write.</param>
        /// <returns>true on success, otherwise false.</returns>
        public async Task <bool> WriteSingleCoil(byte deviceId, Coil coil)
        {
            logger?.LogTrace($"ModbusClient.WriteSingleRegister({deviceId}, {coil})");
            if (isDisposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (coil == null)
            {
                throw new ArgumentNullException(nameof(coil));
            }
            if (deviceId < Consts.MinDeviceIdRtu || Consts.MaxDeviceId < deviceId)
            {
                throw new ArgumentOutOfRangeException(nameof(deviceId));
            }
            if (coil.Address < Consts.MinAddress || Consts.MaxAddress < coil.Address)
            {
                throw new ArgumentOutOfRangeException(nameof(coil.Address));
            }

            try
            {
                var request = new Request
                {
                    DeviceId = deviceId,
                    Function = FunctionCode.WriteSingleCoil,
                    Address  = coil.Address,
                    Data     = new DataBuffer(2)
                };
                var value = (ushort)(coil.Value ? 0xFF00 : 0x0000);
                request.Data.SetUInt16(0, value);
                var response = await SendRequest(request);

                if (response.IsTimeout)
                {
                    throw new ModbusException("Response timed out. Device id invalid?");
                }
                if (response.IsError)
                {
                    throw new ModbusException(response.ErrorMessage);
                }

                return(request.DeviceId == response.DeviceId &&
                       request.Function == response.Function &&
                       request.Address == response.Address &&
                       request.Data.Equals(response.Data));
            }
            catch (IOException ex)
            {
                logger?.LogWarning(ex, "Writing single coil. Reconnecting.");
                ConnectingTask = Task.Run((Action)Reconnect);
            }

            return(false);
        }
Ejemplo n.º 10
0
 void FillCoilInfo(SavedComponentData componentData, Coil coil)
 {
     if (coil)
     {
         componentData.coilData = new SavedCoilData()
         {
             coilType = (int)coil.type,
             delay    = coil.delay
         };
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="codigo"></param>
        /// <returns></returns>
        public int Guardar(string codigo)
        {
            Coil obj = new Coil();

            obj.codigo         = codigo;
            obj.code           = code.Text;
            obj.dimB           = double.Parse(dimB.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_min = double.Parse(WMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_max = double.Parse(WMax.Text, CultureInfo.InvariantCulture.NumberFormat);

            return(DataManager.SetExternal_GR_1P(obj));
        }
Ejemplo n.º 12
0
        public override void Update()
        {
            //power.text = ((int)((AssociatedComponent.Logics as Logics.CoilLogics).chargeState)).ToString() + " %";//TODO
            Coil p = AssociatedComponent as Coil;
            var  l = AssociatedComponent.Logics as Logics.CoilLogics;

            power.text = Math.Round(l.chargeState, 4).ToString() + "\r\n" +
                         "cur: " + Math.Round(l.curField.force * 10000, 4).ToString() + "   " + l.curField.direction.ToString();
            power.Size = new Vector2(size.X - 10, 20);

            base.Update();
        }
        public int Guardar(string codigo)
        {
            Coil obj = new Coil();

            obj.codigo         = codigo;
            obj.code           = code.Text;
            obj.dimA           = double.Parse(dimA.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_min = double.Parse(WMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_max = double.Parse(WMax.Text, CultureInfo.InvariantCulture.NumberFormat);

            return(DataManager.SetSHIM_OF_THE_CUT_SYSTEM(obj));
        }
Ejemplo n.º 14
0
        public int Update()
        {
            Coil obj = new Coil();

            obj.codigo         = herramental.Codigo;
            obj.ID             = herramental.idHerramental;
            obj.code           = code.Text;
            obj.dimB           = double.Parse(dimB.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_min = double.Parse(WMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_max = double.Parse(WMax.Text, CultureInfo.InvariantCulture.NumberFormat);

            return(DataManager.UpdateExternal_GR_1P(obj));
        }
Ejemplo n.º 15
0
        private Response HandleWriteMultipleCoils(Request request)
        {
            try
            {
                var response = new Response(request);

                var numBytes = (int)Math.Ceiling(request.Count / 8.0);
                if (request.Count < Consts.MinCount || request.Count > Consts.MaxCoilCountWrite || numBytes != request.Data.Length)
                {
                    response.ErrorCode = ErrorCode.IllegalDataValue;
                }
                else if (request.Address < Consts.MinAddress || request.Address + request.Count > Consts.MaxAddress)
                {
                    response.ErrorCode = ErrorCode.IllegalDataAddress;
                }
                else
                {
                    try
                    {
                        var list = new List <Coil>();
                        for (int i = 0; i < request.Count; i++)
                        {
                            var addr = (ushort)(request.Address + i);

                            var posByte = i / 8;
                            var posBit  = i % 8;

                            var mask = (byte)Math.Pow(2, posBit);
                            var val  = request.Data[posByte] & mask;

                            var coil = new Coil {
                                Address = addr, Value = (val > 0)
                            };
                            SetCoil(request.DeviceId, coil);
                            list.Add(coil);
                        }
                        CoilWritten?.Invoke(this, new WriteEventArgs(request.DeviceId, list));
                    }
                    catch
                    {
                        response.ErrorCode = ErrorCode.SlaveDeviceFailure;
                    }
                }

                return(response);
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 16
0
        public int Guardar(string codigo)
        {
            Coil obj = new Coil();

            obj.codigo         = codigo;
            obj.code           = code.Text;
            obj.dimA           = double.Parse(dimA.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.dimB           = double.Parse(dimB.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.dimC           = double.Parse(dimC.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.dimD           = double.Parse(dimD.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_min = double.Parse(WMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_max = double.Parse(WMax.Text, CultureInfo.InvariantCulture.NumberFormat);

            return(DataManager.SetCOIL_FEED_ROLLER(obj));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 修改单个线圈的值
        /// </summary>
        /// <param name="coil">线圈</param>
        /// <param name="Press">是否按下 值【0:False;1:True】</param>
        internal void AddMsgList(Coil coil, bool Press)
        {
            if (coil.Value == Press)
            {
                return;                     //相等则不修改
            }
            InputModule input = new InputModule();

            input.byFunction  = Modbus.byWRITE_SINGLE_COIL;
            input.nStartAddr  = coil.Addr;
            input.nDataLength = Coil.Size;
            input.byWriteData = new byte[] { Press ? (byte)255 : (byte)0, 0x00 };

            AddMsgList(input);
        }
Ejemplo n.º 18
0
        public override void Draw(MicroWorld.Graphics.Renderer renderer)
        {
            if (texture0cw == null)
            {
                return;
            }
            if (!CanDraw())
            {
                return;
            }
            Coil p = parent as Coil;

            Components.Logics.CoilLogics l = (Components.Logics.CoilLogics)parent.Logics;
            if (!wasAOEDrawn && AOEOpacity > 0 && !MicroWorld.Graphics.GraphicsEngine.IsSelectedGlowPass)
            {
                DrawAOE(renderer, 1f);
                wasAOEDrawn = false;
            }

            //renderer.DrawString(MicroWorld.Graphics.GUI.GUIEngine.font, p.W.Resistance.ToString(), Position, Color.Red, MicroWorld.Graphics.Renderer.TextAlignment.Left);

            switch (parent.ComponentRotation)
            {
            case Component.Rotation.cw0:
                renderer.Draw(texture0cw,
                              new Rectangle((int)Position.X, (int)Position.Y,
                                            (int)GetSizeRotated(parent.ComponentRotation).X, (int)GetSizeRotated(parent.ComponentRotation).Y), null,
                              Color.White);
                break;

            case Component.Rotation.cw90:
                renderer.Draw(texture90cw,
                              new Rectangle((int)Position.X, (int)Position.Y,
                                            (int)GetSizeRotated(parent.ComponentRotation).X, (int)GetSizeRotated(parent.ComponentRotation).Y), null,
                              Color.White);
                break;

            case Component.Rotation.cw180:
                break;

            case Component.Rotation.cw270:
                break;

            default:
                break;
            }
            //renderer.DrawStringLeft(MicroWorld.Graphics.GUI.GUIEngine.font, l.Field.ToString() + "\r\n" + l.desiredField.ToString(), Position, Color.Red);
        }
        public int Update()
        {
            //Declaración del objeto.
            Coil obj = new Coil();

            //Asiganmos los valores.
            obj.codigo         = herramental.Codigo;
            obj.ID             = herramental.idHerramental;
            obj.code           = code.Text;
            obj.dimA           = double.Parse(dimA.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_min = double.Parse(WMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_max = double.Parse(WMax.Text, CultureInfo.InvariantCulture.NumberFormat);


            return(DataManager.UpdateSHIM_OF_THE_CUT_SYSTEM(obj));
        }
Ejemplo n.º 20
0
        public int Update()
        {
            Coil coil = new Coil();

            coil.codigo         = herramental.Codigo;
            coil.ID             = herramental.idHerramental;
            coil.code           = code.Text;
            coil.dimA           = double.Parse(dimA.Text, CultureInfo.InvariantCulture.NumberFormat);
            coil.dimB           = double.Parse(dimB.Text, CultureInfo.InvariantCulture.NumberFormat);
            coil.dimC           = double.Parse(dimC.Text, CultureInfo.InvariantCulture.NumberFormat);
            coil.dimD           = double.Parse(dimD.Text, CultureInfo.InvariantCulture.NumberFormat);
            coil.wire_width_min = double.Parse(WMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            coil.wire_width_max = double.Parse(WMax.Text, CultureInfo.InvariantCulture.NumberFormat);

            return(DataManager.UpdateCOIL_FEED_ROLLER(coil));
        }
Ejemplo n.º 21
0
        /// <summary>
        ///  Additional check on options.
        /// </summary>
        /// <returns></returns>
        public void CheckOptions(IConsole console)
        {
            // Ignoring some of the options
            if (Hex && !string.IsNullOrEmpty(Type) && !Type.Equals("string", StringComparison.InvariantCultureIgnoreCase))
            {
                console.Out.WriteLine("HEX output option is ignored (-x can only be used with type 'string').");
            }

            if (Hex && !string.IsNullOrEmpty(Coil))
            {
                console.Out.WriteLine($"HEX output option is ignored (-x can only be used with -h -t string).");
            }

            if (!string.IsNullOrEmpty(Type) && !string.IsNullOrEmpty(Coil))
            {
                console.Out.WriteLine($"Specified type '{Type}' is ignored (-t can only be used with -h).");
            }

            if (!string.IsNullOrEmpty(Coil))
            {
                if (!Coil.Contains("["))
                {
                    Coil = "[" + Coil;
                }
                if (!Coil.Contains("]"))
                {
                    Coil += "]";
                }
            }

            if (!string.IsNullOrEmpty(Holding))
            {
                if (!string.IsNullOrEmpty(Type) && Type.Equals("string", StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                if (!Holding.Contains("["))
                {
                    Holding = "[" + Holding;
                }
                if (!Holding.Contains("]"))
                {
                    Holding += "]";
                }
            }
        }
Ejemplo n.º 22
0
        private void ScanImpCoilResult(CoilPoint p, string text, string scantime, DataTable dt)
        {
            curcoil = new Coil(p, text);
            int    scanflag = 0;
            string zzdy     = "";

            if (dt.Rows.Count > 0)
            {
                scanflag = 1;
                zzdy     = dt.Rows[0]["Make"].ToString();
            }

            if (Global.coils.ContainsKey(p))
            {
                Global.coils[p].scanflag = scanflag;
                Global.coils[p].scantime = scantime;
                Global.coils[p].clh      = text;
                Global.coils[p].zzdy     = zzdy;
            }
            else
            {
                curcoil.scanflag = scanflag;
                curcoil.scantime = scantime;
                curcoil.zzdy     = zzdy;
                Global.coils.Add(p, curcoil);
            }
            if (text.Length > 8)
            {
                //材料号只显示8位
                //dtFrame.Rows[p.row][p.col] = text.Substring(text.Length - 8, 8);
                dtFrame.Rows[p.row][p.col] = text;
            }
            else
            {
                dtFrame.Rows[p.row][p.col] = text;
            }
            dataGrid2.DataSource = dtFrame;
            if (scanflag == 1)
            {
                PsionTeklogix.Sound.Beeper.Beeper.PlayTone(5000, 500, 100);
                string sql = "update importstorageacceptorder set scantime='" + scantime + "', wcflag=1 where clh2='" + text + "'";
                SqlCe.ExecuteNonQuery(sql);
            }
        }
Ejemplo n.º 23
0
        private void clearCoils()
        {
            Global.coils.Clear();
            curcoil = null;

            dtFrame = new DataTable();
            for (int i = 0; i < Global.curFrame.MaxRow; i++)
            {
                DataRow row = dtFrame.NewRow();

                int count = i + 1;
                row["X"] = count;
                row["L"] = "";
                row["R"] = "";
                dtFrame.Rows.Add(row);
            }
            this.dataGrid1.DataSource = dtFrame;
            dataGrid1.Invalidate();
        }
        public int Update()
        {
            //Declaración del objeto.
            Coil obj = new Coil();

            //Asiganmos los valores.
            obj.codigo          = herramental.Codigo;
            obj.ID              = herramental.idHerramental;
            obj.code            = code.Text;
            obj.dimA            = double.Parse(dimA.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.dimB            = double.Parse(dimB.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.dimC            = double.Parse(dimC.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_min  = double.Parse(WMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_max  = double.Parse(WMax.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.radial_wire_min = double.Parse(RMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.radial_wire_max = double.Parse(Rmax.Text, CultureInfo.InvariantCulture.NumberFormat);

            return(DataManager.UpdateCOIL_CENTER_GUIDE(obj));
        }
        /// <summary>
        /// Método que guarda la información registrada.
        /// </summary>
        /// <param name="codigo"></param>
        /// <returns></returns>
        public int Guardar(string codigo)
        {
            //Declaración del objeto.
            Coil obj = new Coil();

            //Asiganmos los valores.
            obj.codigo          = codigo;
            obj.code            = code.Text;
            obj.dimA            = double.Parse(dimA.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.dimB            = double.Parse(dimB.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.dimC            = double.Parse(dimC.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_min  = double.Parse(WMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.wire_width_max  = double.Parse(WMax.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.radial_wire_min = double.Parse(RMin.Text, CultureInfo.InvariantCulture.NumberFormat);
            obj.radial_wire_max = double.Parse(Rmax.Text, CultureInfo.InvariantCulture.NumberFormat);

            //Mandamos a llamar al método para insertar el objeto y retornamos el resultado.
            return(DataManager.SetCOIL_CENTER_GUIDE(obj));
        }
Ejemplo n.º 26
0
        public void GetAllBetweenTest()
        {
            //|     x1             x2     y1   |
            //|--+--[ ]--[OSR]--+--[/]----( )--|
            //|  |  y1    x3    |              |
            //|  +--[ ]---[ ]---+              |
            //

            Rung TestRung = new Rung();

            var Y1 = new Coil();

            Y1.Name = "1";
            var X1 = new Contact();

            X1.Name = "1";
            var X2 = new Contact();

            X2.Name       = "2";
            X2.IsInverted = true;
            var X3 = new Contact();

            X3.Name       = "2";
            X3.IsInverted = true;

            var Y1C = new Contact();

            Y1C.Name = "1";
            Y1C.Type = Contact.ContactType.OutputPin;

            TestRung.Add(Y1);
            TestRung.InsertBefore(X2, Y1);
            TestRung.Add(X1);
            TestRung.InsertUnder(Y1C, X1);
            TestRung.InsertAfter(new OSR(), X1);
            TestRung.InsertAfter(X3, Y1C);

            Assert.AreEqual(TestRung.GetAllBetween(X1.LeftLide, X1.RightLide).Count, 1);
            Assert.AreEqual(TestRung.GetAllBetween(X1.LeftLide, X3.RightLide).Count, 4);
            Assert.AreEqual(TestRung.GetAllBetween(X1.LeftLide, X2.RightLide).Count, 5);
            Assert.AreEqual(TestRung.GetAllBetween(X1.LeftLide, Y1.RightLide).Count, 6);
        }
Ejemplo n.º 27
0
        private Response HandleWriteSingleCoil(Request request)
        {
            var response = new Response(request);

            try
            {
                var val = request.Data.GetUInt16(0);
                if (val != 0x0000 && val != 0xFF00)
                {
                    response.ErrorCode = ErrorCode.IllegalDataValue;
                }
                else if (request.Address < Consts.MinAddress || request.Address > Consts.MaxAddress)
                {
                    response.ErrorCode = ErrorCode.IllegalDataAddress;
                }
                else
                {
                    try
                    {
                        var coil = new Coil {
                            Address = request.Address, Value = (val > 0)
                        };

                        SetCoil(request.DeviceId, coil);
                        response.Data = request.Data;

                        CoilWritten?.Invoke(this, new WriteEventArgs(request.DeviceId, coil));
                    }
                    catch
                    {
                        response.ErrorCode = ErrorCode.SlaveDeviceFailure;
                    }
                }
            }
            catch
            {
                return(null);
            }

            return(response);
        }
Ejemplo n.º 28
0
        private void dataGrid2_Click(object sender, EventArgs e)
        {
            if (dataGrid2.CurrentCell.Equals(null))
            {
                return;
            }

            if (dataGrid2.CurrentCell.ColumnNumber > 0)
            {
                curPoint = new CoilPoint(Global.curFrame.KJH, dataGrid2.CurrentCell.RowNumber, dataGrid2.CurrentCell.ColumnNumber);
                if (dtFrame.Rows[curPoint.row][curPoint.col].ToString() != "")
                {
                    curcoil = Global.coils[curPoint];
                }
                else
                {
                    curcoil = null;
                }
            }
            dataGrid2.Invalidate();
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="coil">线圈</param>
        /// <param name="value">线圈判断的值</param>
        /// <param name="btn">按钮</param>
        internal MsgBox(Coil coil, bool value, MessageBoxButtons btn = MessageBoxButtons.OK)
        {
            InitializeComponent();

            this.m_Coil      = coil;
            this.m_CoilValue = value;

            switch (btn)
            {
            case MessageBoxButtons.OK:
                this.btn_Confirm.Text     = "确认";
                this.btn_Confirm.Location = new Point((this.Width - this.btn_Confirm.Width) / 2, this.btn_Confirm.Location.Y);
                this.btn_Cancel.Visible   = false;
                break;

            case MessageBoxButtons.YesNo:

                break;
            }

            CheckIsShow();
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Создаёт контроллер сети Modbus из файла конфигурации сети
        /// </summary>
        /// <param name="pathToXmlFile">Путь + название файла конфигурации сети *.xml</param>
        /// <param name="pathToXsdFile">Путь + название файла файла схемы для файла конфигурации *.xsd</param>
        /// <returns>Если возникла ошибка возвращается null, если процесс создания 
        /// успешно завершён возвращается контроллер сети</returns>
        public static NetworkController Create(String pathToXmlFile, 
            String pathToXsdFile)
        {
            XmlReaderSettings xmlrdsettings;
            XmlReader reader;
            NetworkController network;
            Device device;
            Coil coil;
            DiscreteInput dinput;
            HoldingRegister hregister;
            InputRegister iregister;
            File file;
            Record record;
            List<Device> devices;
            String networkName;

            networkName = String.Empty;
            devices = new List<Device>();

            xmlrdsettings = new XmlReaderSettings();
            xmlrdsettings.IgnoreComments = true;
            xmlrdsettings.IgnoreWhitespace = true;
            xmlrdsettings.Schemas.Add("", pathToXsdFile);
            xmlrdsettings.ValidationType = ValidationType.Schema;
            //xmlrdsettings.ValidationEventHandler +=
            //    new ValidationEventHandler(EventHandler_vr_ValidationEventHandler);
            reader = XmlReader.Create(pathToXmlFile, xmlrdsettings);

            try
            {
                while(reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (!reader.IsEmptyElement)
                        {
                            switch (reader.Name)
                            {
                                case "Network":
                                    {
                                        if (reader.HasAttributes)
                                        {
                                            // Получаем наименование сети
                                            networkName = reader.GetAttribute("Name");
                                            //network.NetworkName = reader.GetAttribute("Name");
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format(
                                                "Ошибка в строке {0}.Элемент Network не имеет свойства Name",
                                                reader.Settings.LineNumberOffset.ToString()));
                                        }
                                        break;
                                    }
                                case "Device":
                                    {
                                        if (reader.HasAttributes)
                                        {
                                            device = new Device(Byte.Parse(reader.GetAttribute("Address")));
                                            device.Description = reader.GetAttribute("Description");                                          
                                            device.Status = (Status)Enum.Parse(typeof(Status), 
                                                reader.GetAttribute("Status"));
                                            //network.Devices.Add(device);
                                            devices.Add(device);
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format(
                                                "Ошибка в строке {0}.Элемент Device не имеет свойств",
                                                reader.Settings.LineNumberOffset.ToString()));
                                        }
                                        break;
                                    }
                                case "Coil":
                                    {
                                        if (reader.HasAttributes)
                                        {
                                            Boolean value;
                                            UInt16 address = UInt16.Parse(reader.GetAttribute("Address"));

                                            reader.Read();
                                            if (reader.NodeType == XmlNodeType.Element)
                                            {
                                                if (reader.Name == "Value")
                                                {
                                                    reader.Read();
                                                    value = Boolean.Parse(reader.Value);
                                                }
                                                else
                                                {
                                                    throw new Exception(String.Format(
                                                        "Ошибка в строке {0}. Элемент Coil не содержит элемент Value",
                                                        reader.Settings.LineNumberOffset.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент Coil содержит элемент недопустимого типа",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }

                                            reader.Read(); // EndElement Value
                                            reader.Read();
                                            if (reader.NodeType == XmlNodeType.Element)
                                            {
                                                if (reader.Name == "Description")
                                                {
                                                    reader.Read();
                                                    coil = new Coil(address, value, reader.Value);
                                                    //network.Devices[network.Devices.Count - 1].Coils.Add(coil);
                                                    devices[devices.Count - 1].Coils.Add(coil);
                                                }
                                                else
                                                {
                                                    throw new Exception(String.Format(
                                                        "Ошибка в строке {0}. Элемент Coil не содержит элемент Description",
                                                        reader.Settings.LineNumberOffset.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент Coil содержит элемент недопустимого типа",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format(
                                                "Ошибка в строке {0}.Элемент Coil не имеет свойств",
                                                reader.Settings.LineNumberOffset.ToString()));
                                        }
                                        break;
                                    }
                                case "DiscreteInput":
                                    {
                                        if (reader.HasAttributes)
                                        {
                                            Boolean value;
                                            UInt16 address = UInt16.Parse(reader.GetAttribute("Address"));

                                            reader.Read();
                                            if (reader.NodeType == XmlNodeType.Element)
                                            {
                                                if (reader.Name == "Value")
                                                {
                                                    reader.Read();
                                                    value = Boolean.Parse(reader.Value);
                                                }
                                                else
                                                {
                                                    throw new Exception(String.Format(
                                                        "Ошибка в строке {0}. Элемент DiscreteInput не содержит элемент Value",
                                                        reader.Settings.LineNumberOffset.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент DiscreteInput содержит элемент недопустимого типа",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }

                                            reader.Read(); // EndElement Value
                                            reader.Read();
                                            if (reader.NodeType == XmlNodeType.Element)
                                            {
                                                if (reader.Name == "Description")
                                                {
                                                    reader.Read();
                                                    dinput = new DiscreteInput(address, value, reader.Value);
                                                    
                                                    //network.Devices[network.Devices.Count - 1].DiscretesInputs.Add(dinput);
                                                    devices[devices.Count - 1].DiscretesInputs.Add(dinput);
                                                }
                                                else
                                                {
                                                    throw new Exception(String.Format(
                                                        "Ошибка в строке {0}. Элемент DiscreteInput не содержит элемент Description",
                                                        reader.Settings.LineNumberOffset.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент DiscreteInput содержит элемент недопустимого типа",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format(
                                                "Ошибка в строке {0}.Элемент DiscreteInput не имеет свойств",
                                                reader.Settings.LineNumberOffset.ToString()));
                                        }
                                        break;
                                    }
                                case "HoldingRegister":
                                    {
                                        if (reader.HasAttributes)
                                        {
                                            UInt16 value;
                                            UInt16 address = UInt16.Parse(reader.GetAttribute("Address"));

                                            reader.Read();
                                            if (reader.NodeType == XmlNodeType.Element)
                                            {
                                                if (reader.Name == "Value")
                                                {
                                                    reader.Read();
                                                    value = UInt16.Parse(reader.Value);
                                                }
                                                else
                                                {
                                                    throw new Exception(String.Format(
                                                        "Ошибка в строке {0}. Элемент HoldingRegister не содержит элемент Value",
                                                        reader.Settings.LineNumberOffset.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент HoldingRegister содержит элемент недопустимого типа",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }

                                            reader.Read(); // EndElement Value
                                            reader.Read();
                                            if (reader.NodeType == XmlNodeType.Element)
                                            {
                                                if (reader.Name == "Description")
                                                {
                                                    reader.Read();
                                                    hregister = new HoldingRegister(address, value, reader.Value);
                                                    //network.Devices[network.Devices.Count - 1].HoldingRegisters.Add(hregister);
                                                    devices[devices.Count - 1].HoldingRegisters.Add(hregister);
                                                }
                                                else
                                                {
                                                    throw new Exception(String.Format(
                                                        "Ошибка в строке {0}. Элемент HoldingRegister не содержит элемент Description",
                                                        reader.Settings.LineNumberOffset.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент HoldingRegister содержит элемент недопустимого типа",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format(
                                                "Ошибка в строке {0}.Элемент HoldingRegister не имеет свойств",
                                                reader.Settings.LineNumberOffset.ToString()));
                                        }
                                        break; 
                                    }
                                case "InputRegister":
                                    {
                                        if (reader.HasAttributes)
                                        {
                                            UInt16 value;
                                            UInt16 address = UInt16.Parse(reader.GetAttribute("Address"));

                                            reader.Read();
                                            if (reader.NodeType == XmlNodeType.Element)
                                            {
                                                if (reader.Name == "Value")
                                                {
                                                    reader.Read();
                                                    value = UInt16.Parse(reader.Value);
                                                }
                                                else
                                                {
                                                    throw new Exception(String.Format(
                                                        "Ошибка в строке {0}. Элемент InputRegister не содержит элемент Value",
                                                        reader.Settings.LineNumberOffset.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент InputRegister содержит элемент недопустимого типа",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }

                                            reader.Read(); // EndElement Value
                                            reader.Read();
                                            if (reader.NodeType == XmlNodeType.Element)
                                            {
                                                if (reader.Name == "Description")
                                                {
                                                    reader.Read();
                                                    iregister = new InputRegister(address, value, reader.Value);
                                                    //network.Devices[network.Devices.Count - 1].InputRegisters.Add(iregister);
                                                    devices[devices.Count - 1].InputRegisters.Add(iregister);
                                                }
                                                else
                                                {
                                                    throw new Exception(String.Format(
                                                        "Ошибка в строке {0}. Элемент InputRegister не содержит элемент Description",
                                                        reader.Settings.LineNumberOffset.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент InputRegister содержит элемент недопустимого типа",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format(
                                                "Ошибка в строке {0}.Элемент InputRegister не имеет свойств",
                                                reader.Settings.LineNumberOffset.ToString()));
                                        }
                                        break; 
                                    }
                                case "File":
                                    {
                                        file = new File(UInt16.Parse(reader.GetAttribute("Number")),
                                            reader.GetAttribute("Description"));
                                        //network.Devices[network.Devices.Count - 1].Files.Add(file);
                                        devices[devices.Count - 1].Files.Add(file);
                                        break;
                                    }
                                case "Record":
                                    {
                                        UInt16 number = UInt16.Parse(reader.GetAttribute("Number"));
                                        String description = reader.GetAttribute("Description");
                                        // Вычитываем следующий элемент. Это долно быть Value
                                        reader.Read();
                                        if (reader.NodeType == XmlNodeType.Element)
                                        {
                                            if (reader.Name == "Value")
                                            {
                                                reader.Read();
                                                record = new Record(number,
                                                    UInt16.Parse(reader.Value), description);
                                                //device = network.Devices[network.Devices.Count - 1];
                                                //device.Files[device.Files.Count - 1].Records.Add(record);
                                                device = devices[devices.Count - 1];
                                                device.Files[device.Files.Count - 1].Records.Add(record);
                                            }
                                            else
                                            {
                                                throw new Exception(String.Format(
                                                    "Ошибка в строке {0}. Элемент Record не содержит элемент Value",
                                                    reader.Settings.LineNumberOffset.ToString()));
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format(
                                                "Ошибка в строке {0}. Элемент Record содержит элемент недопустимого типа",
                                                reader.Settings.LineNumberOffset.ToString()));
                                        }
                                        break;
                                    }
                            }
                        }
                    } // End of if (reader.NodeType == XmlNodeType.Element)
                } // End of while(reader.Read())
            }
            //catch (XmlException ex)
            //{
            //    if (reader != null)
            //    {
            //        reader.Close();
            //    }

            //    throw;
            //}
            catch //(Exception ex)
            {
                if (reader != null)
                {
                    reader.Close();
                }

                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            // Создаём сеть из полученных данных
            network = new NetworkController(networkName, null);

            foreach (Device item in devices)
            {
                network.Devices.Add(item);
            }

            return network;
        }
Ejemplo n.º 31
0
        //---------------------------------------------------------------------------
        private void AddCoil()
        {
            UInt16 address;
            Device device;
            Coil coil;

            device = (Device)_BindingSourceDevicesList.Current;

            for (address = 0; address <= UInt16.MaxValue; address++)
            {
                if (!device.Coils.Contains(address))
                {
                    coil = new Coil(address, false, String.Empty);
                    device.Coils.Add(coil);
                    _BindingSourceDevicesList.ResetCurrentItem();

                    if (device.Coils.Count > 0)
                    {
                        _ToolStripMenuItemRemoveCoil.Enabled = true;
                    }
                    if (device.Coils.Count == UInt16.MaxValue)
                    {
                        _ToolStripMenuItemAddCoil.Enabled = false;
                    }
                    return;
                }
            }
            throw new InvalidOperationException(
                "Не удалось добавить новый coil в устройство, все адреса заняты");
        }
Ejemplo n.º 32
0
    // Use this for initialization
    void Start()
    {
        coilTracker = GameObject.Find("CoilTracker").GetComponent<Coil>();
        camController = GameObject.Find("Camera Controller").GetComponent<CameraController>();
        matching = false;
        usingGrid = false;
        settingHotSpot = false;
        numGrids = 0;
        scalpHotSpot.pos = null;
        scalpHotSpot.rot = null;
        watch = new Stopwatch();
        logging = false;
        loggingString = new string[6];

        CreateTextArray();

        currentGrid = new Grid("null", new List<TargetPoint>());

        string path = Application.dataPath + @"\Grids\Load";

        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }

        path = Application.dataPath + @"\Grids\Saved";

        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }

        path = Application.dataPath + @"\Logs";

        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }
    }
Ejemplo n.º 33
0
 void Awake()
 {
     editingCoil         = GetComponent <Coil>();
     componentReferences = GetComponent <ComponentReferences>();
     spriteRenderer      = GetComponent <SpriteRenderer>();
 }