Example #1
1
        /// <summary>
        /// Connect to the MCU.
        /// </summary>
        /// <param name="comPort">Com port over which to connect to the MCU.</param>
        public virtual bool Connect(string Address, int rack, int slot)
        {
            // We're connecting...
            this.State = PLCState.Connecting;

            try
            {
                // Open the specified port
                fds.rfd = libnodave.openSocket(102, Address);
                fds.wfd = fds.rfd;
                //If connection successful
                if (fds.rfd > 0)
                {
                    PLCInterface = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP,
                                                               libnodave.daveSpeed187k);
                    PLCInterface.setTimeout(1000000);
                    //	    res=di.initAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
                    PLCConnection = new libnodave.daveConnection(PLCInterface, 0, rack, slot);
                    if (0 == PLCConnection.connectPLC())
                    {
                        // Now we're connected!
                        this.State = PLCState.Connected;
                    }
                }
            }
            catch
            (Exception ex)
            {
                MessageBox.Show("Exception Connecting to Port!\r\n\r\n" + ex.Message);
                //  logger.ErrorException("Exception Connecting to Port", ex);
                this.State = PLCState.Disconnected;
                return(false);
            }
            return(true);
        }
Example #2
1
        /// <summary>
        /// Connect to the MCU.
        /// </summary>
        /// <param name="comPort">Com port over which to connect to the MCU.</param>
        public virtual bool Connect(string Address, int rack, int slot)
        {
            // We're connecting...
            this.State = PLCState.Connecting;

            try
            {
                // Open the specified port
                fds.rfd = libnodave.openSocket(102, Address);
                fds.wfd = fds.rfd;
                //If connection successful
                if (fds.rfd > 0)
                {
                    PLCInterface = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP,
                        libnodave.daveSpeed187k);
                    PLCInterface.setTimeout(1000000);
                    //	    res=di.initAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
                    PLCConnection = new libnodave.daveConnection(PLCInterface, 0, rack, slot);
                    if (0 == PLCConnection.connectPLC())
                    {
                        // Now we're connected!
                        this.State = PLCState.Connected;
                    }
                }
            }
            catch
                (Exception ex)
            {
                MessageBox.Show("Exception Connecting to Port!\r\n\r\n" + ex.Message);
                //  logger.ErrorException("Exception Connecting to Port", ex);
                this.State = PLCState.Disconnected;
                return false;
            }
            return true;
        }
Example #3
0
    static void readSZLAll(libnodave.daveConnection dc)
    {
        byte[] d = new byte[1000];
        int    res, SZLid, indx, SZcount, SZlen, i, j, rid, rind;

        res = dc.readSZL(0, 0, d, 1000);
        Console.WriteLine(" " + res + " " + dc.getAnswLen());
        if ((dc.getAnswLen()) >= 4)
        {
            SZLid = dc.getU16();
            indx  = dc.getU16();
            Console.WriteLine(String.Format("result SZL ID {0:X04} index {1:X02}", SZLid, indx));
            if ((dc.getAnswLen()) >= 8)
            {
                SZlen   = 0x100 * d[4] + d[5];
                SZcount = 0x100 * d[6] + d[7];
                Console.WriteLine("%d elements of %d bytes\n", SZcount, SZlen);
                for (i = 0; i < SZcount; i++)
                {
                    rid  = libnodave.getU16from(d, i * SZlen + 8);
                    rind = 0;
                    Console.WriteLine(String.Format("\nID:{0:X04} index {1:X02}", rid, rind));
                    readSZL(dc, rid, rind);
                }
            }
        }
        Console.WriteLine("\n");
    }
