Ejemplo n.º 1
0
        public bool Connect()
        {
            try
            {
                byte[] bytStatus = new byte[1];
                int    num       = MXIO_CS.MXEIO_Init();
                switch (MXIO_CS.MXEIO_E1K_Connect(Encoding.UTF8.GetBytes(this.ipAddress), this.port, this.timeOut, this.hConnection, Encoding.UTF8.GetBytes(this.password)))
                {
                case 0:
                    switch (MXIO_CS.MXEIO_CheckConnection(this.hConnection[0], this.timeOut, bytStatus))
                    {
                    case 0:
                        return(true);

                    case 0x7d1:
                    case 0xfa2:
                        MXIO_CS.MXEIO_Exit();
                        break;
                    }
                    return(false);

                case 0x7d1:
                case 0xfa2:
                    MXIO_CS.MXEIO_Exit();
                    break;
                }
                return(false);
            }
            catch (Exception exception)
            {
                CLog.WriteErrLogInTrace(string.Format("在连接IOLogik时出错,{0}", exception.Message));
                return(false);
            }
        }
Ejemplo n.º 2
0
 private void testThread()
 {
     bytCount        = 5;
     bytStartChannel = 0;
     UInt32[] dwGetDIValue = new UInt32[1];
     UInt32[] dwOldValue   = new UInt32[1];
     dwOldValue[0] = 0;
     bool[] isOn = new bool[bytCount];
     while (true)
     {
         ret = MXIO_CS.E1K_DI_Reads(hConnection[0], bytStartChannel, bytCount, dwGetDIValue);
         if (ret == MXIO_CS.MXIO_OK)
         {
             if (dwOldValue[0] != dwGetDIValue[0])
             {
                 Console.WriteLine(ret);
                 dwOldValue[0] = dwGetDIValue[0];
                 for (i = 0, dwShiftValue = 0; i < bytCount; i++, dwShiftValue++)
                 {
                     isOn[i] = (dwGetDIValue[0] & (1 << dwShiftValue)) != 0;
                     //TODO handle the result (change DIs value to bool?)
                 }
                 Console.WriteLine("New register: " + _timer.Elapsed);
             }
         }
         Thread.Sleep(100);
     }
 }