Example #4
0
 public void Close()
 {
     this.m_Dc.disconnectPLC();
     this.IsOpen = false;
     this.m_Dc   = null;
     this.m_Di   = null;
 }
    /// <summary>
    /// This method is used for connecting PLC. The connection status can be checked with "IsConnected" property.
    /// It returns false at unexpected situation.
    /// </summary>
    /// <returns></returns>
    public bool connect_plc()
    {
        bool result = false;

        try
        {
            fds.rfd = libnodave.openSocket(port, ip);
            fds.wfd = fds.rfd;
            di      = new libnodave.daveInterface(fds, "FD1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
            di.setTimeout(10000);
            dc = new libnodave.daveConnection(di, 0, rack, slot);
            if (fds.rfd > 0 && dc.connectPLC() == 0)
            {
                result         = true;
                isDisconnected = false;
            }
            else
            {
                result = false;
            }
        }
        catch (Exception e)
        {
            send_error_message(e, "CONNECTION PROBLEM");
            result = false;
        }
        isConnected = result;
        return(result);
    }
        private int connetti()
        {
            int   i, a = 0, j, res, b = 0, c = 0;
            float d = 0;

            byte[] buf1 = new byte[libnodave.davePartnerListSize];


            fds.rfd = libnodave.openS7online(param.s7online);
            fds.wfd = fds.rfd;
            if (fds.rfd >= 0)
            {
                di = new libnodave.daveInterface(fds, param.IF, param.localMPI, param.useProto, param.speed);
                di.setTimeout(param.timeOut);
                for (i = 0; i < 3; i++)
                {
                    if (0 == di.initAdapter())
                    {
                        initSuccess = true;
                        a           = di.listReachablePartners(buf1);
                        plc.setTextln("daveListReachablePartners List length: " + a);
                        if (a > 0)
                        {
                            for (j = 0; j < a; j++)
                            {
                                if (buf1[j] == libnodave.daveMPIReachable)
                                {
                                    plc.setTextln("Device at address: " + j);
                                }
                            }
                        }
                        break;
                    }
                    else
                    {
                        di.disconnectAdapter();
                    }
                }
                if (!initSuccess)
                {
                    plc.setTextln("Couldn't connect to Adapter!.\n Please try again. You may also try the option -2 for some adapters.");
                    return(-3);
                }

                dc = new libnodave.daveConnection(di, param.plcMPI, 0, 0);

                return(dc.connectPLC());
            }
            else
            {
                plc.setTextln("Couldn't open s7 online ");
                return(-1);
            }
        }
Example #7
0
 private void DeletePLC()
 {
     if (this.m_Dc != null)
     {
         this.m_Di.disconnectAdapter();
         this.m_Dc.disconnectPLC();
         libnodave.closeSocket(this.m_Fds.rfd);
         this.m_Dc = null;
         this.m_Di = null;
     }
 }
Example #8
0
        private void InitPLC()
        {
            this.DeletePLC();
            this.m_Fds.rfd = libnodave.openSocket(102, this.m_IP);
            this.m_Fds.wfd = this.m_Fds.rfd;
            this.m_Di      = new libnodave.daveInterface(this.m_Fds, "PLC", this.m_LocalMPI, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
            this.m_Di.setTimeout(5000);
            this.m_Dc = new libnodave.daveConnection(this.m_Di, this.m_LocalMPI, this.m_Rack, this.m_Slot);

            this.m_PlcState = this.m_Dc.connectPLC();
        }
Example #9
0
 private void button1_Click(object sender, EventArgs e)
 {
     fds.rfd = libnodave.openSocket(102, "192.168.186.130");
     fds.wfd = fds.rfd;
     if (fds.rfd > 0)
     {
         di = new libnodave.daveInterface(fds, "IF1", 2, libnodave.daveProtoISOTCP, libnodave.daveSpeed1500k);//libnodave.daveProtoISOTCP
         di.setTimeout(0xbb8);
         dc = new libnodave.daveConnection(di, 0, 2, 0);
         int res = dc.connectPLC();
         if (res == 0)
         {
             MessageBox.Show("链接到PLC");
         }
     }
 }
Example #10
0
    public static int Main(string[] args)
    {
        int   i, a = 0, j, res, b = 0, c = 0;
        float d = 0;

        fds.rfd = libnodave.setPort(args[0], "38400", 'O');
        fds.wfd = fds.rfd;
        if (fds.rfd > 0)
        {
            di = new libnodave.daveInterface(fds, "IF1", localMPI, libnodave.daveProtoMPI, libnodave.daveSpeed187k);
            di.setTimeout(1000000);
            res = di.initAdapter();
            if (res == 0)
            {
                dc = new libnodave.daveConnection(di, plcMPI, 0, 0);
                if (0 == dc.connectPLC())
                {
                    res = dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
                    if (res == 0)
                    {
                        a = dc.getS32();
                        b = dc.getS32();
                        c = dc.getS32();
                        d = dc.getFloat();
                        Console.WriteLine("FD0: " + a);
                        Console.WriteLine("FD4: " + b);
                        Console.WriteLine("FD8: " + c);
                        Console.WriteLine("FD12: " + d);
                    }
                    else
                    {
                        Console.WriteLine("error " + res + " " + libnodave.daveStrerror(res));
                    }
                }
                dc.disconnectPLC();
            }
            di.disconnectAdapter();
            libnodave.closePort(fds.rfd);
        }
        else
        {
            Console.WriteLine("Couldn't open serial port " + args[0]);
            return(-1);
        }
        return(0);
    }
Example #11
0
    public static int Main(string[] args)
    {
        int   i, a = 0, j, res, b = 0, c = 0;
        float d = 0;

        fds.rfd = libnodave.openSocket(102, args[0]);
        fds.wfd = fds.rfd;
        if (fds.rfd > 0)
        {
            di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
            di.setTimeout(1000000);
//	    res=di.initAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
//	    if(res==0) {
            dc = new libnodave.daveConnection(di, 0, rack, slot);
            if (0 == dc.connectPLC())
            {
                res = dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
                if (res == 0)
                {
                    a = dc.getS32();
                    b = dc.getS32();
                    c = dc.getS32();
                    d = dc.getFloat();
                    Console.WriteLine("FD0: " + a);
                    Console.WriteLine("FD4: " + b);
                    Console.WriteLine("FD8: " + c);
                    Console.WriteLine("FD12: " + d);
                }
                else
                {
                    Console.WriteLine("error " + res + " " + libnodave.daveStrerror(res));
                }
            }
            dc.disconnectPLC();
//	    }
//	    di.disconnectAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
            libnodave.closePort(fds.rfd);
        }
        else
        {
            Console.WriteLine("Couldn't open TCP connaction to " + args[0]);
            return(-1);
        }
        return(0);
    }
Example #12
0
    static void readSZL(libnodave.daveConnection dc, int id, int index)
    {
        int res, SZLid, indx, SZcount, SZlen, i, j, len;

        byte[] ddd = new byte[3000];
        Console.WriteLine(String.Format("Trying to read SZL-ID {0:X04}, index {1:X02}", id, index));
        res = dc.readSZL(id, index, ddd, 3000);
        Console.WriteLine("Function result: " + res + " " + libnodave.daveStrerror(res) + " len:" + dc.getAnswLen());

        if (dc.getAnswLen() >= 4)
        {
            len   = dc.getAnswLen() - 8;
            SZLid = libnodave.getU16from(ddd, 0);
            indx  = libnodave.getU16from(ddd, 2);
            Console.WriteLine(String.Format("result SZL ID {0:X04}, index {1:X02}", SZLid, indx));
            int d = 8;
            if (dc.getAnswLen() >= 8)
            {
                SZlen   = libnodave.getU16from(ddd, 4);
                SZcount = libnodave.getU16from(ddd, 6);
                Console.WriteLine(" " + SZcount + " elements of " + SZlen + " bytes");
                if (len > 0)
                {
                    for (i = 0; i < SZcount; i++)
                    {
                        if (len > 0)
                        {
                            for (j = 0; j < SZlen; j++)
                            {
                                if (len > 0)
                                {
                                    Console.Write(String.Format("{0:X02},", ddd[d]));
                                    d++;
                                }
                                len--;
                            }
                            Console.WriteLine(" ");
                        }
                    }
                }
            }
        }
        Console.WriteLine(" ");
    }
Example #13
0
        public bool ConnectPLC()
        {
            try
            {
                daveSerial.rfd = libnodave.openSocket(plcConf.Port, plcConf.IP);
                daveSerial.wfd = daveSerial.rfd;

                if (daveSerial.rfd > 0)
                {
                    daveInterface = new libnodave.daveInterface(daveSerial, "", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
                    //daveInterface.setTimeout(1000000);
                    if (0 == daveInterface.initAdapter())
                    {
                        daveConnection = new libnodave.daveConnection(daveInterface, 0, plcConf.Rack, plcConf.Slot);
                        if (0 == daveConnection.connectPLC())
                        {
                            return(true);
                        }
                        else
                        {
                            daveConnection.disconnectPLC();
                            libnodave.closeSocket(daveSerial.rfd);
                            return(false);
                        }
                    }
                    else
                    {
                        daveInterface.disconnectAdapter();
                        libnodave.closeSocket(daveSerial.rfd);
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
        public void Connect()
        {
            if (_state == PlcConnectionState.Connect)
            {
                SendPlcException(DEFAULTERRORCODE, ResPlcAccess.StateIsConnect);
                return;
            }

            _daveConnection = new libnodave.daveConnection(_daveInterface, LOCALMPI, _rack, _slot);

            Int32 errorCode = _daveConnection.connectPLC();
            if (errorCode != 0)
            {
                _state = PlcConnectionState.Error;
                SendPlcException(errorCode);
                return;
            }

            _state = PlcConnectionState.Connect;
        }
Example #15
0
 public void Open()
 {
     if (!this.IsOpen)
     {
         this.m_Fds.rfd = libnodave.openSocket(102, this.IP);
         this.m_Fds.wfd = m_Fds.rfd;
         this.m_Di      = new libnodave.daveInterface(this.m_Fds, "PLC", localMPI, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
         this.m_Di.setTimeout(5000);
         this.m_Dc = new libnodave.daveConnection(m_Di, localMPI, this.Rack, this.Slot);
         int retval = this.m_Dc.connectPLC();
         if (retval == 0)
         {
             this.IsOpen = true;
         }
         else
         {
             this.IsOpen = false;
         }
     }
 }
Example #16
0
 public ItemData <byte> ReadByte(DeviceAddress address)
 {
     if (dc != null)
     {
         int res = -1;
         lock (_async)
         {
             res = dc.readBytes(address.Area, address.DBNumber, address.Start, 1, null);
             if (res == 0)
             {
                 return(new ItemData <byte>((byte)dc.getS8(), 0, QUALITIES.QUALITY_GOOD));
             }
         }
         _closed = true; dc = null; _closeTime = DateTime.Now;
         if (OnClose != null)
         {
             OnClose(this, new ShutdownRequestEventArgs(daveStrerror(res)));
         }
     }
     return(new ItemData <byte>(0, 0, QUALITIES.QUALITY_NOT_CONNECTED));;
 }
Example #17
0
 public ItemData <float> ReadFloat(DeviceAddress address)
 {
     if (dc != null)
     {
         int res = -1;
         lock (_async)
         {
             res = dc.readBytes(address.Area, address.DBNumber, address.Start, 4, null);
             if (res == 0)
             {
                 return(new ItemData <float>(dc.getFloat(), 0, QUALITIES.QUALITY_GOOD));
             }
         }
         _closed = true; dc = null; _closeTime = DateTime.Now;
         if (OnError != null)
         {
             OnError(this, new IOErrorEventArgs(daveStrerror(res))); _closeTime = DateTime.Now;
         }
     }
     return(new ItemData <float>(0, 0, QUALITIES.QUALITY_NOT_CONNECTED));;
 }
Example #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            fds.rfd = libnodave.openSocket(102, textBox2.Text);


            fds.wfd = fds.rfd;

            di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
            di.setTimeout(1000);
            res = di.initAdapter();
            try
            {
                dc  = new libnodave.daveConnection(di, 0, 0, 1);
                res = dc.connectPLC();
                MessageBox.Show("连接成功");
            }
            catch (Exception)
            {
                MessageBox.Show("连接失败");
            }
        }
Example #19
0
 public int Open()
 {
     fds.rfd = libnodave.openSocket(_port, _address);
     fds.wfd = fds.rfd;
     if (fds.rfd > 0)
     {
         di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
         di.setTimeout(1000000);
         dc = new libnodave.daveConnection(di, 0, _rack, _slot);
         if (0 == dc.connectPLC())
         {
             IsConnect = true;
         }
         return(0);
     }
     else
     {
         IsConnect = false;
         return(-1);
     }
 }
Example #20
0
    static void loadBlocksOfType(libnodave.daveConnection dc, int blockType, bool doReadout)
    {
        int j, i, len, k;

        int res;

        byte[] blockBuffer = new byte[20000];
        byte[] dbe         = new byte[2000];

        j = dc.ListBlocksOfType(blockType, dbe);

        if (j < 0)
        {
            Console.WriteLine("error " + (-j) + " = " + libnodave.daveStrerror(-j));
            return;
        }
        string blockName = libnodave.blockName(blockType);

        Console.WriteLine(j + " blocks of type " + blockName);

        for (i = 0; i < j; i++)
        {
            int number = BitConverter.ToInt16(dbe, 4 * i + 0);

            Console.WriteLine(libnodave.blockName(blockType) + " " + number);

            if (doReadout)
            {
                len = 1111;
                dc.getProgramBlock(blockType, number, blockBuffer, ref (len));
                blockName = libnodave.blockName(blockType) + number + ".mc7";
                FileStream   fs = new FileStream(blockName, FileMode.CreateNew);
                BinaryWriter w  = new BinaryWriter(fs);
                for (k = 0; k < len; k++)
                {
                    w.Write(blockBuffer[k]);
                }
            }
        }
    }
Example #21
0
        public string FromController()
        {
            libnodave.daveOSserialType fds; //Тип соединения
            libnodave.daveInterface    di;  //Интерфейс соединения
            libnodave.daveConnection   dc;  //Соединение
            int res = 0;

            fds.rfd = libnodave.openSocket(102, "192.168.10.70"); //102-сокет по умолчанию, и адрес контроллера

            fds.wfd = fds.rfd;
            if (fds.rfd > 0)
            {
                di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
                di.setTimeout(1000);
                dc = new libnodave.daveConnection(di, 2, 0, 2); //последние цифры 0-стойка 2-номер слота
                if (0 == dc.connectPLC())
                {
                    res = dc.readBytes(libnodave.daveDB, 28, 78, 4, null); //28-номер DB,78-смещение (адрес переменной), 4-длина, null - буфер записии

                    if (res == 0)                                          //conection OK
                    {
                        float temperatura = dc.getFloat();
                        ViewBag.Temperatura = Math.Round(temperatura, 2).ToString();
                    }
                    else
                    {
                        ViewBag.Err = res + " " + libnodave.daveStrerror(res);
                    }
                }
                dc.disconnectPLC();
                libnodave.closeSocket(fds.rfd);
            }

            else
            {
                ViewBag.Temperatura = "Врменно не доступна";
            }

            return(ViewBag.Temperatura);
        }
Example #22
0
        public ItemData <bool> ReadBit(DeviceAddress address)
        {
            int res = -1;

            if (dc != null)
            {
                lock (_async)
                {
                    res = dc.readBits(address.Area, address.DBNumber, address.Start * 8 + address.Bit, 1, null);//修改了原地址上的Bug
                    if (res == 0)
                    {
                        return(new ItemData <bool>(dc.getS8() != 0, 0, QUALITIES.QUALITY_GOOD));
                    }
                }
                _closed = true; dc = null; _closeTime = DateTime.Now;
                if (OnError != null)
                {
                    OnError(this, new IOErrorEventArgs(daveStrerror(res)));
                }
            }
            return(new ItemData <bool>(false, 0, QUALITIES.QUALITY_NOT_CONNECTED));
        }
Example #23
0
 public ItemData <string> ReadString(DeviceAddress address, ushort size = 0xFF)
 {
     if (dc != null)
     {
         byte[] buffer = new byte[size];
         int    res    = -1;
         lock (_async)
         {
             res = dc.readBytes(address.Area, address.DBNumber, address.Start, size, buffer);
         }
         if (res == 0)
         {
             return(new ItemData <string>(Utility.ConvertToString(buffer), 0, QUALITIES.QUALITY_GOOD));
         }
         _closed = true; dc = null; _closeTime = DateTime.Now;
         if (OnError != null)
         {
             OnError(this, new IOErrorEventArgs(daveStrerror(res)));
         }
     }
     return(new ItemData <string>(string.Empty, 0, QUALITIES.QUALITY_NOT_CONNECTED));
 }
Example #24
0
 public byte[] ReadBytes(DeviceAddress address, ushort len)//从PLC中读取自己数组
 {
     if (dc != null)
     {
         byte[] buffer = new byte[len];
         int    res    = -1;
         lock (_async)
         {
             res = dc == null ? -1 : dc.readBytes(address.Area, address.DBNumber, address.Start, len, buffer);
         }
         if (res == 0)
         {
             return(buffer);
         }
         _closed = true; dc = null; _closeTime = DateTime.Now;
         if (OnError != null)
         {
             OnError(this, new IOErrorEventArgs(daveStrerror(res))); _closeTime = DateTime.Now;
         }
     }
     return(null);
 }
        public bool Connect()
        {
            try
            {
                _OSSerialType.rfd = libnodave.openSocket(_PortNumber, _IPAdress);
                _OSSerialType.wfd = _OSSerialType.rfd;

                if (_OSSerialType.rfd > 0)
                {
                    _Interface = new libnodave.daveInterface(_OSSerialType, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
                    _Interface.setTimeout(1000000);

                    _Connection = new libnodave.daveConnection(_Interface, 0, _Rack, _Slot);
                    _Connected = _Connection.connectPLC() == 0 ? true : false;
                }
            }
            catch
            {
                _Connected = false;
            }
            return _Connected;
        }
Example #26
0
        public bool Connect()
        {
            lock (_async)
            {
                if (IsConnect)
                {
                    return(true);
                }
                double sec = (DateTime.Now - _closeTime).TotalMilliseconds;
                if (sec < 6000)
                {
                    System.Threading.Thread.Sleep(6000 - (int)sec);
                }
                fds.rfd = libnodave.openSocket(102, _IP);
                fds.wfd = fds.rfd;
                if (fds.rfd > 0)
                {
                    di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
                    di.setTimeout(TimeOut);
                    //	    res=di.initAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
                    //	    if(res==0) {

                    dc = new libnodave.daveConnection(di, 0, _rack, _slot);     // logNet.RecordMessage(HslMessageDegree.INFO,"断开已重连" +DateTime.Now);


                    if (0 == dc.connectPLC())
                    {
                        _closed    = false;
                        _isconnect = true;
                        return(true);
                    }
                }
                //if (dc != null) dc.disconnectPLC();
                //libnodave.closeSocket(fds.rfd);
            }
            IsConnect = false;
            _closed   = true;
            return(false);
        }
Example #27
0
        private void button1_Click(object sender, EventArgs e)
        {
            fds.rfd = libnodave.openSocket(102, IP);
            fds.wfd = fds.rfd;

            if (fds.rfd > 0)
            {
                di = new libnodave.daveInterface(fds, "IF1", localMPI, useProto, speed);
                di.setTimeout(5000000);

                if (0 == di.initAdapter())
                {
                    initSuccess = 1;
                    dc          = new libnodave.daveConnection(di, plcMPI, rack, slot);
                    int ret = dc.connectPLC();
                    if (ret == 0)
                    {
                        Connection          = true;
                        this.lblstatus.Text = "已经连接PLC" + IP;
                    }
                }
            }
        }
Example #28
0
    public static int Main(string[] args)
    {
        int i,a=0,j,res,b=0,c=0;
        float d=0;

        fds.rfd=libnodave.setPort(args[0],"38400",'O');
        fds.wfd=fds.rfd;
        if (fds.rfd>0) {
        di =new libnodave.daveInterface(fds, "IF1", localMPI, libnodave.daveProtoMPI, libnodave.daveSpeed187k);
            di.setTimeout(1000000);
        res=di.initAdapter();
        if(res==0) {
        dc = new libnodave.daveConnection(di,plcMPI, 0, 0);
        if (0==dc.connectPLC()) {
            res=dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
            if (res==0) {
                a=dc.getS32();
                b=dc.getS32();
                c=dc.getS32();
            d=dc.getFloat();
            Console.WriteLine("FD0: " + a);
            Console.WriteLine("FD4: " + b);
            Console.WriteLine("FD8: " + c);
            Console.WriteLine("FD12: " + d);
            } else
            Console.WriteLine("error "+res+" "+libnodave.daveStrerror(res));
        }
        dc.disconnectPLC();
        }
        di.disconnectAdapter();
        libnodave.closePort(fds.rfd);
        } else {
        Console.WriteLine("Couldn't open serial port "+args[0]);
        return -1;
        }
        return 0;
    }
Example #29
0
    public static int Main(string[] args)
    {
        int i,a=0,j,res,b=0,c=0;
        float d=0;

        fds.rfd=libnodave.openSocket(102,args[0]);
        fds.wfd=fds.rfd;
        if (fds.rfd>0) {
        di =new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
            di.setTimeout(1000000);
        //	    res=di.initAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
        //	    if(res==0) {
        dc = new libnodave.daveConnection(di,0 , rack, slot);
        if (0==dc.connectPLC()) {
            res=dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
            if (res==0) {
                a=dc.getS32();
                b=dc.getS32();
                c=dc.getS32();
            d=dc.getFloat();
            Console.WriteLine("FD0: " + a);
            Console.WriteLine("FD4: " + b);
            Console.WriteLine("FD8: " + c);
            Console.WriteLine("FD12: " + d);
            } else
            Console.WriteLine("error "+res+" "+libnodave.daveStrerror(res));
        }
        dc.disconnectPLC();
        //	    }
        //	    di.disconnectAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
        libnodave.closePort(fds.rfd);
        } else {
        Console.WriteLine("Couldn't open TCP connaction to "+args[0]);
        return -1;
        }
        return 0;
    }
Example #30
0
    public static int Main(string[] args)
    {
        int i,a=0,j,res,b=0,c=0;
        float d=0;
        byte[] buf1=new byte[libnodave.davePartnerListSize];

        if (args.Length <1) {
        usage();
        return -1;
        }

        while (args[adrPos][0]=='-') {
        if (args[adrPos].StartsWith("--debug=")) {
        libnodave.daveSetDebug(Convert.ToInt32(args[adrPos].Substring(8)));
        Console.WriteLine("setting debug to: ",Convert.ToInt32(args[adrPos].Substring(8)));
        } else if (args[adrPos].StartsWith("-d")) {
        libnodave.daveSetDebug(libnodave.daveDebugAll);
        } else if (args[adrPos].StartsWith("-s")) {
        doStop=true;
        } else if (args[adrPos].StartsWith("-w")) {
        doWrite=true;
        } else if (args[adrPos].StartsWith("-b")) {
        doBenchmark=true;
        } else if (args[adrPos].StartsWith("--readoutall")) {
        doReadout=true;
        doSFBandSFC=true;
        } else if (args[adrPos].StartsWith("--readout")) {
        doReadout=true;
        } else if (args[adrPos].StartsWith("-r")) {
        doRun=true;
        } else if (args[adrPos].StartsWith("-e")) {
        doExperimental=true;
        } else if (args[adrPos].StartsWith("--local=")) {
        localMPI=Convert.ToInt32(args[adrPos].Substring(8));
        Console.WriteLine("setting local MPI address to: "+localMPI);
        } else if (args[adrPos].StartsWith("--mpi=")) {
        plcMPI=Convert.ToInt32(args[adrPos].Substring(6));
        Console.WriteLine("setting MPI address of PLC to: "+plcMPI);
        } else if (args[adrPos].StartsWith("--mpi2=")) {
        plc2MPI=Convert.ToInt32(args[adrPos].Substring(7));
        Console.WriteLine("setting MPI address of 2md PLC to: "+plc2MPI);
        } else if (args[adrPos].StartsWith("--wbit=")) {
        wbit=Convert.ToInt32(args[adrPos].Substring(7));
        Console.WriteLine("setting bit number: "+wbit);
        doWbit=true;
        } else if (args[adrPos].StartsWith("-z")) {
        doSZLread=true;
        } else if (args[adrPos].StartsWith("-a")) {
        doSZLreadAll=true;
        } else if (args[adrPos].StartsWith("-m")) {
        doMultiple=true;
        } else if (args[adrPos].StartsWith("-c")) {
        doClear=true;
        } else if (args[adrPos].StartsWith("-n")) {
        doNewfunctions=true;
        } else if (args[adrPos].StartsWith("-2")) {
        useProto=libnodave.daveProtoMPI2;
        } else if (args[adrPos].StartsWith("-3")) {
        useProto=libnodave.daveProtoMPI3;
        } else if (args[adrPos].StartsWith("-9")) {
         	    speed=libnodave.daveSpeed9k;
         	} else if (args[adrPos].StartsWith("-19")) {
         	    speed=libnodave.daveSpeed19k;
         	} else if (args[adrPos].StartsWith("-45")) {
         	    speed=libnodave.daveSpeed45k;
         	} else if (args[adrPos].StartsWith("-93")) {
         	    speed=libnodave.daveSpeed93k;
         	} else if (args[adrPos].StartsWith("-500")) {
         	    speed=libnodave.daveSpeed500k;
         	} else if (args[adrPos].StartsWith("-1500")) {
         	    speed=libnodave.daveSpeed1500k;
         	}

        adrPos++;
        if (args.Length<=adrPos) {
        usage();
        return -1;
        }
        }

        fds.rfd=libnodave.setPort(args[adrPos],"38400",'O');
        fds.wfd=fds.rfd;
        if (fds.rfd>0) {
        di =new libnodave.daveInterface(fds, "IF1", localMPI, useProto, speed);
            di.setTimeout(5000000);
            for (i=0; i<3; i++) {
        if (0==di.initAdapter()) {
            initSuccess=1;
        //		    a= libnodave.daveListReachablePartners(di,buf1);
            a= di.listReachablePartners(buf1);
            Console.WriteLine("daveListReachablePartners List length: "+a);
            if (a>0) {
            for (j=0;j<a;j++) {
                if (buf1[j]==libnodave.daveMPIReachable)
                Console.WriteLine("Device at address: "+j);
            }
            }
            break;
        } else di.disconnectAdapter();
        }
        if (initSuccess==0) {
            Console.WriteLine("Couldn't connect to Adapter!.\n Please try again. You may also try the option -2 for some adapters.");
            return -3;
        }

        dc = new libnodave.daveConnection(di,plcMPI,0,0);

        if (0==dc.connectPLC()) {;
        res=dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
        if (res==0) {
                a=dc.getS32();
                b=dc.getS32();
                c=dc.getS32();
            d=dc.getFloat();
            Console.WriteLine("FD0: " + a);
            Console.WriteLine("FD4: " + b);
            Console.WriteLine("FD8: " + c);
            Console.WriteLine("FD12: " + d);
        } else
            Console.WriteLine("error "+res+" "+libnodave.daveStrerror(res));

        if(doExperimental) {
            Console.WriteLine("Trying to read outputs");
            res=dc.readBytes(libnodave.daveOutputs, 0, 0, 2, null);
            Console.WriteLine("function result: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            if (res==0) {
                Console.Write("Bytes:");
            for (b=0; b<dc.getAnswLen(); b++) {
                c=dc.getU8();
                Console.Write(String.Format(" {0:X0}, ",c));
            }
            Console.WriteLine("");
            }
            a=0x01;
            Console.WriteLine("Trying to write outputs");
            res=dc.writeBytes(libnodave.daveOutputs, 0, 0, 1, BitConverter.GetBytes(a));
            Console.WriteLine("function result: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            libnodave.daveSetDebug(libnodave.daveDebugAll);
            res=dc.force200(libnodave.daveOutputs,0,0);
            Console.WriteLine("function result: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            libnodave.daveSetDebug(0);
            res=dc.force200(libnodave.daveOutputs,0,1);
            Console.WriteLine("function result of force: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            wait();

            res=dc.force200(libnodave.daveOutputs,0,2);
            Console.WriteLine("function result of force: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            wait();
            res=dc.force200(libnodave.daveOutputs,0,3);
            Console.WriteLine("function result of force: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            wait();
            res=dc.force200(libnodave.daveOutputs,1,4);
            Console.WriteLine("function result of force: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            wait();
            res=dc.force200(libnodave.daveOutputs,2,5);
            Console.WriteLine("function result of force: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            wait();
            res=dc.force200(libnodave.daveOutputs,3,7);
            Console.WriteLine("function result of force: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            wait();
            Console.WriteLine("Trying to read outputs again\n");
            res=dc.readBytes(libnodave.daveOutputs, 0, 0, 4, null);
            Console.WriteLine("function result: "+res+"="+libnodave.daveStrerror(res)+" "+dc.getAnswLen());
            if (res==0) {
                Console.Write("Bytes:");
            for (b=0; b<dc.getAnswLen(); b++) {
                c=dc.getU8();
                Console.Write(String.Format(" {0:X0}, ",c));
            }
            Console.WriteLine("");
            }
        }

        if(doWrite) {
                Console.WriteLine("Now we write back these data after incrementing the integers by 1,2 and 3 and the float by 1.1.\n");
                wait();
        /*
        Attention! you need to daveSwapIed little endian variables before using them as a buffer for
        daveWriteBytes() or before copying them into a buffer for daveWriteBytes()!
        */
                a=libnodave.daveSwapIed_32(a+1);
            dc.writeBytes(libnodave.daveFlags,0,0,4,BitConverter.GetBytes(a));
                    b=libnodave.daveSwapIed_32(b+2);
            dc.writeBytes(libnodave.daveFlags,0,4,4,BitConverter.GetBytes(b));
                c=libnodave.daveSwapIed_32(c+3);
            dc.writeBytes(libnodave.daveFlags,0,8,4,BitConverter.GetBytes(c));
                    d=libnodave.toPLCfloat(d+1.1f);
                dc.writeBytes(libnodave.daveFlags,0,12,4,BitConverter.GetBytes(d));
        /*
         *   Read back and show the new values, so users may notice the difference:
         */
                dc.readBytes(libnodave.daveFlags,0,0,16, null);
            a=dc.getU32();
                    b=dc.getU32();
            c=dc.getU32();
                d=dc.getFloat();
            Console.WriteLine("FD0: "+a);
            Console.WriteLine("FD4: "+b);
            Console.WriteLine("FD8: "+c);
            Console.WriteLine("FD12: "+d);
        } // doWrite

        if(doClear) {
                Console.WriteLine("Now writing 0 to the bytes FB0...FB15.\n");
        //    		    wait();
            byte[] aa={0,0,0,0};
                dc.writeBytes(libnodave.daveFlags,0,0,4,aa);
                dc.writeBytes(libnodave.daveFlags,0,4,4,aa);
            dc.writeBytes(libnodave.daveFlags,0,8,4,aa);
                dc.writeBytes(libnodave.daveFlags,0,12,4,aa);
            dc.readBytes(libnodave.daveFlags,0,0,16, null);
                a=dc.getU32();
                b=dc.getU32();
                c=dc.getU32();
                d=dc.getFloat();
            Console.WriteLine("FD0: "+a);
            Console.WriteLine("FD4: "+b);
            Console.WriteLine("FD8: "+c);
            Console.WriteLine("FD12: "+d);
        } // doClear

        if(doSZLread) {
            readSZL(dc,0x92,0x0);
                readSZL(dc,0xB4,0x1024);
            readSZL(dc,0x111,0x1);
            readSZL(dc,0xD91,0x0);
            readSZL(dc,0x232,0x4);
            readSZL(dc,0x1A0,0x0);
            readSZL(dc,0x0A0,0x0);
        }

        if(doSZLreadAll) {
            readSZLAll(dc);
        }

        if(doStop) {
            dc.stop();
        }
        if(doRun) {
            dc.start();
        }
        if(doBenchmark) {
            rBenchmark(dc,libnodave.daveFlags);
        }

        if(doReadout) {
            loadBlocksOfType(dc, libnodave.daveBlockType_OB, doReadout);
            loadBlocksOfType(dc, libnodave.daveBlockType_FC, doReadout);
            loadBlocksOfType(dc, libnodave.daveBlockType_FB, doReadout);
            loadBlocksOfType(dc, libnodave.daveBlockType_DB, doReadout);
            loadBlocksOfType(dc, libnodave.daveBlockType_SDB, doReadout);
        }

        if(doNewfunctions) {
            int saveDebug=libnodave.daveGetDebug();

            Console.WriteLine("Trying to read two consecutive bits from DB11.DBX0.1");;
            res=dc.readBits(libnodave.daveDB, 11, 1, 2, null);
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));

            Console.WriteLine("Trying to read no bit (length 0) from DB17.DBX0.1");
            res=dc.readBits(libnodave.daveDB, 17, 1, 0, null);
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));

            libnodave.daveSetDebug(libnodave.daveGetDebug()|libnodave.daveDebugPDU);
            Console.WriteLine("Trying to read a single bit from DB17.DBX0.3\n");
            res=dc.readBits(libnodave.daveDB, 17, 3, 1, null);
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));

            Console.WriteLine("Trying to read a single bit from E0.2\n");
            res=dc.readBits(libnodave.daveInputs, 0, 2, 1, null);
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));

            a=0;
            Console.WriteLine("Writing 0 to EB0\n");
            res=dc.writeBytes(libnodave.daveOutputs, 0, 0, 1, BitConverter.GetBytes(libnodave.daveSwapIed_32(a)));
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));

            a=1;
            Console.WriteLine("Trying to set single bit E0.5\n");
            res=dc.writeBits(libnodave.daveOutputs, 0, 5, 1, BitConverter.GetBytes(libnodave.daveSwapIed_32(a)));
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));

            Console.WriteLine("Trying to read 1 byte from AAW0\n");
            res=dc.readBytes(libnodave.daveAnaIn, 0, 0, 2, null);
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));

            a=2341;
            Console.WriteLine("Trying to write 1 word (2 bytes) to AAW0\n");
            res=dc.writeBytes(libnodave.daveAnaOut, 0, 0, 2, BitConverter.GetBytes(libnodave.daveSwapIed_32(a)));
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));

            Console.WriteLine("Trying to read 4 items from Timers\n");
            res=dc.readBytes(libnodave.daveTimer, 0, 0, 4, null);
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));
            if(res==0) {
            d=dc.getSeconds();
            Console.WriteLine("Time: %0.3f, ",d);
                d=dc.getSeconds();
            Console.WriteLine("%0.3f, ",d);
            d=dc.getSeconds();
            Console.WriteLine("%0.3f, ",d);
            d=dc.getSeconds();
            Console.WriteLine(" %0.3f\n",d);

                d=dc.getSecondsAt(0);
                Console.WriteLine("Time: %0.3f, ",d);
                d=dc.getSecondsAt(2);
            Console.WriteLine("%0.3f, ",d);
                d=dc.getSecondsAt(4);
                Console.WriteLine("%0.3f, ",d);
                d=dc.getSecondsAt(6);
                Console.WriteLine(" %0.3f\n",d);
            }

            Console.WriteLine("Trying to read 4 items from Counters\n");
            res=dc.readBytes(libnodave.daveCounter, 0, 0, 4, null);
            Console.WriteLine("function result:" + res+ "="+libnodave.daveStrerror(res));
            if(res==0) {
                c=dc.getCounterValue();
                Console.WriteLine("Count: %d, ",c);
            c=dc.getCounterValue();
                Console.WriteLine("%d, ",c);
            c=dc.getCounterValue();
            Console.WriteLine("%d, ",c);
            c=dc.getCounterValue();
                Console.WriteLine(" %d\n",c);

            c=dc.getCounterValueAt(0);
                Console.WriteLine("Count: %d, ",c);
                c=dc.getCounterValueAt(2);
                Console.WriteLine("%d, ",c);
                c=dc.getCounterValueAt(4);
                Console.WriteLine("%d, ",c);
                c=dc.getCounterValueAt(6);
                Console.WriteLine(" %d\n",c);
            }

            libnodave.PDU p=dc.prepareReadRequest();
            p.addVarToReadRequest(libnodave.daveInputs,0,0,1);
            p.addVarToReadRequest(libnodave.daveFlags,0,0,4);
            p.addVarToReadRequest(libnodave.daveDB,6,20,2);
            p.addVarToReadRequest(libnodave.daveTimer,0,0,4);
            p.addVarToReadRequest(libnodave.daveTimer,0,1,4);
            p.addVarToReadRequest(libnodave.daveTimer,0,2,4);
            p.addVarToReadRequest(libnodave.daveCounter,0,0,4);
            p.addVarToReadRequest(libnodave.daveCounter,0,1,4);
            p.addVarToReadRequest(libnodave.daveCounter,0,2,4);
            libnodave.resultSet rs=new libnodave.resultSet();
                res=dc.execReadRequest(p, rs);
            libnodave.daveSetDebug(saveDebug);
        }

        //		System.GarbageCollect();

        if(doMultiple) {
                Console.WriteLine("Now testing read multiple variables.\n"
                    +"This will read 1 Byte from inputs,\n"
                    +"4 bytes from flags, 2 bytes from DB6,\n"
                    +"and other 2 bytes from flags");
                wait();
            libnodave.PDU p=dc.prepareReadRequest();
            p.addVarToReadRequest(libnodave.daveInputs,0,0,1);
            p.addVarToReadRequest(libnodave.daveFlags,0,0,4);
            p.addVarToReadRequest(libnodave.daveDB,6,20,2);
            p.addVarToReadRequest(libnodave.daveFlags,0,12,2);
            p.addBitVarToReadRequest(libnodave.daveFlags, 0, 25 /* 25 is 3.1*/, 1);
            libnodave.resultSet rs=new libnodave.resultSet();
            res=dc.execReadRequest(p, rs);

            Console.Write("Input Byte 0: ");
            res=dc.useResult(rs, 0); // first result
            if (res==0) {
            a=dc.getU8();
                Console.WriteLine(a);
            } else
            Console.WriteLine("*** Error: "+libnodave.daveStrerror(res));

            Console.Write("Flag DWord 0: ");
            res=dc.useResult(rs, 1); // 2nd result
            if (res==0) {
            a=dc.getS16();
                Console.WriteLine(a);
            } else
            Console.WriteLine("*** Error: "+libnodave.daveStrerror(res));

            Console.Write("DB 6 Word 20: ");
            res=dc.useResult(rs, 2); // 3rd result
            if (res==0) {
            a=dc.getS16();
                Console.WriteLine(a);
            } else
            Console.WriteLine("*** Error: "+libnodave.daveStrerror(res));

            Console.Write("Flag Word 12: ");
            res=dc.useResult(rs, 3); // 4th result
            if (res==0) {
            a=dc.getU16();
                Console.WriteLine(a);
                } else
                Console.WriteLine("*** Error: "+libnodave.daveStrerror(res));

            Console.Write("Flag F3.1: ");
            res=dc.useResult(rs, 4); // 4th result
            if (res==0) {
            a=dc.getU8();
                Console.WriteLine(a);
            } else
            Console.WriteLine("*** Error: "+libnodave.daveStrerror(res));

            Console.Write("non existing result (we read 5 items, but try to use a 6th one): ");
            res=dc.useResult(rs, 5); // 5th result
            if (res==0) {
            a=dc.getU16();
                Console.WriteLine(a);
            } else
            Console.WriteLine("*** Error: "+libnodave.daveStrerror(res));

            if (doWrite){
            Console.WriteLine("Now testing write multiple variables:\n"
                +"IB0, FW0, QB0, DB6:DBW20 and DB20:DBD24 in a single multiple write.");
            wait();
        //			libnodave.daveSetDebug(0xffff);
            byte[] aa={0};
                libnodave.PDU p2=dc.prepareWriteRequest();
            p2.addVarToWriteRequest(libnodave.daveInputs,0,0,1, aa);
            p2.addVarToWriteRequest(libnodave.daveFlags,0,4,2, aa);
                p2.addVarToWriteRequest(libnodave.daveOutputs,0,0,2, aa);
            p2.addVarToWriteRequest(libnodave.daveDB,6,20,2, aa);
            p2.addVarToWriteRequest(libnodave.daveDB,20,24,4, aa);
            aa[0]=1;
            p2.addBitVarToWriteRequest(libnodave.daveFlags, 0, 27 /* 27 is 3.3*/, 1, aa);
            rs =new libnodave.resultSet();
            res=dc.execWriteRequest(p2, rs);
            Console.WriteLine("Result code for the entire multiple write operation: "+res+"="+libnodave.daveStrerror(res));
        /*
        //	I could list the single result codes like this, but I want to tell
        //	which item should have been written, so I do it in 5 individual lines:

            for (i=0;i<rs.numResults;i++){
                res=rs.results[i].error;
                Console.WriteLine("result code from writing item %d: %d=%s\n",i,res,libnodave.libnodave.daveStrerror(res));
            }
        */
            int err=rs.getErrorOfResult(0);
            Console.WriteLine("Result code for writing IB0:       "+err+"="+libnodave.daveStrerror(err));
            err=rs.getErrorOfResult(1);
            Console.WriteLine("Result code for writing FW4:       "+err+"="+libnodave.daveStrerror(err));
            err=rs.getErrorOfResult(2);
            Console.WriteLine("Result code for writing QB0:       "+err+"="+libnodave.daveStrerror(err));
            err=rs.getErrorOfResult(3);
            Console.WriteLine("Result code for writing DB6:DBW20: "+err+"="+libnodave.daveStrerror(err));
            err=rs.getErrorOfResult(4);
            Console.WriteLine("Result code for writing DB20:DBD24:"+err+"="+libnodave.daveStrerror(err));
            err=rs.getErrorOfResult(5);
            Console.WriteLine("Result code for writing F3.3:      "+err+"="+libnodave.daveStrerror(err));
        /*
         *   Read back and show the new values, so users may notice the difference:
         */
                dc.readBytes(libnodave.daveFlags,0,0,16, null);
                a=dc.getU32();
                b=dc.getU32();
                c=dc.getU32();
                d=dc.getFloat();
                Console.WriteLine("FD0: %d\n",a);
            Console.WriteLine("FD4: %d\n",b);
            Console.WriteLine("FD8: %d\n",c);
                Console.WriteLine("FD12: %f\n",d);
            } // doWrite
        }

        dc.disconnectPLC();
        }
        di.disconnectAdapter();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("Here we are");
        } else {
        Console.WriteLine("Couldn't open serial port "+args[adrPos]);
        return -1;
        }
        return 0;
    }
Example #31
0
    public static int Main(string[] args)
    {
        int i;
        int rack, slot;
        int res;
        int readDB, readstart, readnumberofbytes;
        int writeDB, writestart, writenumberofbytes;
        int area = 0;

        var writebuffer = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        var readbuffer = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

        string PLC = "255.255.255.255";

        libnodave.daveSetDebug(libnodave.daveDebugRawRead);

        if (args.Length != 9)
        {
            Console.WriteLine("");
            Console.WriteLine("Usage:");
            Console.WriteLine("./S7koppelvlak [ipaddress] [rack] [slot] [readDB] [startbyte] [numberofbytes] [writeDB] [startbyte] [numberofbytes]");
            Console.WriteLine("");
            Console.WriteLine("Examples:");
            Console.WriteLine("./S7koppelvlak 172.24.40.191 0 3 DB10 0 16 DB20 17 16");
            Console.WriteLine("");
            Console.WriteLine("./S7koppelvlak 172.24.40.191 0 3 DB100 128 32 DB100 0 64");
            Console.WriteLine("");
            return(-4);
        }

        for (i = 0; i < 9; i++)
        {
            Console.WriteLine("" + args[i]);
        }

        PLC  = args[0];
        rack = Convert.ToInt32(args[1]);
        slot = Convert.ToInt32(args[2]);

        readDB            = Convert.ToInt32(args[3]);
        readstart         = Convert.ToInt32(args[4]);
        readnumberofbytes = Convert.ToInt32(args[5]);

        writeDB            = Convert.ToInt32(args[6]);
        writestart         = Convert.ToInt32(args[7]);
        writenumberofbytes = Convert.ToInt32(args[8]);

        Console.WriteLine("Connection PLC " + PLC + ", rack " + Convert.ToString(rack) + ", slot " + Convert.ToString(slot));
        Console.WriteLine("Read block  : DB" + Convert.ToString(readDB) + "[" + Convert.ToString(readstart) + ".." + Convert.ToString(readstart + readnumberofbytes - 1) + "]");
        Console.WriteLine("Write block : DB" + Convert.ToString(writeDB) + "[" + Convert.ToString(writestart) + ".." + Convert.ToString(writestart + writenumberofbytes - 1) + "]");

        area    = libnodave.daveDB;
        fds.rfd = libnodave.openSocket(102, PLC);
        fds.wfd = fds.rfd;
        if (fds.rfd <= 0)
        {
            return(-5);
        }
        else
        {
            di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
            di.setTimeout(1000000);
            res = di.initAdapter();
            if (res != 0)
            {
                return(-4);
            }
            else
            {
                dc = new libnodave.daveConnection(di, 0, rack, slot);
                if (dc.connectPLC() != 0)
                {
                    Console.WriteLine("Couldn't open TCP connaction to " + args[0]);
                    return(-2);
                }
                else
                {
                    while (true)
                    {
                        // Incoming data
                        res = dc.readBytes(area, readDB, readstart, readnumberofbytes, null);
                        if (res == 0)
                        {
                            for (i = 0; i < readnumberofbytes; i++)
                            {
                                readbuffer[i] = (System.Byte)dc.getU8();
                            }
                        }

                        // Copy incoming data to PiFace Digital board outputs...
                        Console.WriteLine(readbuffer);
                        // Copy inputs form PiFace Digital board to writebuffer...

                        // Outgoing data
                        for (i = 0; i < writenumberofbytes; i++)
                        {
                            writebuffer[i] = (byte)i;
                        }
                        res = dc.writeBytes(area, writeDB, writestart, writenumberofbytes, writebuffer);
                        Thread.Sleep(1000);
                    }
                    dc.disconnectPLC();
                }
                di.disconnectAdapter();
                libnodave.closeSocket(fds.rfd);
                return(0);
            }
        }
    }