Ejemplo n.º 3
0
        private void Open(DevicePortTcp tcp)
        {
            Ping      ping  = new Ping();
            PingReply reply = null;

            reply = ping.Send(tcp.Address, 1000);

            if (reply.Status != IPStatus.Success)
            {
                throw new IOException(this, String.Format("Failed to ping Moxa ioLogic1200 device '{0}' at {1}", Name, tcp));
            }

            _ipAddress = System.Text.Encoding.UTF8.GetBytes(tcp.Address.ToString());
            _password  = System.Text.Encoding.UTF8.GetBytes("");
            _port      = (ushort)tcp.Port;

            MoxaStatus status = (MoxaStatus)MXIO_CS.MXEIO_E1K_Connect(_ipAddress, _port, _timeout, _hConn, _password);

            if (status != MoxaStatus.Ok)
            {
                throw new IOException(this, String.Format("Failed to connect to Moxa ioLogic1200 device '{0}' at {1}", Name, tcp));
            }

            // Check Connection
            CheckConnection(false);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Moxa1200"/> class.
        /// </summary>
        /// <exception cref="System.Exception">Moxa ioLogic 1200 driver failed to initialize.</exception>
        public Moxa1200()
        {
            ExtractEmbeddedAssembly();

            MoxaStatus status = (MoxaStatus)MXIO_CS.MXEIO_Init();

            if (status != MoxaStatus.Ok)
            {
                throw new Exception("Moxa ioLogic 1200 driver failed to initialize.");
            }
        }
Ejemplo n.º 5
0
        public override void Open()
        {
            int ret;

            Manager.Logger.Log(LogLevel.INFO, "IP address: {0}", IP);
            Manager.Logger.Log(LogLevel.INFO, "Port: {0}", Port);

            // Ping.
            Ping      ping = new Ping();
            PingReply rep;

            rep = ping.Send(IP, (int)Manager.Timeout);
            if (rep.Status != IPStatus.Success)
            {
                throw new MXIOException("Cannot reach the IO module.");
            }

            // Connect.
            int[] conn = new int[1];
            ret = MXIO_CS.MXEIO_E1K_Connect(Encoding.UTF8.GetBytes(IP), Port, Manager.Timeout, conn, new byte[0]);
            if (ret != MXIO_CS.MXIO_OK)
            {
                throw new MXIOException("MXEIO_E1K_Connect failed: {0}.", ret);
            }
            this.connection = conn[0];

            // Check connection.
            byte[] bytCheckStatus = new byte[1];
            ret = MXIO_CS.MXEIO_CheckConnection(connection, Manager.Timeout, bytCheckStatus);
            if (ret != MXIO_CS.MXIO_OK)
            {
                throw new MXIOException("MXEIO_CheckConnection failed: {0}.", ret);
            }
            if (bytCheckStatus[0] != MXIO_CS.CHECK_CONNECTION_OK)
            {
                string msg;
                switch (bytCheckStatus[0])
                {
                case MXIO_CS.CHECK_CONNECTION_FAIL:
                    msg = "fail";
                    break;

                case MXIO_CS.CHECK_CONNECTION_TIME_OUT:
                    msg = "timeout";
                    break;

                default:
                    msg = "unknown: " + bytCheckStatus[0];
                    break;
                }
                throw new MXIOException("MXEIO_CheckConnection status failed: {0}.", msg);
            }
        }
Ejemplo n.º 6
0
 public VmIOReaderHome()
 {
     uiContext = SynchronizationContext.Current;
     DIs       = new ObservableCollection <DigitalInput>();
     Relays    = new ObservableCollection <Relay>();
     SetupHTTPClient();
     ret = MXIO_CS.MXEIO_Init();
     ret = MXIO_CS.MXEIO_E1K_Connect(System.Text.Encoding.UTF8.GetBytes(IpAddress), Port, Timeout, hConnection, System.Text.Encoding.UTF8.GetBytes(Password));
     testDelay();
     DIs.Insert(0, new DigitalInput()
     {
         diIndex  = 0,
         diMode   = 0,
         diStatus = 0
     });
     DIs.Insert(1, new DigitalInput()
     {
         diIndex  = 0,
         diMode   = 0,
         diStatus = 0
     }); DIs.Insert(0, new DigitalInput()
     {
         diIndex  = 0,
         diMode   = 0,
         diStatus = 0
     });
     DIs.Insert(1, new DigitalInput()
     {
         diIndex  = 1,
         diMode   = 0,
         diStatus = 0
     });
     Relays.Insert(0, new Relay()
     {
         relayIndex             = 0,
         relayStatus            = 0,
         relayCurrentCount      = 0,
         relayCurrentCountReset = 0,
         relayMode       = 0,
         relayTotalCount = 0
     });
     Relays.Insert(1, new Relay()
     {
         relayIndex             = 1,
         relayStatus            = 0,
         relayCurrentCount      = 0,
         relayCurrentCountReset = 0,
         relayMode       = 0,
         relayTotalCount = 0
     });
     //StartDIListenerThread();
 }
Ejemplo n.º 7
0
 public bool DisConnect()
 {
     try
     {
         int num = MXIO_CS.MXEIO_Disconnect(this.hConnection[0]);
         MXIO_CS.MXEIO_Exit();
         return(num == 0);
     }
     catch (Exception exception)
     {
         CLog.WriteErrLogInTrace(string.Format("在设置IO端口状态时出错,{0}", exception.Message));
         return(false);
     }
 }
Ejemplo n.º 8
0
        private int CreateIoHandle()
        {
            ret = MXIO_CS.MXEIO_E1K_Connect(System.Text.Encoding.UTF8.GetBytes(ioLogicIP), ioLogicPortNo, ioLogicTimeout, hConnection, System.Text.Encoding.UTF8.GetBytes(Password));
            MXEIO_Error.CheckErr(ret, "MXEIO_E1K_Connect");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText("MXEIO_E1K_Connect Success.\r\n");
            }
            else
            {
                tbCommunication.AppendText("MXEIO_E1K_Connect FAILED!!!.\r\n");
            }

            return(ret);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Closes the connection to this device.
        /// </summary>
        public void Close()
        {
            if (!Connected)
            {
                return;
            }

            MoxaStatus status = (MoxaStatus)MXIO_CS.MXEIO_Disconnect(_hConn[0]);

            if (status != MoxaStatus.Ok)
            {
                throw new IOException(this, String.Format("Failed to disconnect from Moxa ioLogic1200 device '{0}'.", Name));
            }

            Connected = false;
        }
Ejemplo n.º 10
0
        private void CheckConnection(bool attemptReconnect)
        {
            // Check Connection
            Connected = false;

            byte[]     checkStatus = new byte[1];
            MoxaStatus status      = (MoxaStatus)MXIO_CS.MXEIO_CheckConnection(_hConn[0], _timeout, checkStatus);

            if (status != MoxaStatus.Ok)
            {
                throw new IOException(this, String.Format("Failed to check connection to Moxa ioLogic1200 device '{0}'.", Name));
            }

            if (checkStatus[0] == MXIO_CS.CHECK_CONNECTION_OK)
            {
                Connected = true;
                return;
            }

            if (attemptReconnect)
            {
                status = (MoxaStatus)MXIO_CS.MXEIO_E1K_Connect(_ipAddress, _port, _timeout, _hConn, _password);
                if (status == MoxaStatus.Ok)
                {
                    if (Logging)
                    {
                        Log.Trace(IOComponent.Instance.Name).Warn(this.ToString(), "Connection to Moxa ioLogic1200 device restored.");
                    }

                    return;
                }
            }

            switch (checkStatus[0])
            {
            case MXIO_CS.CHECK_CONNECTION_FAIL:
                throw new IOException(this, String.Format("Connection failed to Moxa ioLogic1200 device '{0}'.", Name));

            case MXIO_CS.CHECK_CONNECTION_TIME_OUT:
                throw new IOException(this, String.Format("Connection timed-out to Moxa ioLogic1200 device '{0}'.", Name));

            default:
                throw new IOException(this, String.Format("Unknown connection failure ({1}) to Moxa ioLogic1200 device '{0}'.", Name, checkStatus[0]));
            }
        }
Ejemplo n.º 11
0
        private int CheckConnection(bool ShowDialog)
        {
            //--------------------------------------------------------------------------
            //Check Connection
            byte[] bytCheckStatus = new byte[1];
            ret = MXIO_CS.MXEIO_CheckConnection(hConnection[0], ioLogicTimeout, bytCheckStatus);
            MXEIO_Error.CheckErr(ret, "MXEIO_CheckConnection");
            if (ret == MXIO_CS.MXIO_OK)
            {
                switch (bytCheckStatus[0])
                {
                case MXIO_CS.CHECK_CONNECTION_OK:
                    if (ShowDialog)
                    {
                        tbCommunication.AppendText(string.Format("MXEIO_CheckConnection: Check connection ok => {0}{1}", bytCheckStatus[0], "\r\n"));
                    }
                    break;

                case MXIO_CS.CHECK_CONNECTION_FAIL:
                    if (ShowDialog)
                    {
                        tbCommunication.AppendText(string.Format("MXEIO_CheckConnection: Check connection fail => {0}{1}", bytCheckStatus[0], "\r\n"));
                    }
                    break;

                case MXIO_CS.CHECK_CONNECTION_TIME_OUT:
                    if (ShowDialog)
                    {
                        tbCommunication.AppendText(string.Format("MXEIO_CheckConnection: Check connection time out => {0}{1}", bytCheckStatus[0], "\r\n"));
                    }
                    break;

                default:
                    if (ShowDialog)
                    {
                        tbCommunication.AppendText(string.Format("MXEIO_CheckConnection: Check connection status unknown => {0}{1}", bytCheckStatus[0], "\r\n"));
                    }
                    break;
                }
            }
            return(ret);
            //--------------------------------------------------------------------------
        }
Ejemplo n.º 12
0
        private void NewMethod(int index)
        {
            bytCount        = 1;
            bytStartChannel = (byte)(0 + index);
            Console.WriteLine("Start new update method");
            TimeSpan startTime = _timer.Elapsed;
            //Set Ch{0}~ch{1} DO Direction DO Mode value = ON
            UInt32 dwSetDOValue = (uint)(Relays[index].relayStatus == 0 ? 1 : 0);

            Console.WriteLine(dwSetDOValue);
            ret = MXIO_CS.E1K_DO_Writes(hConnection[0], bytStartChannel, bytCount, dwSetDOValue);
            Console.WriteLine(ret);
            if (ret == MXIO_CS.MXIO_OK)
            {
            }
            Console.WriteLine("End new update method");
            TimeSpan elapsedTime = _timer.Elapsed - startTime;

            Console.WriteLine("Elapsed time NEW: " + elapsedTime);
        }
Ejemplo n.º 13
0
        public MXIOManager(Logger logger)
        {
            this.Logger = logger;
            Logger.Log(LogLevel.INFO, "Initializing the MXIO library...");
            int ret;

            // DLL version.
            ret = MXIO_CS.MXIO_GetDllVersion();
            Logger.Log(LogLevel.INFO, "DLL Version: {0}.{1}.{2}.{3}", (ret >> 12) & 0xF, (ret >> 8) & 0xF, (ret >> 4) & 0xF, (ret) & 0xF);

            // Build date.
            ret = MXIO_CS.MXIO_GetDllBuildDate();
            Logger.Log(LogLevel.INFO, "DLL Build Date: {0:x}/{1:x}/{2:x}", (ret >> 16), (ret >> 8) & 0xFF, (ret) & 0xFF);

            // Init.
            ret = MXIO_CS.MXEIO_Init();
            if (ret != MXIO_CS.MXIO_OK)
            {
                throw new MXIOException("MXIO init failed: {0}.", ret);
            }
        }
Ejemplo n.º 14
0
        private void eXX_DO_Write(string IPAddr, UInt16 Port, UInt32 Timeout, byte Channel, uint Value, int ModuleType)
        {
            Int32[] hConnection = new Int32[16];
            string  Password    = "";
            int     ret         = 0;

            try
            {
                this.myLog.LogAlert(AlertType.System, this.id.ToString(), this.GetType().ToString(), "e1K_DO_Write()", "IPAddr = " + IPAddr.ToString(), "system");
                int init = MXIO_CS.MXEIO_Init();

                if ((MXIO_ModuleType)ModuleType == MXIO_ModuleType.E1212)
                {
                    ret = MXIO_CS.MXEIO_E1K_Connect(System.Text.Encoding.UTF8.GetBytes(IPAddr), Port, Timeout, hConnection, System.Text.Encoding.UTF8.GetBytes(Password));
                    ret = MXIO_CS.E1K_DO_Writes(hConnection[0], Channel, 1, Value);
                    MXIO_CS.MXEIO_Disconnect(hConnection[0]);
                }
                else if ((MXIO_ModuleType)ModuleType == MXIO_ModuleType.E2210)
                {
                    byte bytSlot = 0;
                    ret = MXIO_CS.MXEIO_Connect(System.Text.Encoding.UTF8.GetBytes(IPAddr), Port, Timeout, hConnection);
                    ret = MXIO_CS.DO_Writes(hConnection[0], bytSlot, Channel, 1, Value);
                    MXIO_CS.MXEIO_Disconnect(hConnection[0]);
                }

                MXIO_CS.MXEIO_Exit();

                if (ret != 0)
                {
                    this.myLog.LogAlert(AlertType.Error, this.id.ToString(), this.GetType().ToString(), "e1K_DO_Write()",
                                        "Error code, ret = " + ret.ToString(), "system");
                }
            }
            catch (Exception ex)
            {
                this.myLog.LogAlert(AlertType.Error, this.id.ToString(), this.GetType().ToString(), "e1K_DO_Write()",
                                    ex.ToString(), "system");
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Attempts to set the current value of the digital output bit (0 or 1) at the specified channel address to the specified value.
        /// Retries until successful or the max number of attempts is reached.
        /// </summary>
        /// <param name="channel">The channel address.</param>
        /// <param name="value">The set value (0 or 1).</param>
        /// <param name="attempt">The max number of retry attempts.</param>
        /// <exception cref="System.IO.IOException"></exception>
        public void SetDOBit(int channel, int value, int attempt)
        {
            /*
             * byte wordLength = (byte)GetDIOWordLength();
             *
             *
             * int startChannel = channel / wordLength;
             *
             * MoxaStatus status = (MoxaStatus)MXIO_CS.E1K_DO_Reads(_hConn[0], (byte)startChannel, wordLength, readValues);
             *
             * if (status != MoxaStatus.Ok)
             *  throw new IOException(this, String.Format("Could not read state before setting MOXA DO channel {0} ({1}).", channel, status));
             *
             * uint bitMask = (uint)1 << (channel % wordLength);
             *
             * if (value > 0)
             *  readValues[0] |= bitMask;
             * else if (value < 0)
             *  readValues[0] &= ~bitMask;
             */

            lock (_lock)
            {
                MoxaStatus status = (MoxaStatus)MXIO_CS.E1K_DO_Writes(_hConn[0], (byte)channel, (byte)1, (uint)value);

                if (status != MoxaStatus.Ok)
                {
                    CheckConnection(true);

                    if (attempt >= _retries)
                    {
                        throw new IOException(this, String.Format("Could not write to MOXA DO channel {0} after {1} retries ({2}).", channel, attempt, status));
                    }

                    SetDOBit(channel, value, attempt + 1);
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gets the do bit.
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <param name="attempt">The attempt.</param>
        /// <returns></returns>
        /// <exception cref="System.IO.IOException"></exception>
        private int GetDOBit(int channel, int attempt)
        {
            uint[] value = new uint[1];

            lock (_lock)
            {
                MoxaStatus status = (MoxaStatus)MXIO_CS.E1K_DO_Reads(_hConn[0], (byte)channel, (byte)1, value);

                if (status != MoxaStatus.Ok)
                {
                    CheckConnection(true);

                    if (attempt >= _retries)
                    {
                        throw new IOException(this, String.Format("Could not read MOXA DO channel {0} after {1} retries. ({2}).", channel, attempt, status));
                    }

                    return(GetDOBit(channel, attempt + 1));
                }
            }

            return((int)value[0]);
        }
Ejemplo n.º 17
0
        protected void Init()
        {
            Manager.Logger.Log(LogLevel.INFO, "Connecting to the IO module for {0}...", Name);

            // Connect.
            Open();

            // Get firmware version
            int ret;

            byte[] bytRevision = new byte[4];
            ret = MXIO_CS.MXIO_ReadFirmwareRevision(connection, bytRevision);
            if (ret != MXIO_CS.MXIO_OK)
            {
                throw new MXIOException("MXIO read firmware version failed: {0}.", ret);
            }
            Manager.Logger.Log(LogLevel.INFO, "Firmware Version: {0}.{1}, release: {2}, build: {3}", bytRevision[0], bytRevision[1], bytRevision[2], bytRevision[3]);

            // Get firmware release date
            ushort[] wGetFirmwareDate = new ushort[2];
            ret = MXIO_CS.MXIO_ReadFirmwareDate(connection, wGetFirmwareDate);
            if (ret != MXIO_CS.MXIO_OK)
            {
                throw new MXIOException("MXIO read firmware date failed: {0}.", ret);
            }
            Manager.Logger.Log(LogLevel.INFO, "Firmware Date: {0:x}/{1:x}/{2:x}", wGetFirmwareDate[1], (wGetFirmwareDate[0] >> 8) & 0xFF, (wGetFirmwareDate[0]) & 0xFF);

            // Get module type
            ushort[] wModuleType = new ushort[1];
            ret = MXIO_CS.MXIO_GetModuleType(connection, 0, wModuleType);
            if (ret != MXIO_CS.MXIO_OK)
            {
                throw new MXIOException("MXIO get module type failed: {0}.", ret);
            }
            Manager.Logger.Log(LogLevel.INFO, "Module type: {0:x}", wModuleType[0]);
        }
Ejemplo n.º 18
0
        public bool Do_Writes(byte channel, uint dwSetDOValue)
        {
            try
            {
                byte bytCount        = 1;
                byte bytStartChannel = channel;
                switch (MXIO_CS.E1K_DO_Writes(this.hConnection[0], bytStartChannel, bytCount, dwSetDOValue))
                {
                case 0:
                    return(true);

                case 0x7d1:
                case 0xfa2:
                    MXIO_CS.MXEIO_Exit();
                    break;
                }
                return(false);
            }
            catch (Exception exception)
            {
                CLog.WriteErrLogInTrace(string.Format("在设置IO端口状态时出错,{0}", exception.Message));
                return(false);
            }
        }
Ejemplo n.º 19
0
        private void CheckErr(int iRet, string szFunctionName)
        {
            string str = "MXIO_OK";

            switch (iRet)
            {
            case 0x3e9:
                str = "ILLEGAL_FUNCTION";
                break;

            case 0x3ea:
                str = "ILLEGAL_DATA_ADDRESS";
                break;

            case 0x3eb:
                str = "ILLEGAL_DATA_VALUE";
                break;

            case 0x3ec:
                str = "SLAVE_DEVICE_FAILURE";
                break;

            case 0x3ee:
                str = "SLAVE_DEVICE_BUSY";
                break;

            case 0x7d1:
                str = "EIO_TIME_OUT";
                break;

            case 0x7d2:
                str = "EIO_INIT_SOCKETS_FAIL";
                break;

            case 0x7d3:
                str = "EIO_CREATING_SOCKET_ERROR";
                break;

            case 0x7d4:
                str = "EIO_RESPONSE_BAD";
                break;

            case 0x7d5:
                str = "EIO_SOCKET_DISCONNECT";
                break;

            case 0x7d6:
                str = "PROTOCOL_TYPE_ERROR";
                break;

            case 0xbb9:
                str = "SIO_OPEN_FAIL";
                break;

            case 0xbba:
                str = "SIO_TIME_OUT";
                break;

            case 0xbbb:
                str = "SIO_CLOSE_FAIL";
                break;

            case 0xbbc:
                str = "SIO_PURGE_COMM_FAIL";
                break;

            case 0xbbd:
                str = "SIO_FLUSH_FILE_BUFFERS_FAIL";
                break;

            case 0xbbe:
                str = "SIO_GET_COMM_STATE_FAIL";
                break;

            case 0xbbf:
                str = "SIO_SET_COMM_STATE_FAIL";
                break;

            case 0xbc0:
                str = "SIO_SETUP_COMM_FAIL";
                break;

            case 0xbc1:
                str = "SIO_SET_COMM_TIME_OUT_FAIL";
                break;

            case 0xbc2:
                str = "SIO_CLEAR_COMM_FAIL";
                break;

            case 0xbc3:
                str = "SIO_RESPONSE_BAD";
                break;

            case 0xbc4:
                str = "SIO_TRANSMISSION_MODE_ERROR";
                break;

            case 0xfa1:
                str = "PRODUCT_NOT_SUPPORT";
                break;

            case 0xfa2:
                str = "HANDLE_ERROR";
                break;

            case 0xfa3:
                str = "SLOT_OUT_OF_RANGE";
                break;

            case 0xfa4:
                str = "CHANNEL_OUT_OF_RANGE";
                break;

            case 0xfa5:
                str = "COIL_TYPE_ERROR";
                break;

            case 0xfa6:
                str = "REGISTER_TYPE_ERROR";
                break;

            case 0xfa7:
                str = "FUNCTION_NOT_SUPPORT";
                break;

            case 0xfa8:
                str = "OUTPUT_VALUE_OUT_OF_RANGE";
                break;

            case 0xfa9:
                str = "INPUT_VALUE_OUT_OF_RANGE";
                break;

            case 0:
                return;
            }
            Console.WriteLine("Function \"{0}\" execution Fail. Error Message : {1}\n", szFunctionName, str);
            if ((iRet == 0x7d1) || (iRet == 0xfa2))
            {
                MXIO_CS.MXEIO_Exit();
                Console.WriteLine("Press any key to close application\r\n");
                Console.ReadLine();
            }
        }
Ejemplo n.º 20
0
 public override void SetDigitalOutput(int output, bool value)
 {
     InvokeWithRetry("SetDigitalOutput", () => MXIO_CS.E1K_DO_Writes(connection, (byte)output, 1, (uint)(value ? 1 : 0)));
 }
Ejemplo n.º 21
0
 public override bool GetDigitalInput(int input)
 {
     uint[] value = new uint[1];
     InvokeWithRetry("GetDigitalInput", () => MXIO_CS.E1K_DI_Reads(connection, 1, (byte)input, value));
     return(value[0] == 1);
 }
Ejemplo n.º 22
0
        public int[] GetDOBits(int[] channels)
        {
            List <int> allValues = new List <int>(channels.Length);

            List <List <int> > _contGroups = new List <List <int> >();

            _contGroups.Add(new List <int>());

            for (int i = 0; i < channels.Length; i++)
            {
                List <int> group = _contGroups.Last();

                if (group.Count == 0)
                {
                    group.Add(channels[i]);
                    continue;
                }

                if (group.Last() != channels[i] - 1)
                {
                    _contGroups.Add(new List <int>()
                    {
                        channels[i]
                    });
                }
                else
                {
                    group.Add(channels[i]);
                }
            }

            foreach (List <int> group in _contGroups)
            {
                uint[] values = new uint[1];

                lock (_lock)
                {
                    MoxaStatus status  = MoxaStatus.SIOResponseBad;
                    int        attempt = 0;

                    while (attempt < _retries)
                    {
                        status = (MoxaStatus)MXIO_CS.E1K_DO_Reads(_hConn[0], (byte)group.First(), (byte)group.Count, values);

                        if (status == MoxaStatus.Ok)
                        {
                            break;
                        }

                        CheckConnection(true);

                        attempt++;
                    }

                    if (status != MoxaStatus.Ok)
                    {
                        throw new IOException(this, String.Format("Could not read MOXA DO channels {0} after {1} retries ({2}).", String.Join(",", channels), _retries, status));
                    }
                }

                for (int i = 0; i < group.Count; i++)
                {
                    uint bitMask  = (uint)1 << i;
                    int  bitValue = (values[0] & bitMask) != 0 ? 1 : 0;

                    allValues.Add(bitValue);
                }
            }

            return(allValues.ToArray());
        }
Ejemplo n.º 23
0
 public override void Close()
 {
     MXIO_CS.MXEIO_Disconnect(this.connection);
 }
Ejemplo n.º 24
0
        //------------- Format variable ------------


        private void RunTimer_Tick(object sender, EventArgs e)
        {
            Int32 dwShiftValue = 0x0000;
            int   i            = 0;

            UInt32[] dwGetDIValue = new UInt32[1];
            if (cbService.Checked)
            {
                CheckService(NavServiceServer, NavServiceUserName, NavServicePassword, NavServiceServiceName, false);
            }
            BalanceWS.BalanceWS CBPAutomation = new BalanceWS.BalanceWS();
            CBPAutomation.UseDefaultCredentials = true;
            try
            {
                bool OK = false;
                OK = CBPAutomation.WSNewPalletExist(NewPalletPosIs);
                if (OK)
                {
                    ret = CheckConnection(false);
                    if (ret == MXIO_CS.EIO_SOCKET_DISCONNECT)
                    {
                        CreateIoHandle();
                    }
                    ret = MOXA_CSharp_MXIO.MXIO_CS.E1K_DO_Writes(hConnection[0], DO_DATA_SEND_TO_FISKER, 1, TRIGGER_TYPE_LO_2_HI);
                    MXEIO_Error.CheckErr(ret, "E1K_DO_Writes");
                    if (ret == MXIO_CS.MXIO_OK)
                    {
                        tbCommunication.AppendText(string.Format("New Pallet E1K_DO_Writes Set Ch{0} DO Direction DO Mode value = ON success.{1}", DO_DATA_SEND_TO_FISKER, "\r\n"));
                    }
                    else
                    {
                        tbCommunication.AppendText(string.Format("New Pallet E1K_DO_Write Ch{0} ON returned ERROR: {1} Return value: {2}{3}", DO_DATA_SEND_TO_FISKER, MXEIO_Error.CheckErr(ret, "E1K_DO_Writes"), ret.ToString(), "\r\n"));
                    }
                    GlobalChannel = DO_DATA_SEND_TO_FISKER;
                    Thread.Sleep(2000);
                    ResetChanel_Tick(sender, e);
                }

                if (OK)
                {
                    try
                    {
                        CBPAutomation.WSRenameNewPallet(NewPalletPosIs);
                    }
                    catch (Exception ex)
                    {
                        tbCommunication.AppendText(string.Format("Rename New pallet failed: {0}{1}", MessageBox.Show(ex.Message), "\r\n"));
                    }
                }
            }
            catch (Exception ex)
            {
                tbCommunication.AppendText(string.Format("New pallet check failed: {0}{1}", MessageBox.Show(ex.Message), "\r\n"));
            }

            ret = CheckConnection(false);
            if (ret == MXIO_CS.EIO_SOCKET_DISCONNECT)
            {
                CreateIoHandle();
            }

            ret = MXIO_CS.E1K_DI_Reads(hConnection[0], bytStartChannel, bytCount, dwGetDIValue);
            MXEIO_Error.CheckErr(ret, "E1K_DI_Reads");

            if (ret == MXIO_CS.MXIO_OK)
            {
                for (i = 0, dwShiftValue = 0; i < bytCount; i++, dwShiftValue++)
                {
                    MyString = (((dwGetDIValue[0] & (1 << dwShiftValue)) == 0) ? "OFF" : "ON");
                    if (MyString.Equals("ON"))
                    {
                        // se hvilken Ch det drejer sig om og udfør handling.
                        //tbCommunication.AppendText(string.Format("DI value: ch[{0}] = {1}{2}", i + bytStartChannel, ((dwGetDIValue[0] & (1 << dwShiftValue)) == 0) ? "OFF" : "ON", "\r\n"));
                        if ((dwShiftValue) == DI_DUMMY_PALLET)
                        {
                            try
                            {
                                CBPAutomation.WSAddPalletToQue(string.Format("W {0}", DateTime.Now.ToShortDateString() + ' ' + DateTime.Now.ToShortTimeString()));
                                tbCommunication.AppendText(string.Format("Add Wrap-only pallet OK: {0}", "\r\n"));
                            }
                            catch (Exception ex)
                            {
                                tbCommunication.AppendText(string.Format("Add Wrap-only pallet failed: {0}{1}", MessageBox.Show(ex.Message), "\r\n"));
                            }
                        }


                        if ((dwShiftValue) == DI_READY_FOR_LABEL)
                        {
                            try
                            {
                                if (CBPAutomation.WSIsDummyPallet())
                                {
                                    ret = CheckConnection(false);
                                    if (ret == MXIO_CS.EIO_SOCKET_DISCONNECT)
                                    {
                                        CreateIoHandle();
                                    }

                                    ret = MOXA_CSharp_MXIO.MXIO_CS.E1K_DO_Writes(hConnection[0], DO_DUMMY_PALLET, 1, TRIGGER_TYPE_LO_2_HI);
                                    MXEIO_Error.CheckErr(ret, "E1K_DO_Writes");
                                    if (ret == MXIO_CS.MXIO_OK)
                                    {
                                        tbCommunication.AppendText(string.Format("Dummy Pallet DataE1K_DO_Writes Set Ch{0} DO Direction DO Mode value = ON success.{1}", DO_LABEL_SEND_TO_PRINTER, "\r\n"));
                                    }
                                    else
                                    {
                                        tbCommunication.AppendText(string.Format("Dummy Pallet E1K_DO_Write returned ERROR: {0} Return value: {1}{2}", MXEIO_Error.CheckErr(ret, "E1K_DO_Writes"), ret.ToString(), "\r\n"));
                                    }
                                    Thread.Sleep(2000);
                                    GlobalChannel = DO_DUMMY_PALLET;
                                    ResetChanel_Tick(sender, e);
                                }

                                else if (CBPAutomation.WSCreateSSCCDataFile())
                                {
                                    if (System.IO.File.Exists(s_SSCCPath + s_SSCCLabelName))
                                    {
                                        System.IO.File.Copy(s_SSCCPath + s_SSCCLabelName, EidosPrinterIp + EidosPrinterPort, true);
                                    }

                                    if (b_DeleteFile)
                                    {
                                        System.IO.File.Delete(s_SSCCPath + s_SSCCLabelName);
                                    }

                                    ret = CheckConnection(false);
                                    if (ret == MXIO_CS.EIO_SOCKET_DISCONNECT)
                                    {
                                        CreateIoHandle();
                                    }

                                    ret = MOXA_CSharp_MXIO.MXIO_CS.E1K_DO_Writes(hConnection[0], DO_LABEL_SEND_TO_PRINTER, 1, TRIGGER_TYPE_LO_2_HI);
                                    MXEIO_Error.CheckErr(ret, "E1K_DO_Writes");
                                    if (ret == MXIO_CS.MXIO_OK)
                                    {
                                        tbCommunication.AppendText(string.Format("Create SSCC DataE1K_DO_Writes Set Ch{0} DO Direction DO Mode value = ON success.{1}", DO_LABEL_SEND_TO_PRINTER, "\r\n"));
                                    }
                                    else
                                    {
                                        tbCommunication.AppendText(string.Format("Create SSCC E1K_DO_Write returned ERROR: {0} Return value: {1}{2}", MXEIO_Error.CheckErr(ret, "E1K_DO_Writes"), ret.ToString(), "\r\n"));
                                    }
                                    Thread.Sleep(2000);
                                    GlobalChannel = DO_LABEL_SEND_TO_PRINTER;
                                    //RunTimer.Stop();
                                    //ResetChanel.Start();
                                    ResetChanel_Tick(sender, e);
                                }
                            }
                            catch (Exception ex)
                            {
                                tbCommunication.AppendText(string.Format("Send SSCC Data to printer failed: {0}{1}", MessageBox.Show(ex.Message), "\r\n"));
                            }
                        }

                        if ((dwShiftValue) == DI_PALLET_FINISHED)
                        {
                            try
                            {
                                CBPAutomation.WSRemovePallet();
                                tbCommunication.AppendText(string.Format("Remove pallet success: {0}", "\r\n"));
                                Thread.Sleep(2000);
                            }
                            catch (Exception ex)
                            {
                                tbCommunication.AppendText(string.Format("Remove pallet failed: {0}{1}", MessageBox.Show(ex.Message), "\r\n"));
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
        private void btnInit_Click(object sender, EventArgs e)
        {
            //--------------------------------------------------------------------------
            ret = MXIO_CS.MXIO_GetDllVersion();
            tbCommunication.AppendText(string.Format("MXIO_GetDllVersion:{0}.{1}.{2}.{3}{4}", (ret >> 12) & 0xF, (ret >> 8) & 0xF, (ret >> 4) & 0xF, (ret) & 0xF, "\r\n"));

            ret = MXIO_CS.MXIO_GetDllBuildDate();
            tbCommunication.AppendText(string.Format("MXIO_GetDllBuildDate:{0:x}/{1:x}/{2:x}{3}", (ret >> 16), (ret >> 8) & 0xFF, (ret) & 0xFF, "\r\n"));
            //--------------------------------------------------------------------------
            ret = MXIO_CS.MXEIO_Init();
            tbCommunication.AppendText(string.Format("MXEIO_Init return {0}{1}", ret, "\r\n"));
            //--------------------------------------------------------------------------
            //Connect to ioLogik device
            tbCommunication.AppendText(string.Format("MXEIO_E1K_Connect IP={0}, Port={1}, Timeout={2}, Password={3}{4}", ioLogicIP, ioLogicPortNo, ioLogicTimeout, Password, "\r\n"));
            //Create Connection
            CreateIoHandle();
            //Check Connection
            CheckConnection(true);
            //Check the if the webservice for Navision is running
            if (cbService.Checked)
            {
                CheckService(NavServiceServer, NavServiceUserName, NavServicePassword, NavServiceServiceName, true);
            }
            //Get firmware Version
            byte[] bytRevision = new byte[4];
            ret = MXIO_CS.MXIO_ReadFirmwareRevision(hConnection[0], bytRevision);
            MXEIO_Error.CheckErr(ret, "MXIO_ReadFirmwareRevision");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("MXIO_ReadFirmwareRevision:V{0}.{1}, Release:{2}, build:{3}{4}", bytRevision[0], bytRevision[1], bytRevision[2], bytRevision[3], "\r\n"));
            }
            //--------------------------------------------------------------------------
            //Get firmware Release Date
            UInt16[] wGetFirmwareDate = new UInt16[2];
            ret = MXIO_CS.MXIO_ReadFirmwareDate(hConnection[0], wGetFirmwareDate);
            MXEIO_Error.CheckErr(ret, "MXIO_ReadFirmwareDate");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("MXIO_ReadFirmwareDate:{0:x}/{1:x}/{2:x}{3}", wGetFirmwareDate[1], (wGetFirmwareDate[0] >> 8) & 0xFF, (wGetFirmwareDate[0]) & 0xFF, "\r\n"));
            }
            //--------------------------------------------------------------------------
            //Get Module Type
            UInt16[] wModuleType = new UInt16[1];
            ret = MXIO_CS.MXIO_GetModuleType(hConnection[0], 0, wModuleType);
            MXEIO_Error.CheckErr(ret, "MXIO_GetModuleType");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("MXIO_GetModuleType: Module Type = {0:x}{1}", wModuleType[0], "\r\n"));
            }
            //--------------------------------------------------------------------------

            byte safebytCount        = 8;
            byte safebytStartChannel = 0;

            //Set Power On value = OFF
            UInt32 dwSetDOPowerOnValue = 0;

            ret = MXIO_CS.E1K_DO_SetPowerOnValues(hConnection[0], safebytStartChannel, safebytCount, dwSetDOPowerOnValue);
            MXEIO_Error.CheckErr(ret, "E1K_DO_GetPowerOnValues");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("E1K_DO_SetPowerOnValues Set Ch{0}~ch{1} DO Direction DO Mode Power On value = OFF success.{2}", bytStartChannel, safebytCount + bytStartChannel - 1, "\r\n"));
            }

            //Get Ch{0}~ch{1} DO Direction DO Mode value
            UInt32[] dwGetDOValue = new UInt32[1];
            ret = MXIO_CS.E1K_DO_Reads(hConnection[0], safebytStartChannel, safebytCount, dwGetDOValue);
            MXEIO_Error.CheckErr(ret, "E1K_DO_Reads");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("E1K_DO_Reads Get Ch{0}~ch{1} DO Direction DO Mode value success.{2}", bytStartChannel, bytCount + bytStartChannel - 1, "\r\n"));
                for (int i = 0, dwShiftValue = 0; i < safebytCount; i++, dwShiftValue++)
                {
                    tbCommunication.AppendText(string.Format("DO value: ch[{0}] = {1}{2}", i + safebytStartChannel, ((dwGetDOValue[0] & (1 << dwShiftValue)) == 0) ? "OFF" : "ON", "\r\n"));
                }
            }

            UInt16[] wDoSafeValue = new UInt16[8] {
                0, 0, 0, 0, 0, 0, 0, 0
            };

            ret = MXIO_CS.E1K_DO_SetSafeValues_W(hConnection[0], safebytStartChannel, safebytCount, wDoSafeValue);
            MXEIO_Error.CheckErr(ret, "E1K_DO_SetSafeValues_W");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("E1K_DO_SetSafeValues_W ch{0}~ch{1} success.{2}", safebytStartChannel, safebytStartChannel + safebytCount - 1, "\r\n"));
            }
            //Get Ch XX DO Direction DO Mode safe values
            UInt16[] wGetDOSafeValue = new UInt16[8];
            ret = MXIO_CS.E1K_DO_GetSafeValues_W(hConnection[0], safebytStartChannel, safebytCount, wGetDOSafeValue);
            MXEIO_Error.CheckErr(ret, "E1K_DO_GetSafeValues_W");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("E1K_DO_GetSafeValues_W Get Ch{0}~ch{1} DO Direction DO Mode DO Safe Value success.", safebytStartChannel, safebytStartChannel + safebytCount - 1, "\r\n"));
                for (int i = 0; i < safebytCount; i++)
                {
                    switch (wGetDOSafeValue[i])
                    {
                    case 0:
                        tbCommunication.AppendText(string.Format("DO Safe value: ch[{0}] = {1}{2}", i, "OFF", "\r\n"));
                        break;

                    case 1:
                        tbCommunication.AppendText(string.Format("DO Safe value: ch[{0}] = {1}{2}", i, "ON", "\r\n"));
                        break;

                    case 2:
                        tbCommunication.AppendText(string.Format("DO Safe value: ch[{0}] = {1}{2}", i, "Hold Last", "\r\n"));
                        break;
                    }
                }
            }
            //  ---------------------------------------  DI setup -------------------------------------------------

            //Set Ch0~ch3 DI Direction DI Mode
            for (int i = 0; i < bytCount; i++)
            {
                wSetDI_DIMode[i] = DI_DIRECTION_DI_MODE;
            }

            ret = MXIO_CS.E1K_DI_SetModes(hConnection[0], bytStartChannel, bytCount, wSetDI_DIMode);
            MXEIO_Error.CheckErr(ret, "E1K_DI_SetModes");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("E1K_DI_SetModes Set Ch{0} ~ Ch{1} DI Direction DI Mode Succcess.{2}", bytStartChannel, bytCount - 1, "\r\n"));
            }
            //Get Ch0~ch3 DI Direction Mode
            ret = MXIO_CS.E1K_DI_GetModes(hConnection[0], bytStartChannel, bytCount, wGetDIMode);
            MXEIO_Error.CheckErr(ret, "E1K_DI_GetModes");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("E1K_DI_GetModes Get Ch{0}~ch{1} DI Direction Mode success.", bytStartChannel, bytCount + bytStartChannel - 1));
                tbCommunication.AppendText("\r\n");
                for (int i = 0; i < bytCount; i++)
                {
                    tbCommunication.AppendText(string.Format("ch{0}={1}", i + bytStartChannel, (wGetDIMode[i] == wDI_DI_MODE) ? "DI_MODE" : "COUNT_MODE"));
                    tbCommunication.AppendText("\r\n");
                }
            }
            //*******************
            // Set/Get DI filter
            //*******************
            //Set Ch0~ch3 DI Direction Filter
            UInt16[] wFilter = new UInt16[8];
            for (int i = 0; i < safebytCount; i++)
            {
                wFilter[i] = (UInt16)(DI_SignalFilter);
            }
            ret = MXIO_CS.E1K_DI_SetFilters(hConnection[0], safebytStartChannel, safebytCount, wFilter);
            MXEIO_Error.CheckErr(ret, "E1K_DI_SetFilters");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("E1K_DI_SetFilters Set Ch{0}~ch{1} DI Direction Filter to {2} return {3}{4}", safebytStartChannel, safebytCount + safebytStartChannel - 1, DI_SignalFilter, ret, "\r\n"));
            }

            //Get Ch0~ch3 DI Direction Filter
            ret = MXIO_CS.E1K_DI_GetFilters(hConnection[0], safebytStartChannel, safebytCount, wFilter);
            MXEIO_Error.CheckErr(ret, "E1K_DI_GetFilters");
            if (ret == MXIO_CS.MXIO_OK)
            {
                tbCommunication.AppendText(string.Format("E1K_DI_GetFilters Get Ch{0}~ch{1} DI Direction Filter return {2}", bytStartChannel, bytCount + bytStartChannel - 1, ret));
                tbCommunication.AppendText("\r\n");
                for (int i = 0; i < safebytCount; i++)
                {
                    tbCommunication.AppendText(string.Format("DI Filter Value: ch[{0}] = {1}{2}", i, wFilter[i], "\r\n"));
                }
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     MXIO_CS.MXEIO_Exit();
 }