Example #32
0
        void ReadProdave_UW()
        {
            try
            {
                this.Invoke((EventHandler) delegate
                {
                    lblPLC.Text = "开始连接PLC" + DateTime.Now.ToString();
                });
                libnodave.daveOSserialType fds;
                libnodave.daveInterface    di;
                libnodave.daveConnection   dc;
                byte[] allBytes = new byte[30000];
                int    rack = 0;
                int    slot = 1;
                byte[] ZeroBytes = new byte[255];
                int    i, a = 0, j, res, b = 0, c = 0;
                float  d         = 0;
                int    iTotalLen = 3720;
                int    dbNum     = 666;
                for (int ii = 0; ii < 254; ii++)
                {
                    ZeroBytes[ii] = 0;
                }
                fds.rfd = libnodave.openSocket(102, "192.168.1.63");//192.168.1.63                172.29.238.86
                fds.wfd = fds.rfd;
                if (fds.rfd > 0)
                {
                    di = new libnodave.daveInterface(fds, "IF2", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed1500k);
                    di.setTimeout(1000000);
                    //    res=di.initAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
                    //	    if(res==0) {
                    dc = new libnodave.daveConnection(di, 0, rack, slot);                //  MessageBox.Show(dc.connectPLC().ToString());
                    //  libnodave.daveexecWriteRequest
                    if (0 == dc.connectPLC())
                    {
                        byte[] bt    = new byte[] { 1 };
                        byte[] btBC  = new byte[32];
                        byte[] btBC2 = new byte[16];
                        this.Invoke((EventHandler) delegate
                        {
                            lblPLC.Text      = "PLC连接成功" + DateTime.Now.ToString();
                            lblPLC.BackColor = Color.Lime;
                        });
                        bPLCThread = true;
                        if (bPLCThread)
                        {
                            this.Invoke((EventHandler) delegate
                            {
                                lblPLC.Text = "reading" + DateTime.Now.ToString();
                                //lblPLC.BackColor = Color.Lime;
                            });
                            Thread.Sleep(20);
                            byte[]    dcBytes = new byte[255];
                            int       iPos    = 0;
                            Stopwatch sw      = new Stopwatch();
                            sw.Reset();
                            sw.Start();
                            while (iPos < iTotalLen)
                            {
                                #region Reading....
                                int iLen = 200;
                                if (iTotalLen - iPos < 200)
                                {
                                    iLen = iTotalLen - iPos;
                                }
                                Array.Copy(ZeroBytes, dcBytes, 200);
                                res = dc.readBytes(libnodave.daveDB, 76, iPos, iLen, dcBytes);
                                Array.Copy(dcBytes, 0, allBytes, iPos, iLen);
                                sw.Stop();
                                int iResult = 0;
                                if (res == 0)
                                {
                                    this.Invoke((EventHandler) delegate
                                    {
                                        lblPLC.Text = "read ok" + DateTime.Now.ToString() + "  " + dcBytes[4].ToString() + " " + sw.ElapsedMilliseconds.ToString() + " " + iPos.ToString();
                                        //lblPLC.BackColor = Color.Lime;
                                        //   textBox1.Text = lblPLC.Text + "\r\n" + textBox1.Text;
                                    });
                                    Thread.Sleep(2);
                                    sw.Start();
                                    #region
                                    //ig_Count = 0;
                                    //for (int ii = 0; ii < 30; ii++)
                                    //{
                                    //    btBC[ii] = (byte)dc.getU8At(0 + ii);
                                    //}
                                    //for (int ii = 0; ii < 16; ii++)
                                    //{
                                    //    btBC2[ii] = (byte)dc.getU8At(50 + ii);
                                    //}
                                    //iResult = (int)(dc.getU8At(100));
                                    //int iCode = dc.getU16At(80);
                                    //this.Invoke((EventHandler)delegate
                                    //    {
                                    //        // txtFixNum.Text = iFixNum.ToString();
                                    //        lblCode.Text = iCode.ToString();
                                    //        lbBC.Text = System.Text.Encoding.Default.GetString(btBC);
                                    //        lbFix.Text = System.Text.Encoding.Default.GetString(btBC2);
                                    //        if ((iResult & 1) == 0)
                                    //        {
                                    //            lblOK.BackColor = Color.LightGray;
                                    //        }
                                    //        else
                                    //        {
                                    //            if ((iResultOld & 1) == 0) SaveToMDB(lbBC.Text, lbFix.Text, lblCode.Text, 1);
                                    //            lblOK.BackColor = Color.Lime;
                                    //        }
                                    //        if ((iResult & 2) == 0)
                                    //        {
                                    //            lblNG.BackColor = Color.LightGray;
                                    //        }
                                    //        else
                                    //        {
                                    //            if ((iResultOld & 2) == 0) SaveToMDB(lbBC.Text, lbFix.Text, lblCode.Text, 2);
                                    //            lblNG.BackColor = Color.Lime;
                                    //        }

                                    //    });
                                    //80=code
                                    #endregion
                                    iResultOld = iResult;
                                }
                                else
                                {
                                    bPLCThread = false;
                                    this.Invoke((EventHandler) delegate
                                    {
                                        libnodave.closeSocket(fds.rfd);
                                        timer1.Enabled = true;
                                        Thread.Sleep(100);
                                        lblPLC.Text      = "读取PLC失败" + DateTime.Now.ToString();
                                        lblPLC.BackColor = Color.Red;
                                    });
                                }
                                #endregion
                                iPos = iPos + 200;
                            }
                        }

                        this.Invoke((EventHandler) delegate
                        {
                            translatePLCUW(allBytes);
                            this.lblCode.Text = allBytes[3719].ToString();
                            //    lblPLC.Text = "读取PLC失败" + DateTime.Now.ToString();
                            //   lblPLC.BackColor = Color.Red;
                        });
                    }
                    dc.disconnectPLC();
                    //	    }
                    //	    di.disconnectAdapter();	// does nothing in ISO_TCP. But call it to keep your programs indpendent of protocols
                    libnodave.closeSocket(fds.rfd);
                    #region
                    //this.Invoke((EventHandler)delegate
                    //{
                    //    timerPLC.Enabled = true;
                    //    Thread.Sleep(100);
                    //    lblPLC.Text = "读取PLC失败" + DateTime.Now.ToString();
                    //    lblPLC.BackColor = Color.Red;
                    //});
                    #endregion
                }
                else
                {
                    this.Invoke((EventHandler) delegate
                    {
                        libnodave.closeSocket(fds.rfd);
                        timer1.Enabled = true;
                        Thread.Sleep(100);
                        lblPLC.Text      = "连接PLC失败" + DateTime.Now.ToString();
                        lblPLC.BackColor = Color.Red;
                    });

                    //MessageBox.Show("Couldn't open TCP connaction to ");
                    //  return -1;
                }
            }
            catch
            {
            }
            #region deleted
            // MessageBox.Show("end");
            //  libnodave.daveexecWriteRequest

            //  int rtVal = 1;
            //  short ConNr = 1; // First connection;(0 ... 63);(max. 64 connections).
            //  string AccessPoint = "S7ONLINE"; // Default access point——S7ONLINE
            //  Prodave6_CS.Prodave6.CON_TABLE_TYPE ConTable;// Connection table
            //  int ConTableLen = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Prodave6_CS.Prodave6.CON_TABLE_TYPE));// Length of the connection table

            //  ConTable.Adr = new byte[] { 192,168,2, 1, 0, 0 };
            //  ConTable.AdrType = 2;// (Byte)(globalVars.PSetting[9].iMode + 1); // Type of address: MPI/PB (1), IP (2), MAC (3)
            ///*  if (ConTable.AdrType > 3)
            //  {
            //      ConTable.AdrType = 3;
            //      ConTable.SlotNr = 1; // 插槽号
            //  }
            //  else
            //  {
            //      ConTable.SlotNr = 2;
            //  }
            //  ConTable.SlotNr = 1;
            //   * */
            //  ConTable.SlotNr = 1;
            //  ConTable.RackNr = 0; // 机架号
            //  try
            //  {
            //      rtVal = Prodave6.LoadConnection_ex6(ConNr, AccessPoint, ConTableLen, ref ConTable);
            //  }
            //  catch// Exception(Ex)
            //  {
            //      //      MessageBox.Show("");
            //  }
            //  if (rtVal != 0)
            //  {
            //     globalVars.bPLCThread = false;
            //      return;
            //  }
            //  //以下测试SetActiveConnection_ex6
            //  UInt16 UConNr = (UInt16)ConNr;
            //  rtVal = Prodave6.SetActiveConnection_ex6(UConNr);
            //  while (globalVars.bPLCThread)
            //  {
            //      Thread.Sleep(200);
            //      UInt16 BlkNr = 1;//data block号
            //      UInt32 pDatLen = 0;
            //      Prodave6.DatType DType = Prodave6.DatType.BYTE;//要读取的数据类型
            //      //    DType = Prodave6.DatType.WORD;//要读取的数据类型
            //      UInt16 StartNr = 0;//起始地址号
            //      UInt32 pAmount = 10;//需要读取类型的数量 0-9是写  10-19是读
            //      UInt32 BufLen = 10;//缓冲区长度(字节为单位)
            //      //参数:data block号、要写入的数据类型、起始地址号、需要写入类型的数量、缓冲区长度(字节为单位)、缓冲区
            //      byte[] pWriteBuffer = new byte[20];
            //      rtVal = Prodave6.field_read_ex6(Prodave6.FieldType.D, 1, 10, pAmount, BufLen,globalVars.AGLBuff, ref pDatLen);
            //      globalVars.bConnState = (rtVal == 0);
            //      if ((globalVars.AGLBuff[0] & 1) != 0 & (globalVars.AGLBuffOld[0] & 1) == 0)
            //      {
            //          GC.Collect();
            //          trigCam();
            //      }

            //      Buffer.BlockCopy(globalVars.AGLBuff, 0, globalVars.AGLBuffOld, 0, globalVars.AGLBuff.Length);
            //      btnTest.Text=(rtVal.ToString()+ " "+globalVars.AGLBuff[0].ToString());
            //  }

            //  Prodave6.UnloadConnection_ex6(UConNr);
            #endregion
        }
Example #33
0
        public void OpenConnection()
        {
            // Check if configuration is done
            if (ConfigurationStatus != 1)
            {
                Logger.Log("ID: " + Header.Id + " Connection failed: Plc communication is not configured.");
                throw new PlcException("ID: " + Header.Id + " Error: Plc communication is not configured.");
            }
            // Open connection only if was closed
            if (ConnectionStatus != 1)
            {
                _daveOSserialType.rfd = libnodave.openSocket(PlcConfiguration.PlcPortNumber, PlcConfiguration.PlcIpAddress);
                _daveOSserialType.wfd = _daveOSserialType.rfd;
                if (_daveOSserialType.rfd > 0)
                {
                    _daveInterface = new libnodave.daveInterface(_daveOSserialType, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
                    _daveInterface.setTimeout(10000); // orginal was:1000000
                    _daveConnection = new libnodave.daveConnection(_daveInterface, 0, PlcConfiguration.PlcRackNumber, PlcConfiguration.PlcSlotNumber);

                    if (_daveConnection.connectPLC() == 0)
                    {
                        ConnectionStatus = 1;
                        Logger.Log("ID: " + Header.Id + " Communication with PLC IP Address : " +
                                   PlcConfiguration.PlcIpAddress + " established");
                    }
                    else
                        ConnectionStatus = -1;
                }
                else
                {
                    Logger.Log("ID: " + Header.Id + " Connection failed: Can not open connection to PLC.");
                    throw new PlcException("ID: " + Header.Id + " Error: Can not open connection to PLC.");
                }
            }
        }
Example #34
0
    public static int Main(string[] args)
    {
        int   i, a = 0, j, res, b = 0, c = 0;
        float d = 0;

        byte[] buf1 = new byte[libnodave.davePartnerListSize];

        if (args.Length < 1)
        {
            usage();
            return(-1);
        }

        while (args[adrPos][0] == '-')
        {
            if (args[adrPos].StartsWith("--debug="))
            {
                libnodave.daveSetDebug(Convert.ToInt32(args[adrPos].Substring(8)));
                Console.WriteLine("setting debug to: ", Convert.ToInt32(args[adrPos].Substring(8)));
            }
            else if (args[adrPos].StartsWith("-d"))
            {
                libnodave.daveSetDebug(libnodave.daveDebugAll);
            }
            else if (args[adrPos].StartsWith("-s"))
            {
                doStop = true;
            }
            else if (args[adrPos].StartsWith("-w"))
            {
                doWrite = true;
            }
            else if (args[adrPos].StartsWith("-b"))
            {
                doBenchmark = true;
            }
            else if (args[adrPos].StartsWith("--readoutall"))
            {
                doReadout   = true;
                doSFBandSFC = true;
            }
            else if (args[adrPos].StartsWith("--readout"))
            {
                doReadout = true;
            }
            else if (args[adrPos].StartsWith("-r"))
            {
                doRun = true;
            }
            else if (args[adrPos].StartsWith("-e"))
            {
                doExperimental = true;
            }
            else if (args[adrPos].StartsWith("--local="))
            {
                localMPI = Convert.ToInt32(args[adrPos].Substring(8));
                Console.WriteLine("setting local MPI address to: " + localMPI);
            }
            else if (args[adrPos].StartsWith("--mpi="))
            {
                plcMPI = Convert.ToInt32(args[adrPos].Substring(6));
                Console.WriteLine("setting MPI address of PLC to: " + plcMPI);
            }
            else if (args[adrPos].StartsWith("--mpi2="))
            {
                plc2MPI = Convert.ToInt32(args[adrPos].Substring(7));
                Console.WriteLine("setting MPI address of 2md PLC to: " + plc2MPI);
            }
            else if (args[adrPos].StartsWith("--wbit="))
            {
                wbit = Convert.ToInt32(args[adrPos].Substring(7));
                Console.WriteLine("setting bit number: " + wbit);
                doWbit = true;
            }
            else if (args[adrPos].StartsWith("-z"))
            {
                doSZLread = true;
            }
            else if (args[adrPos].StartsWith("-a"))
            {
                doSZLreadAll = true;
            }
            else if (args[adrPos].StartsWith("-m"))
            {
                doMultiple = true;
            }
            else if (args[adrPos].StartsWith("-c"))
            {
                doClear = true;
            }
            else if (args[adrPos].StartsWith("-n"))
            {
                doNewfunctions = true;
            }
            else if (args[adrPos].StartsWith("-9"))
            {
                speed = libnodave.daveSpeed9k;
            }
            else if (args[adrPos].StartsWith("-19"))
            {
                speed = libnodave.daveSpeed19k;
            }
            else if (args[adrPos].StartsWith("-45"))
            {
                speed = libnodave.daveSpeed45k;
            }
            else if (args[adrPos].StartsWith("-93"))
            {
                speed = libnodave.daveSpeed93k;
            }
            else if (args[adrPos].StartsWith("-500"))
            {
                speed = libnodave.daveSpeed500k;
            }
            else if (args[adrPos].StartsWith("-1500"))
            {
                speed = libnodave.daveSpeed1500k;
            }

            adrPos++;
            if (args.Length <= adrPos)
            {
                usage();
                return(-1);
            }
        }

        fds.rfd = libnodave.openS7online(args[adrPos]);
        fds.wfd = fds.rfd;
        if (fds.rfd >= 0)
        {
            di = new libnodave.daveInterface(fds, "IF1", localMPI, useProto, speed);
            di.setTimeout(5000000);
            for (i = 0; i < 3; i++)
            {
                if (0 == di.initAdapter())
                {
                    initSuccess = 1;
                    a           = di.listReachablePartners(buf1);
                    Console.WriteLine("daveListReachablePartners List length: " + a);
                    if (a > 0)
                    {
                        for (j = 0; j < a; j++)
                        {
                            if (buf1[j] == libnodave.daveMPIReachable)
                            {
                                Console.WriteLine("Device at address: " + j);
                            }
                        }
                    }
                    break;
                }
                else
                {
                    di.disconnectAdapter();
                }
            }
            if (initSuccess == 0)
            {
                Console.WriteLine("Couldn't connect to Adapter!.\n Please try again. You may also try the option -2 for some adapters.");
                return(-3);
            }

            dc = new libnodave.daveConnection(di, plcMPI, 0, 0);

            if (0 == dc.connectPLC())
            {
                ;
                res = dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
                if (res == 0)
                {
                    a = dc.getS32();
                    b = dc.getS32();
                    c = dc.getS32();
                    d = dc.getFloat();
                    Console.WriteLine("FD0: " + a);
                    Console.WriteLine("FD4: " + b);
                    Console.WriteLine("FD8: " + c);
                    Console.WriteLine("FD12: " + d);
                }
                else
                {
                    Console.WriteLine("error " + res + " " + libnodave.daveStrerror(res));
                }

                if (doExperimental)
                {
                    Console.WriteLine("Trying to read outputs");
                    res = dc.readBytes(libnodave.daveOutputs, 0, 0, 2, null);
                    Console.WriteLine("function result: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    if (res == 0)
                    {
                        Console.Write("Bytes:");
                        for (b = 0; b < dc.getAnswLen(); b++)
                        {
                            c = dc.getU8();
                            Console.Write(String.Format(" {0:X0}, ", c));
                        }
                        Console.WriteLine("");
                    }
                    a = 0x01;
                    Console.WriteLine("Trying to write outputs");
                    res = dc.writeBytes(libnodave.daveOutputs, 0, 0, 1, BitConverter.GetBytes(a));
                    Console.WriteLine("function result: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    libnodave.daveSetDebug(libnodave.daveDebugAll);
                    res = dc.force200(libnodave.daveOutputs, 0, 0);
                    Console.WriteLine("function result: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    libnodave.daveSetDebug(0);
                    res = dc.force200(libnodave.daveOutputs, 0, 1);
                    Console.WriteLine("function result of force: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    wait();

                    res = dc.force200(libnodave.daveOutputs, 0, 2);
                    Console.WriteLine("function result of force: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    wait();
                    res = dc.force200(libnodave.daveOutputs, 0, 3);
                    Console.WriteLine("function result of force: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    wait();
                    res = dc.force200(libnodave.daveOutputs, 1, 4);
                    Console.WriteLine("function result of force: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    wait();
                    res = dc.force200(libnodave.daveOutputs, 2, 5);
                    Console.WriteLine("function result of force: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    wait();
                    res = dc.force200(libnodave.daveOutputs, 3, 7);
                    Console.WriteLine("function result of force: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    wait();
                    Console.WriteLine("Trying to read outputs again\n");
                    res = dc.readBytes(libnodave.daveOutputs, 0, 0, 4, null);
                    Console.WriteLine("function result: " + res + "=" + libnodave.daveStrerror(res) + " " + dc.getAnswLen());
                    if (res == 0)
                    {
                        Console.Write("Bytes:");
                        for (b = 0; b < dc.getAnswLen(); b++)
                        {
                            c = dc.getU8();
                            Console.Write(String.Format(" {0:X0}, ", c));
                        }
                        Console.WriteLine("");
                    }
                }


                if (doWrite)
                {
                    Console.WriteLine("Now we write back these data after incrementing the integers by 1,2 and 3 and the float by 1.1.\n");
                    wait();

/*
 *  Attention! you need to daveSwapIed little endian variables before using them as a buffer for
 *  daveWriteBytes() or before copying them into a buffer for daveWriteBytes()!
 */
                    a = libnodave.daveSwapIed_32(a + 1);
                    dc.writeBytes(libnodave.daveFlags, 0, 0, 4, BitConverter.GetBytes(a));
                    b = libnodave.daveSwapIed_32(b + 2);
                    dc.writeBytes(libnodave.daveFlags, 0, 4, 4, BitConverter.GetBytes(b));
                    c = libnodave.daveSwapIed_32(c + 3);
                    dc.writeBytes(libnodave.daveFlags, 0, 8, 4, BitConverter.GetBytes(c));
                    d = libnodave.toPLCfloat(d + 1.1f);
                    dc.writeBytes(libnodave.daveFlags, 0, 12, 4, BitConverter.GetBytes(d));

/*
 *   Read back and show the new values, so users may notice the difference:
 */
                    dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
                    a = dc.getU32();
                    b = dc.getU32();
                    c = dc.getU32();
                    d = dc.getFloat();
                    Console.WriteLine("FD0: " + a);
                    Console.WriteLine("FD4: " + b);
                    Console.WriteLine("FD8: " + c);
                    Console.WriteLine("FD12: " + d);
                } // doWrite

                if (doClear)
                {
                    Console.WriteLine("Now writing 0 to the bytes FB0...FB15.\n");
//              wait();
                    byte[] aa = { 0, 0, 0, 0 };
                    dc.writeBytes(libnodave.daveFlags, 0, 0, 4, aa);
                    dc.writeBytes(libnodave.daveFlags, 0, 4, 4, aa);
                    dc.writeBytes(libnodave.daveFlags, 0, 8, 4, aa);
                    dc.writeBytes(libnodave.daveFlags, 0, 12, 4, aa);
                    dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
                    a = dc.getU32();
                    b = dc.getU32();
                    c = dc.getU32();
                    d = dc.getFloat();
                    Console.WriteLine("FD0: " + a);
                    Console.WriteLine("FD4: " + b);
                    Console.WriteLine("FD8: " + c);
                    Console.WriteLine("FD12: " + d);
                } // doClear

                if (doSZLread)
                {
                    readSZL(dc, 0x92, 0x0);
                    readSZL(dc, 0xB4, 0x1024);
                    readSZL(dc, 0x111, 0x1);
                    readSZL(dc, 0xD91, 0x0);
                    readSZL(dc, 0x232, 0x4);
                    readSZL(dc, 0x1A0, 0x0);
                    readSZL(dc, 0x0A0, 0x0);
                }

                if (doSZLreadAll)
                {
                    readSZLAll(dc);
                }

                if (doStop)
                {
                    dc.stop();
                }
                if (doRun)
                {
                    dc.start();
                }
                if (doBenchmark)
                {
                    rBenchmark(dc, libnodave.daveFlags);
                }


                if (doNewfunctions)
                {
                    int saveDebug = libnodave.daveGetDebug();

                    Console.WriteLine("Trying to read two consecutive bits from DB11.DBX0.1");;
                    res = dc.readBits(libnodave.daveDB, 11, 1, 2, null);
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));

                    Console.WriteLine("Trying to read no bit (length 0) from DB17.DBX0.1");
                    res = dc.readBits(libnodave.daveDB, 17, 1, 0, null);
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));

                    libnodave.daveSetDebug(libnodave.daveGetDebug() | libnodave.daveDebugPDU);
                    Console.WriteLine("Trying to read a single bit from DB17.DBX0.3\n");
                    res = dc.readBits(libnodave.daveDB, 17, 3, 1, null);
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));

                    Console.WriteLine("Trying to read a single bit from E0.2\n");
                    res = dc.readBits(libnodave.daveInputs, 0, 2, 1, null);
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));

                    a = 0;
                    Console.WriteLine("Writing 0 to EB0\n");
                    res = dc.writeBytes(libnodave.daveOutputs, 0, 0, 1, BitConverter.GetBytes(libnodave.daveSwapIed_32(a)));
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));

                    a = 1;
                    Console.WriteLine("Trying to set single bit E0.5\n");
                    res = dc.writeBits(libnodave.daveOutputs, 0, 5, 1, BitConverter.GetBytes(libnodave.daveSwapIed_32(a)));
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));

                    Console.WriteLine("Trying to read 1 byte from AAW0\n");
                    res = dc.readBytes(libnodave.daveAnaIn, 0, 0, 2, null);
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));

                    a = 2341;
                    Console.WriteLine("Trying to write 1 word (2 bytes) to AAW0\n");
                    res = dc.writeBytes(libnodave.daveAnaOut, 0, 0, 2, BitConverter.GetBytes(libnodave.daveSwapIed_32(a)));
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));

                    Console.WriteLine("Trying to read 4 items from Timers\n");
                    res = dc.readBytes(libnodave.daveTimer, 0, 0, 4, null);
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));
                    if (res == 0)
                    {
                        d = dc.getSeconds();
                        Console.WriteLine("Time: %0.3f, ", d);
                        d = dc.getSeconds();
                        Console.WriteLine("%0.3f, ", d);
                        d = dc.getSeconds();
                        Console.WriteLine("%0.3f, ", d);
                        d = dc.getSeconds();
                        Console.WriteLine(" %0.3f\n", d);

                        d = dc.getSecondsAt(0);
                        Console.WriteLine("Time: %0.3f, ", d);
                        d = dc.getSecondsAt(2);
                        Console.WriteLine("%0.3f, ", d);
                        d = dc.getSecondsAt(4);
                        Console.WriteLine("%0.3f, ", d);
                        d = dc.getSecondsAt(6);
                        Console.WriteLine(" %0.3f\n", d);
                    }

                    Console.WriteLine("Trying to read 4 items from Counters\n");
                    res = dc.readBytes(libnodave.daveCounter, 0, 0, 4, null);
                    Console.WriteLine("function result:" + res + "=" + libnodave.daveStrerror(res));
                    if (res == 0)
                    {
                        c = dc.getCounterValue();
                        Console.WriteLine("Count: %d, ", c);
                        c = dc.getCounterValue();
                        Console.WriteLine("%d, ", c);
                        c = dc.getCounterValue();
                        Console.WriteLine("%d, ", c);
                        c = dc.getCounterValue();
                        Console.WriteLine(" %d\n", c);

                        c = dc.getCounterValueAt(0);
                        Console.WriteLine("Count: %d, ", c);
                        c = dc.getCounterValueAt(2);
                        Console.WriteLine("%d, ", c);
                        c = dc.getCounterValueAt(4);
                        Console.WriteLine("%d, ", c);
                        c = dc.getCounterValueAt(6);
                        Console.WriteLine(" %d\n", c);
                    }

                    libnodave.PDU p = dc.prepareReadRequest();
                    p.addVarToReadRequest(libnodave.daveInputs, 0, 0, 1);
                    p.addVarToReadRequest(libnodave.daveFlags, 0, 0, 4);
                    p.addVarToReadRequest(libnodave.daveDB, 6, 20, 2);
                    p.addVarToReadRequest(libnodave.daveTimer, 0, 0, 4);
                    p.addVarToReadRequest(libnodave.daveTimer, 0, 1, 4);
                    p.addVarToReadRequest(libnodave.daveTimer, 0, 2, 4);
                    p.addVarToReadRequest(libnodave.daveCounter, 0, 0, 4);
                    p.addVarToReadRequest(libnodave.daveCounter, 0, 1, 4);
                    p.addVarToReadRequest(libnodave.daveCounter, 0, 2, 4);
                    libnodave.resultSet rs = new libnodave.resultSet();
                    res = dc.execReadRequest(p, rs);
                    libnodave.daveSetDebug(saveDebug);
                }

//		System.GarbageCollect();

                if (doMultiple)
                {
                    Console.WriteLine("Now testing read multiple variables.\n"
                                      + "This will read 1 Byte from inputs,\n"
                                      + "4 bytes from flags, 2 bytes from DB6,\n"
                                      + "and other 2 bytes from flags");
                    wait();
                    libnodave.PDU p = dc.prepareReadRequest();
                    p.addVarToReadRequest(libnodave.daveInputs, 0, 0, 1);
                    p.addVarToReadRequest(libnodave.daveFlags, 0, 0, 4);
                    p.addVarToReadRequest(libnodave.daveDB, 6, 20, 2);
                    p.addVarToReadRequest(libnodave.daveFlags, 0, 12, 2);
                    p.addBitVarToReadRequest(libnodave.daveFlags, 0, 25 /* 25 is 3.1*/, 1);
                    libnodave.resultSet rs = new libnodave.resultSet();
                    res = dc.execReadRequest(p, rs);

                    Console.Write("Input Byte 0: ");
                    res = dc.useResult(rs, 0); // first result
                    if (res == 0)
                    {
                        a = dc.getU8();
                        Console.WriteLine(a);
                    }
                    else
                    {
                        Console.WriteLine("*** Error: " + libnodave.daveStrerror(res));
                    }

                    Console.Write("Flag DWord 0: ");
                    res = dc.useResult(rs, 1); // 2nd result
                    if (res == 0)
                    {
                        a = dc.getS16();
                        Console.WriteLine(a);
                    }
                    else
                    {
                        Console.WriteLine("*** Error: " + libnodave.daveStrerror(res));
                    }

                    Console.Write("DB 6 Word 20: ");
                    res = dc.useResult(rs, 2); // 3rd result
                    if (res == 0)
                    {
                        a = dc.getS16();
                        Console.WriteLine(a);
                    }
                    else
                    {
                        Console.WriteLine("*** Error: " + libnodave.daveStrerror(res));
                    }

                    Console.Write("Flag Word 12: ");
                    res = dc.useResult(rs, 3); // 4th result
                    if (res == 0)
                    {
                        a = dc.getU16();
                        Console.WriteLine(a);
                    }
                    else
                    {
                        Console.WriteLine("*** Error: " + libnodave.daveStrerror(res));
                    }

                    Console.Write("Flag F3.1: ");
                    res = dc.useResult(rs, 4); // 4th result
                    if (res == 0)
                    {
                        a = dc.getU8();
                        Console.WriteLine(a);
                    }
                    else
                    {
                        Console.WriteLine("*** Error: " + libnodave.daveStrerror(res));
                    }

                    Console.Write("non existing result (we read 5 items, but try to use a 6th one): ");
                    res = dc.useResult(rs, 5); // 5th result
                    if (res == 0)
                    {
                        a = dc.getU16();
                        Console.WriteLine(a);
                    }
                    else
                    {
                        Console.WriteLine("*** Error: " + libnodave.daveStrerror(res));
                    }

                    if (doWrite)
                    {
                        Console.WriteLine("Now testing write multiple variables:\n"
                                          + "IB0, FW0, QB0, DB6:DBW20 and DB20:DBD24 in a single multiple write.");
                        wait();
//			libnodave.daveSetDebug(0xffff);
                        byte[]        aa = { 0 };
                        libnodave.PDU p2 = dc.prepareWriteRequest();
                        p2.addVarToWriteRequest(libnodave.daveInputs, 0, 0, 1, aa);
                        p2.addVarToWriteRequest(libnodave.daveFlags, 0, 4, 2, aa);
                        p2.addVarToWriteRequest(libnodave.daveOutputs, 0, 0, 2, aa);
                        p2.addVarToWriteRequest(libnodave.daveDB, 6, 20, 2, aa);
                        p2.addVarToWriteRequest(libnodave.daveDB, 20, 24, 4, aa);
                        aa[0] = 1;
                        p2.addBitVarToWriteRequest(libnodave.daveFlags, 0, 27 /* 27 is 3.3*/, 1, aa);
                        rs  = new libnodave.resultSet();
                        res = dc.execWriteRequest(p2, rs);
                        Console.WriteLine("Result code for the entire multiple write operation: " + res + "=" + libnodave.daveStrerror(res));

/*
 * //	I could list the single result codes like this, but I want to tell
 * //	which item should have been written, so I do it in 5 individual lines:
 *
 *                      for (i=0;i<rs.numResults;i++){
 *                          res=rs.results[i].error;
 *                          Console.WriteLine("result code from writing item %d: %d=%s\n",i,res,libnodave.libnodave.daveStrerror(res));
 *                      }
 */
                        int err = rs.getErrorOfResult(0);
                        Console.WriteLine("Result code for writing IB0:       " + err + "=" + libnodave.daveStrerror(err));
                        err = rs.getErrorOfResult(1);
                        Console.WriteLine("Result code for writing FW4:       " + err + "=" + libnodave.daveStrerror(err));
                        err = rs.getErrorOfResult(2);
                        Console.WriteLine("Result code for writing QB0:       " + err + "=" + libnodave.daveStrerror(err));
                        err = rs.getErrorOfResult(3);
                        Console.WriteLine("Result code for writing DB6:DBW20: " + err + "=" + libnodave.daveStrerror(err));
                        err = rs.getErrorOfResult(4);
                        Console.WriteLine("Result code for writing DB20:DBD24:" + err + "=" + libnodave.daveStrerror(err));
                        err = rs.getErrorOfResult(5);
                        Console.WriteLine("Result code for writing F3.3:      " + err + "=" + libnodave.daveStrerror(err));

/*
 *   Read back and show the new values, so users may notice the difference:
 */
                        dc.readBytes(libnodave.daveFlags, 0, 0, 16, null);
                        a = dc.getU32();
                        b = dc.getU32();
                        c = dc.getU32();
                        d = dc.getFloat();
                        Console.WriteLine("FD0: %d\n", a);
                        Console.WriteLine("FD4: %d\n", b);
                        Console.WriteLine("FD8: %d\n", c);
                        Console.WriteLine("FD12: %f\n", d);
                    } // doWrite
                }

                dc.disconnectPLC();
            }
            di.disconnectAdapter();
            libnodave.closeS7online(fds.rfd);
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Console.WriteLine("Here we are");
        }
        else
        {
            Console.WriteLine("Couldn't open s7 online " + args[adrPos]);
            return(-1);
        }
        return(0);
    }
Example #35
0
    static void rBenchmark(libnodave.daveConnection dc, int bmArea)
    {
        int    i, res, maxReadLen, areaNumber;
        double usec;
        long   t1, t2;

        libnodave.resultSet rs = new libnodave.resultSet();
        maxReadLen = dc.getMaxPDULen() - 46;
        areaNumber = 0;
        if (bmArea == libnodave.daveDB)
        {
            areaNumber = 1;
        }
        Console.WriteLine("Now going to do read benchmark with minimum block length of 1.\n");
        t1 = Environment.TickCount;
        for (i = 1; i < 101; i++)
        {
            dc.readBytes(bmArea, areaNumber, 0, 1, null);
            if (i % 10 == 0)
            {
                Console.Write("..." + i);
            }
        }
        t2   = Environment.TickCount;
        usec = 0.001 * (t2 - t1);
        Console.WriteLine(" 100 reads took " + usec + " secs.");
        Console.WriteLine("Now going to do read benchmark with shurely supported block length " + maxReadLen);
        t1 = Environment.TickCount;
        for (i = 1; i < 101; i++)
        {
            dc.readBytes(bmArea, areaNumber, 0, maxReadLen, null);
            if (i % 10 == 0)
            {
                Console.Write("..." + i);
            }
        }
        t2   = Environment.TickCount;
        usec = 0.001 * (t2 - t1);
        Console.WriteLine(" 100 reads took " + usec + " secs. ");

        Console.WriteLine("Now going to do read benchmark with 5 variables in a single request.");
        Console.WriteLine("running...");

        t1 = Environment.TickCount;

        for (i = 1; i < 101; i++)
        {
            libnodave.PDU p = dc.prepareReadRequest();
            p.addVarToReadRequest(libnodave.daveInputs, 0, 0, 6);
            p.addVarToReadRequest(libnodave.daveFlags, 0, 0, 6);
            p.addVarToReadRequest(libnodave.daveFlags, 0, 6, 6);
            p.addVarToReadRequest(bmArea, areaNumber, 4, 54);
            p.addVarToReadRequest(bmArea, areaNumber, 4, 4);
            res = dc.execReadRequest(p, rs);
            if (res != 0)
            {
                Console.WriteLine("\nerror " + res + " = " + libnodave.daveStrerror(res));
            }
            if (i % 10 == 0)
            {
                Console.Write("..." + i);
            }
        }
        t2   = Environment.TickCount;
        usec = 0.001 * (t2 - t1);
        Console.WriteLine(" 100 reads took " + usec + " secs.");
    }
Example #36
0
    public static int Main(string[] args)
    {
        int rack, slot;
        int DB = 0, DataByte = 0, len = 0;
        int res;
        int p0 = 0, p1 = 0;
        int area        = 0;
        int bitnumber   = 0;
        int IO          = 0;
        var WriteBuffer = new byte[] { 0x00, 0x00, 0x00, 0x00 };

        bool myBit  = false;
        byte myByte = 0;

        System.Int16  myWord    = 0;
        System.Int32  myDWord   = 0;
        System.Single mySingle  = 0.0f;
        Byte[]        byteArray = { 0x00, 0x00, 0x00, 0x00 };
        string        str       = "";
        string        Address   = "";
        string        PLC       = "255.255.255.255";

        libnodave.daveSetDebug(libnodave.daveDebugRawRead);

        if (args.Length != 4 && args.Length != 5)
        {
            Console.WriteLine("");
            Console.WriteLine("Usage:");
            Console.WriteLine("S7PLCVar.exe [ipaddress] [rack] [slot] [address] [value]");
            Console.WriteLine("");
            Console.WriteLine("Examples:");
            Console.WriteLine(" Read bit value from I7.3");
            Console.WriteLine(" S7PLCVar.exe 172.24.40.191 0 3 I7.3");
            Console.WriteLine("");
            Console.WriteLine(" Read bit value from DB10.DBX14.5");
            Console.WriteLine(" S7PLCVar.exe 172.24.40.191 0 3 DB10.DBX14.5");
            Console.WriteLine("");
            Console.WriteLine(" Write DWord value 1234 to DB10.DBD14");
            Console.WriteLine(" S7PLCVar.exe 172.24.40.191 0 3 DB10.DBD14 1234");
            Console.WriteLine("");
            Console.WriteLine(" Write Output bit True to Q3.5");
            Console.WriteLine(" S7PLCVar.exe 172.24.40.191 0 3 Q3.5 True");
            Console.WriteLine("");
            return(-2);
        }
        else
        {
            PLC     = args[0];
            rack    = Convert.ToInt32(args[1]);
            slot    = Convert.ToInt32(args[2]);
            Address = args[3].ToUpper();

            if (args.Length == 5)
            {
                IO = OUTPUTS;
            }
            else
            {
                IO = INPUTS;
            }

            // ***************************************************************************
            //                   Datablocks
            // ***************************************************************************
            if (Address.Contains(".DBX"))
            {
                area = libnodave.daveDB;
                len  = 1;

                p0  = 2;
                p1  = Address.IndexOf(".DBX") - p0;
                str = Address.Substring(p0, p1);
                DB  = Convert.ToInt32(str);

                p0       = Address.IndexOf(".DBX") + 4;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(Convert.ToDouble(str));

                p0        = Address.Length - 1;
                p1        = 1;
                str       = Address.Substring(p0, p1);
                bitnumber = Convert.ToInt32(str) + 1;

                if (IO == OUTPUTS)
                {
                    myBit = Convert.ToBoolean(args[4]);
                }
            }
            else if (Address.Contains(".DBB"))
            {
                area = libnodave.daveDB;
                len  = 1;

                p0  = 2;
                p1  = Address.IndexOf(".DBB") - p0;
                str = Address.Substring(p0, p1);
                DB  = Convert.ToInt32(str);

                p0       = Address.IndexOf(".DBB") + 4;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                if (IO == OUTPUTS)
                {
                    myByte = Convert.ToByte(args[4]);
                }
            }
            else if (Address.Contains(".DBW"))
            {
                area = libnodave.daveDB;
                len  = 2;

                p0  = 2;
                p1  = Address.IndexOf(".DBW") - p0;
                str = Address.Substring(p0, p1);
                DB  = Convert.ToInt32(str);

                p0       = Address.IndexOf(".DBW") + 4;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                if (IO == OUTPUTS)
                {
                    myWord = Convert.ToInt16(args[4]);
                }
            }
            else if (Address.Contains(".DBD"))
            {
                area = libnodave.daveDB;
                len  = 4;

                p0  = 2;
                p1  = Address.IndexOf(".DBD") - p0;
                str = Address.Substring(p0, p1);
                DB  = Convert.ToInt32(str);

                p0       = Address.IndexOf(".DBD") + 4;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                if (IO == OUTPUTS)
                {
                    if (args[4].Contains("."))
                    {
                        mySingle  = Convert.ToSingle(args[4]);
                        byteArray = BitConverter.GetBytes(mySingle);
                        myDWord   = BitConverter.ToInt32(byteArray, 0);
                    }
                    else
                    {
                        myDWord = Convert.ToInt32(args[4]);
                    }
                }
            }
            // ***************************************************************************
            //                   INPUTS
            // ***************************************************************************
            else if (Address.Substring(0, 3).Contains("PIB"))
            {
                area = libnodave.daveInputs;
                len  = 1;

                p0       = 3;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);
            }
            else if (Address.Substring(0, 3).Contains("PIW"))
            {
                area = libnodave.daveInputs;
                len  = 2;

                p0       = 3;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);
            }
            else if (Address.Substring(0, 3).Contains("PID"))
            {
                area = libnodave.daveInputs;
                len  = 4;

                p0       = 3;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);
            }
            else if (Address.Substring(0, 2).Contains("IB"))
            {
                area = libnodave.daveInputs;
                len  = 1;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);
            }
            else if (Address.Substring(0, 2).Contains("IW"))
            {
                area = libnodave.daveInputs;
                len  = 2;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);
            }
            else if (Address.Substring(0, 2).Contains("ID"))
            {
                area = libnodave.daveInputs;
                len  = 4;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);
            }
            else if (Address.Substring(0, 1).Contains("I"))
            {
                area = libnodave.daveInputs;

                p0       = 1;
                p1       = Address.IndexOf(".") - 1;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                p1        = p1 + 2;
                str       = Address.Substring(p1, 1);
                bitnumber = Convert.ToInt32(str) + 1;

                len = 1;
            }


            // ***************************************************************************
            //                   OUTPUTS
            // ***************************************************************************
            else if (Address.Substring(0, 3).Contains("PQB"))
            {
                area = libnodave.daveOutputs;
                len  = 1;

                p0       = 3;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                myByte = Convert.ToByte(args[4]);
            }
            else if (Address.Substring(0, 3).Contains("PQW"))
            {
                area = libnodave.daveOutputs;
                len  = 2;

                p0       = 3;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                myWord = Convert.ToInt16(args[4]);
            }
            else if (Address.Substring(0, 3).Contains("PQD"))
            {
                area = libnodave.daveOutputs;
                len  = 4;

                p0       = 3;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                if (IO == OUTPUTS)
                {
                    if (args[4].Contains("."))
                    {
                        mySingle  = Convert.ToSingle(args[4]);
                        byteArray = BitConverter.GetBytes(mySingle);
                        myDWord   = BitConverter.ToInt32(byteArray, 0);
                    }
                    else
                    {
                        myDWord = Convert.ToInt32(args[4]);
                    }
                }
            }
            else if (Address.Substring(0, 3).Contains("QB"))
            {
                area = libnodave.daveOutputs;
                len  = 1;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                myByte = Convert.ToByte(args[4]);
            }
            else if (Address.Substring(0, 3).Contains("QW"))
            {
                area = libnodave.daveOutputs;
                len  = 2;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                myWord = Convert.ToInt16(args[4]);
            }
            else if (Address.Substring(0, 3).Contains("QD"))
            {
                area = libnodave.daveOutputs;
                len  = 4;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                if (IO == OUTPUTS)
                {
                    if (args[4].Contains("."))
                    {
                        mySingle  = Convert.ToSingle(args[4]);
                        byteArray = BitConverter.GetBytes(mySingle);
                        myDWord   = BitConverter.ToInt32(byteArray, 0);
                    }
                    else
                    {
                        myDWord = Convert.ToInt32(args[4]);
                    }
                }
            }
            else if (Address.Substring(0, 1).Contains("Q"))
            {
                area = libnodave.daveOutputs;
                len  = 1;

                p0       = 1;
                p1       = Address.IndexOf(".") - 1;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                p1        = p1 + 2;
                str       = Address.Substring(p1, 1);
                bitnumber = Convert.ToInt32(str) + 1;

                myBit = Convert.ToBoolean(args[4]);
            }

            // ***************************************************************************
            //                   Merkers / Flags
            // ***************************************************************************
            else if (Address.Substring(0, 3).Contains("MB"))
            {
                area = libnodave.daveFlags;
                len  = 1;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                if (IO == OUTPUTS)
                {
                    myByte = Convert.ToByte(args[4]);
                }
            }
            else if (Address.Substring(0, 3).Contains("MW"))
            {
                area = libnodave.daveFlags;
                len  = 2;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                if (IO == OUTPUTS)
                {
                    myWord = Convert.ToInt16(args[4]);
                }
            }
            else if (Address.Substring(0, 3).Contains("MD"))
            {
                area = libnodave.daveFlags;
                len  = 4;

                p0       = 2;
                p1       = Address.Length - p0;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                if (IO == OUTPUTS)
                {
                    if (args[4].Contains("."))
                    {
                        mySingle  = Convert.ToSingle(args[4]);
                        byteArray = BitConverter.GetBytes(mySingle);
                        myDWord   = BitConverter.ToInt32(byteArray, 0);
                    }
                    else
                    {
                        myDWord = Convert.ToInt32(args[4]);
                    }
                }
            }
            else if (Address.Substring(0, 1).Contains("M"))
            {
                area = libnodave.daveFlags;
                len  = 1;

                p0       = 1;
                p1       = Address.IndexOf(".") - 1;
                str      = Address.Substring(p0, p1);
                DataByte = Convert.ToInt32(str);

                p1        = p1 + 2;
                str       = Address.Substring(p1, 1);
                bitnumber = Convert.ToInt32(str) + 1;

                if (IO == OUTPUTS)
                {
                    myBit = Convert.ToBoolean(args[4]);
                }
            }
            // ***************************************************************************
            else if (Address.Substring(0, 1).Contains("C"))
            {
                area = libnodave.daveCounter;
            }
            else if (Address.Substring(0, 1).Contains("T"))
            {
                area = libnodave.daveTimer;
            }

            fds.rfd = libnodave.openSocket(102, PLC);
            fds.wfd = fds.rfd;
            if (fds.rfd > 0)
            {
                di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
                di.setTimeout(1000000);
                res = di.initAdapter();
                if (res == 0)
                {
                    dc = new libnodave.daveConnection(di, 0, rack, slot);
                    if (0 == dc.connectPLC())
                    {
                        if (IO == 0)
                        {
                            Console.WriteLine("Onbekende Input of Output modus.");
                            return(-3);
                        }
                        if (IO == OUTPUTS)
                        {
                            if (area == libnodave.daveDB || area == libnodave.daveOutputs || area == libnodave.daveFlags)
                            {
                                if (bitnumber > 0)
                                {
                                    res = dc.readBytes(area, DB, DataByte, len, null);
                                    if (res == 0)
                                    {
                                        // Eerst Byte inlezen
                                        myByte = (byte)dc.getU8();

                                        // Daarna Bitje in Byte aanpassen.
                                        if (myBit)
                                        {
                                            myByte = Convert.ToByte(Convert.ToInt16(myByte) + Convert.ToInt16(System.Math.Pow(2, bitnumber - 1)));
                                        }
                                        else
                                        {
                                            myByte = Convert.ToByte(myByte & ~(1 << (bitnumber - 1)));
                                        }
                                    }
                                }

                                if (len == 1)
                                {
                                    WriteBuffer[0] = myByte;
                                    res            = dc.writeBytes(area, DB, DataByte, len, WriteBuffer);
                                }
                                else if (len == 2)
                                {
                                    WriteBuffer[1] = Convert.ToByte(myWord & 0xff);
                                    WriteBuffer[0] = Convert.ToByte((myWord >> (8 * 1)) & 0xff);
                                    res            = dc.writeBytes(area, DB, DataByte, len, WriteBuffer);
                                }
                                else if (len == 4)
                                {
                                    WriteBuffer[3] = Convert.ToByte(myDWord & 0xff);
                                    WriteBuffer[2] = Convert.ToByte((myDWord >> (8 * 1)) & 0xff);
                                    WriteBuffer[1] = Convert.ToByte((myDWord >> (8 * 2)) & 0xff);
                                    WriteBuffer[0] = Convert.ToByte((myDWord >> (8 * 3)) & 0xff);
                                    res            = dc.writeBytes(area, DB, DataByte, len, WriteBuffer);
                                }
                            }
                        }
                        else if (IO == INPUTS)
                        {
                            res = dc.readBytes(area, DB, DataByte, len, null);
                            if (res == 0)
                            {
                                if (area == libnodave.daveDB || area == libnodave.daveInputs || area == libnodave.daveFlags)
                                {
                                    if (bitnumber > 0)
                                    {
                                        myByte = (byte)dc.getU8();
                                        myBit  = (myByte & (1 << bitnumber - 1)) != 0;
                                        Console.WriteLine(myBit);
                                    }
                                    else if (len == 1)
                                    {
                                        myByte = (System.Byte)dc.getU8();
                                        Console.WriteLine(myByte);
                                    }
                                    else if (len == 2)
                                    {
                                        myWord = (System.Int16)dc.getU16();
                                        Console.WriteLine(myWord);
                                    }
                                    else if (len == 4)
                                    {
                                        myDWord = (System.Int32)dc.getU32();
                                        Console.WriteLine(myDWord);
                                    }
                                }
                                if (area == libnodave.daveCounter)
                                {
                                    Console.WriteLine(dc.getS8());
                                }
                                if (area == libnodave.daveTimer)
                                {
                                    Console.WriteLine(dc.getS8());
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("error " + res + " " + libnodave.daveStrerror(res));
                        }
                    }
                    //if (IO == INPUTS)
                    //    Console.ReadKey();

                    dc.disconnectPLC();
                }
                di.disconnectAdapter();
                libnodave.closeSocket(fds.rfd);
            }
            else
            {
                Console.WriteLine("Couldn't open TCP connaction to " + args[0]);
                return(-1);
            }
            return(0);
        }
    }
Example #37
0
 public void Dispose()
 {
     dc.disconnectPLC();
     dc = null;
 }
        private int connetti()
        {
            int i, a = 0, j, res, b = 0, c = 0;
            float d = 0;
            byte[] buf1 = new byte[libnodave.davePartnerListSize];

            fds.rfd = libnodave.openS7online(param.s7online);
            fds.wfd = fds.rfd;
            if (fds.rfd >= 0)
            {
                di = new libnodave.daveInterface(fds, param.IF, param.localMPI, param.useProto, param.speed);
                di.setTimeout(param.timeOut);
                for (i = 0; i < 3; i++)
                {
                    if (0 == di.initAdapter())
                    {
                        initSuccess = true;
                        a = di.listReachablePartners(buf1);
                        plc.setTextln("daveListReachablePartners List length: " + a);
                        if (a > 0)
                        {
                            for (j = 0; j < a; j++)
                            {
                                if (buf1[j] == libnodave.daveMPIReachable)
                                    plc.setTextln("Device at address: " + j);
                            }
                        }
                        break;
                    }
                    else di.disconnectAdapter();
                }
                if (!initSuccess)
                {
                    plc.setTextln("Couldn't connect to Adapter!.\n Please try again. You may also try the option -2 for some adapters.");
                    return -3;
                }

                dc = new libnodave.daveConnection(di, param.plcMPI, 0, 0);

                return dc.connectPLC();

            }
            else
            {
                plc.setTextln("Couldn't open s7 online ");
                return -1;
            }
        }