protected void Send(TransmissionState state, Result result, TResponse baseResponse = null)
        {
            result = result ?? Result.Success;

            try
            {
                string data;
                var    serialize = Result.Success;
                SocketResponsePackage <TResponse, TResponseTypes> response;
                // TODO: Consider other options.
                if (result.Any(i => i.Level >= ResultIssueLevels.Fatal))
                {
                    ErrorOut(result);
                }

                if (IsFailed ||
                    (response = PackResponse(result, baseResponse)) == null ||
                    !(serialize += PayloadSerializer.Serialize(response, out data)) ||
                    !state.Send(data))
                {
                    Send(state, result + serialize);
                }
            }
            catch (Exception e)
            {
                ErrorOut(result + Result.Error(e));
            }
        }
        protected void AcceptConnection(IAsyncResult result)
        {
            try
            {
                Accepted.Set();

                Socket listener, handler;
                if (result == null ||
                    (listener = result.AsyncState as Socket) == null ||
                    (handler = listener.EndAccept(result)) == null)
                {
                    return;
                }

                // TODO: Consider making this configurable.
                const int bufferSize = 1024;

                // Begin receiving.
                var state = new TransmissionState(this, bufferSize, handler, ServiceValues.EoF);
                state.Receive();
            }
            catch (ObjectDisposedException)
            {
                // Exit gracefully in the event of a shutdown.
            }
            catch (Exception e)
            {
                ErrorOut(e);
            }
        }
Esempio n. 3
0
 /// <summary>
 ///Provides data for UploadFileChanged event
 /// </summary>
 /// <param name="bytesSend">Bytes uploaded</param>
 /// <param name="totalBytesToSend">Total bytes uploaded</param>
 public UploadProgressChangedLibArgs(long bytesSend, long totalBytesToSend)
 {
     TransmissionState = TransmissionState.Uploading;
     BytesSent         = bytesSend;
     TotalBytesToSend  = totalBytesToSend;
     Procent           = Procent_.Get(bytesSend, totalBytesToSend);
 }//constructor
Esempio n. 4
0
        }//constructor

        /// <summary>
        /// Provides data for UploadFileChanged event
        /// </summary>
        /// <param name="transmissionState">TransmissionState e.g. Uploading, CreatingDir..</param>
        public UploadProgressChangedLibArgs(TransmissionState transmissionState)
        {
            TransmissionState = transmissionState;
            BytesSent         = 0;
            TotalBytesToSend  = 0;
            Procent           = 0;
        } //constructor
Esempio n. 5
0
        }//constructor

        /// <summary>
        /// Provides data for UploadFileCompleted event
        /// </summary>
        /// <param name="totalBytesSend"></param>
        /// <param name="transmissionState"></param>
        /// <param name="exception">Upload failed => exception describes error</param>
        public UploadFileCompletedEventLibArgs(long totalBytesSend, TransmissionState transmissionState, Exception exception)
        {
            TotalBytesSend    = totalBytesSend;
            TransmissionState = transmissionState;
            WebException      = null;
            Exception         = exception;
        } //constructor
        }//constructor

        /// <summary>
        /// Provides data for DownloadFileChanged event
        /// </summary>
        /// <param name="totalBytesReceived">TotalBytes downloaded</param>
        /// <param name="transmissionState">TransmissionState</param>
        /// <param name="webException">Webexception | Webexception = NULL in case of success</param>
        public DownloadFileCompletedEventLibArgs(long totalBytesReceived, TransmissionState transmissionState, WebException webException)
        {
            TotalBytesReceived = totalBytesReceived;
            TransmissionState  = transmissionState;
            WebException       = webException;
            Exception          = null;
        }//constructor
        private void LogAndSetTxState(TransmissionState newState)
        {
#if DEBUG
            if (this.Cache == null)
            {
                this.Cache = this.CreateProtoItem(this.OutlookItem);
            }
            Globals.ThisAddIn.Log.Debug($"{this.GetType().Name} '{this.Cache?.Description}': transition {this.TxState} => {newState}");
#endif
            this.TxState = newState;
        }
Esempio n. 8
0
        private TransmissionState DoWriteParameterIntern(int pkParameter, int converterType, ref uint value)
        {
            byte[] array = new byte[13];
            int    num   = GlobalData.PKParameter2ConverterParameter(pkParameter, converterType);

            byte[]            array2;
            TransmissionState result;

            try
            {
                array2 = ProtocolFrame.CreateBuffer((ushort)_serialNumber, 0, (ushort)num, true, false, false, value);
                this.WriteData(array2, 0, array2.Length);
            }
            catch (TimeoutException)
            {
                result = TransmissionState.WriteTimeout;
                return(result);
            }
            catch (Exception ex)
            {
                result = TransmissionState.Error;
                return(result);
            }
            try
            {
                TransmissionState transmissionState = this.ReadFrame(13, array2, array);
                if (transmissionState == TransmissionState.Ok)
                {
                    uint num2 = (uint)(((int)array[7] << 24) + ((int)array[8] << 16) + ((int)array[9] << 8) + (int)array[10]);
                    if (value == num2)
                    {
                        result = TransmissionState.Ok;
                    }
                    else
                    {
                        value  = num2;
                        result = TransmissionState.Error;
                    }
                }
                else
                {
                    result = transmissionState;
                }
            }
            catch (TimeoutException)
            {
                result = TransmissionState.ReadTimeout;
            }
            catch (Exception ex2)
            {
                result = TransmissionState.Error;
            }
            return(result);
        }
Esempio n. 9
0
        /// <summary>
        /// This Task handles all the types of Modbus Functions
        /// </summary>
        /// <returns>The operation.</returns>
        /// <param name="functionType">Function type.</param>
        /// <param name="slaveAddress">Slave address.</param>
        /// <param name="nrRegisters">Nr registers.</param>
        /// <param name="selectedRegisterAddress">Selected register address.</param>
        /// <param name="dataToWrite">Data to write.</param>
        public async Task <ReceivedData> ModbusOperation(ModbusFunctionType functionType, byte slaveAddress, byte[] nrRegisters, byte[] selectedRegisterAddress, byte[] dataToWrite)
        {
            frameToSend = new ModbusFrame();

            if (functionType == ModbusFunctionType.WriteCoil || functionType == ModbusFunctionType.WriteHoldingRegister)
            {
                frameToSend = new ModbusFrame(slaveAddress, functionType, selectedRegisterAddress, null, dataToWrite);
            }
            else
            {
                frameToSend = new ModbusFrame(slaveAddress, functionType, selectedRegisterAddress, nrRegisters, null);
            }


            //We send the message to the Slave Device
            TransmissionState b = await SendMessage(frameToSend.BytePacketToSend);

            sizeOfMessage = CalculateExpectedSize();



            ReceivedData responseData = new ReceivedData();

            //If the message was transmitted right, then proceed with the listening
            //of the response
            if (b == TransmissionState.OK)
            {
                System.Diagnostics.Debug.WriteLine("MessageSended: " + b.ToString());

                //TO-DO Implement the retry mechanism
                //int retries = 3;
                //responseData = await ListenMessages();

                responseData = await ListenMessages();
            }
            else
            {
                responseData.state = TransmissionState.ErrorSendMessage;
            }

            if (responseData.state == TransmissionState.OK)
            {
                frameReceived = new ModbusFrame(responseData.data);
            }
            else
            {
                frameReceived = new ModbusFrame();
            }

            return(responseData);
        }
Esempio n. 10
0
        private TransmissionState ReadFileBlock(uint uiFileIndex, byte[] values, int converterType)
        {
            int num = Settings.Default.ReadFileBlockRepeat;
            TransmissionState transmissionState = this.ReadFileBlockIntern(values, converterType);

            while (transmissionState != TransmissionState.Ok && --num >= 0)
            {
                uint v = uiFileIndex / 4u;
                transmissionState = this.DoWriteParameterIntern(264, 0, ref v);
                if (transmissionState == TransmissionState.Ok)
                {
                    transmissionState = this.ReadFileBlockIntern(values, converterType);
                }
            }
            return(transmissionState);
        }
Esempio n. 11
0
        private TransmissionState ReadFileBlockIntern(byte[] values, int converterType)
        {
            byte[] array = new byte[137];
            int    num   = GlobalData.PKParameter2ConverterParameter(270, converterType);

            byte[]            array2;
            TransmissionState result;

            try
            {
                array2 = ProtocolFrame.CreateBuffer((ushort)_serialNumber, 0, (ushort)num, false, true, false, 0u);
                this.WriteData(array2);
            }
            catch (TimeoutException)
            {
                result = TransmissionState.WriteTimeout;
                return(result);
            }
            catch (Exception ex)
            {
                result = TransmissionState.Error;
                return(result);
            }
            try
            {
                TransmissionState transmissionState = this.ReadFrame(137, array2, array);
                if (transmissionState == TransmissionState.Ok)
                {
                    Array.Copy(array, 7, values, 0, 128);
                    result = TransmissionState.Ok;
                }
                else
                {
                    result = transmissionState;
                }
            }
            catch (TimeoutException)
            {
                result = TransmissionState.ReadTimeout;
            }
            catch (Exception ex2)
            {
                result = TransmissionState.Error;
            }
            return(result);
        }
Esempio n. 12
0
 private void LogAndSetTxState(TransmissionState newState)
 {
     try
     {
         if (this.Cache == null)
         {
             this.Cache = this.CreateProtoItem();
         }
         Globals.ThisAddIn.Log.Debug(
             $"{this.GetType().Name} '{this.Cache?.Description}': transition {this.TxState} => {newState}");
     }
     catch (InvalidComObjectException)
     {
         // ignore. It doesn't matter. Although TODO: I'd love to know what happens.
     }
     this.TxState = newState;
 }
Esempio n. 13
0
 public ProtocolFrame(ushort receiver, ushort sender, ushort parameter, bool write, bool read, bool master, bool error, bool file, bool vdew, byte[] value)
 {
     this.Time          = DateTime.Now;
     this.buffer        = ProtocolFrame.CreateBuffer(receiver, sender, parameter, write, read, master, error, file, vdew, value);
     this.DataLength    = value.Length;
     this.Checksum      = this.buffer[7 + this.DataLength];
     this.RatedChecksum = this.Checksum;
     this.Receiver      = receiver;
     this.Sender        = sender;
     this.Parameter     = parameter;
     this.Write         = write;
     this.Read          = read;
     this.Master        = master;
     this.Error         = error;
     this.File          = file;
     this.Vdew          = vdew;
     this.State         = TransmissionState.Ok;
 }
Esempio n. 14
0
        private TransmissionState DrillDownBranchRecursive(AggregationTreeNode tnUpper, MatrixManipulator manipulator)
        {
            var stateUpperDesignated = new TransmissionState();

            if (!tnUpper.IsLeaf)
            {
                foreach (var tn in tnUpper.Children)
                {
                    var aggState = DrillDownBranchRecursive(tn, manipulator);
                    var aggValue = manipulator.AggregationFunctionVector[tn.Level](aggState.LevelValues);
                    stateUpperDesignated.LevelValues.Add(aggValue); // pass to upper
                    stateUpperDesignated.TreeNodes.Add(tn);
                    manipulator.setValue(tn.Dimmension, aggValue);
                }
            }
            else
            {
                stateUpperDesignated.LevelValues.Add(manipulator.getValue(tnUpper.Dimmension));
            }

            return(stateUpperDesignated);
        }
        public static bool initSampleTransmission(int count, int fx1, int fx2, int tempo)
        {
            if (tState != TransmissionState.NA)
                return false;

            /* set up for transmission */
            UsbEndpointReader reader = Device.OpenEndpointReader(ReadEndpointID.Ep01);
            UsbEndpointWriter writer = Device.OpenEndpointWriter(WriteEndpointID.Ep01);

            int bytesWritten, bytesRead;
            byte[] setupMsg = getInitTransferCmd(count, fx1, fx2, tempo);
            byte[] setupReply = new byte[1];
            /* update the state */
            eCode = writer.Write(setupMsg, Int32.MaxValue, out bytesWritten);
            if (eCode != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);
            reader.Read(setupReply, Int32.MaxValue, out bytesRead);
            if (eCode != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

            if (setupReply[0] != Constants.TRANSFER_OK) {
                tState = TransmissionState.NA;
                return false;
            }
            return true;
        }
Esempio n. 16
0
 public TransmissionException(TransmissionState state) : base($"Transmission failure: {state}.")
 {
 }
Esempio n. 17
0
 public TransmissionException(TransmissionState state)
 {
     this.State = state;
 }
Esempio n. 18
0
 public ReceivedData()
 {
     this.data  = new byte[] { };
     this.state = TransmissionState.NONE;
 }
Esempio n. 19
0
 public ReceivedData(byte[] data, TransmissionState state)
 {
     this.data  = data;
     this.state = state;
 }
Esempio n. 20
0
 public BadStateTransition(SyncState state, TransmissionState from, TransmissionState to) : base($"{state.GetType().Name}: failed transition {from} => {to}")
 {
     this.To   = to;
     this.From = from;
 }
Esempio n. 21
0
 /// <summary>
 /// Provides data for UploadFileChanged event
 /// </summary>
 /// <param name="transmissionState">TransmissionState e.g. Uploading, CreatingDir..</param>
 public UploadProgressChangedLibArgs(TransmissionState transmissionState)
 {
     TransmissionState = transmissionState;
     BytesSent = 0;
     TotalBytesToSend = 0;
     Procent = 0;
 }
Esempio n. 22
0
 /// <summary>
 /// Mijenja stanje, mice handler is prijasnjeg stanja i instalira handlere za trenutno stanje
 /// </summary>
 /// <param name="new_state"></param>
 private void ChangeState(TransmissionState new_state)
 {
     this.State.UnInstallHandlers(this);
     this.State = new_state;
     this.State.InstallHandlers(this);
 }
Esempio n. 23
0
 /// <summary>
 /// Provides data for UploadFileCompleted event
 /// </summary>
 /// <param name="totalBytesSend"></param>
 /// <param name="transmissionState"></param>
 /// <param name="exception">Upload failed => exception describes error</param>
 public UploadFileCompletedEventLibArgs(long totalBytesSend, TransmissionState transmissionState, Exception exception)
 {
     TotalBytesSend = totalBytesSend;
     TransmissionState = transmissionState;
     WebException = null;
     Exception = exception;
 }
Esempio n. 24
0
 /// <summary>
 /// Provides data for DownloadFileChanged event
 /// </summary>
 /// <param name="totalBytesReceived">TotalBytes downloaded</param>
 /// <param name="transmissionState">TransmissionState</param>
 /// <param name="exception">Exception | Exception = NULL in case of success</param>
 public DownloadFileCompletedEventLibArgs(long totalBytesReceived, TransmissionState transmissionState, Exception exception)
 {
     TotalBytesReceived = totalBytesReceived;
     TransmissionState = transmissionState;
     WebException = null;
     Exception = exception;
 }
Esempio n. 25
0
        public ProtocolFrame(byte[] data, int startIndex, int length)
        {
            this.Time = DateTime.Now;
            if (length < 13)
            {
                throw new ArgumentOutOfRangeException("length", length, "must not be less then " + 13);
            }
            if (data[startIndex] != 2)
            {
                throw new ApplicationException("FrameErrorException");
            }
            this.State    = TransmissionState.Ok;
            this.Receiver = (ushort)(((int)data[startIndex + 1] << 8) + (int)data[startIndex + 2]);
            this.Sender   = (ushort)(((int)data[startIndex + 3] << 8) + (int)data[startIndex + 4]);
            ushort num = (ushort)(((int)data[startIndex + 5] << 8) + (int)data[startIndex + 6]);

            this.Parameter = (ushort)(num & 1023);
            this.Write     = ((num & 32768) == 32768);
            this.Read      = ((num & 16384) == 16384);
            this.Master    = ((num & 8192) == 8192);
            this.Error     = ((num & 4096) == 4096);
            this.File      = ((num & 2048) == 2048);
            this.Vdew      = ((num & 1024) == 1024);
            int num2;

            if (this.File)
            {
                if (length < 137)
                {
                    throw new ApplicationException("FrameErrorException");
                }
                num2 = 137;
            }
            else
            {
                num2 = 13;
            }
            if (data[startIndex + num2 - 1] != 3)
            {
                throw new ApplicationException("FrameErrorException");
            }
            this.Checksum      = data[startIndex + num2 - 2];
            this.RatedChecksum = GlobalData.CalcChecksum(data, startIndex + 1, startIndex + num2 - 3);
            if (this.RatedChecksum != this.Checksum)
            {
                this.State = TransmissionState.ChecksumError;
            }
            if (this.State == TransmissionState.Ok && this.Error)
            {
                switch (data[startIndex + 10])
                {
                case 1:
                    this.State = TransmissionState.UnknownParameter;
                    break;

                case 2:
                    this.State = TransmissionState.PasswordProtected;
                    break;

                case 3:
                    this.State = TransmissionState.MaxValueError;
                    break;

                case 4:
                    this.State = TransmissionState.MinValueError;
                    break;

                case 5:
                    this.State = TransmissionState.ParameterIsReadOnly;
                    break;

                case 6:
                    this.State = TransmissionState.AccessCode1;
                    break;

                case 7:
                    this.State = TransmissionState.AccessCode2;
                    break;

                case 8:
                    this.State = TransmissionState.NoCommand;
                    break;

                case 9:
                    this.State = TransmissionState.WrongValue;
                    break;

                case 10:
                    this.State = TransmissionState.NoAnswer;
                    break;

                case 11:
                    this.State = TransmissionState.NoFWFile;
                    break;

                default:
                    this.State = TransmissionState.Error;
                    break;
                }
            }
            if (this.File)
            {
                this.DataLength = 128;
                this.buffer     = new byte[137];
            }
            else
            {
                this.DataLength = 4;
                this.buffer     = new byte[13];
            }
            Array.Copy(data, startIndex, this.buffer, 0, this.buffer.Length);
        }
        private static void initSampleTransmission(int row, int col, string filepath, int mode, int loop)
        {
            if (tState != TransmissionState.NA)
                return;
            /* set up for transmission */
            UsbEndpointReader reader = Device.OpenEndpointReader(ReadEndpointID.Ep01);
            UsbEndpointWriter writer = Device.OpenEndpointWriter(WriteEndpointID.Ep01);

            int bytesWritten, bytesRead;
            byte[] setupMsg = getTransferCmd(row, col, filepath, mode, loop);
            byte[] setupReply = new byte[1];
            /* update the state */
            tState = TransmissionState.INIT;
            eCode = writer.Write(setupMsg, Int32.MaxValue, out bytesWritten);
            if (eCode != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);
            reader.Read(setupReply, Int32.MaxValue, out bytesRead);
            if (eCode != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

            if (setupReply[0] != Constants.TRANSFER_OK) {
                tState = TransmissionState.NA;
                return;
            }

            tState = TransmissionState.TRANSFER;
        }
Esempio n. 27
0
 public NodeCommandCompleted(byte[] payload) : 
     base(FrameHeader.SOF, MessageType.Request, Channel.Function.SendData)
 {
     CallbackID = payload[0];
     TransmissionState = (TransmissionState)payload[1];
 }
Esempio n. 28
0
        private TransmissionState DoReadFile(uint fileNumber, int converterType)
        {
            uint num  = 0u;
            uint num2 = 0u;

            byte[] values = new byte[128];
            int    num3   = Settings.Default.ReadFileLengthRepeat;

            int num4 = (int)fileNumber;

            if (num4 <= 12)
            {
                if (num4 != 2)
                {
                    if (num4 == 12)
                    {
                        this.file12Data = new byte[32768];
                    }
                }
            }
            else
            {
                if (num4 != 18)
                {
                    if (num4 == 28)
                    {
                        this.file28Data = new byte[32768];
                    }
                }
                else
                {
                    this.file18Data = new byte[1480];
                }
            }
            uint v = 0;
            TransmissionState transmissionState = DoWriteParameterIntern(260, converterType, ref v);

            if (transmissionState == TransmissionState.Ok)
            {
                transmissionState = this.DoWriteParameterIntern(260, converterType, ref fileNumber);
            }
            DateTime t = DateTime.Now.AddMilliseconds((double)Settings.Default.ReadFileLengthTimeout);

            while (transmissionState == TransmissionState.Ok && num == 0u && num3 > 0 && t > DateTime.Now)
            {
                transmissionState = this.DoReadParameter(261, out num, converterType);
                System.Threading.Thread.Sleep(50);
                num3--;
            }

            num *= 4u;
            uint num5 = num;

            if (fileNumber == 23 || fileNumber == 24 || fileNumber == 31)
            {
                this.fileRawData = new byte[num];
            }
            if (transmissionState == TransmissionState.Ok && num == 0u)
            {
                transmissionState = TransmissionState.ReadTimeout;
            }
            if (transmissionState == TransmissionState.Ok)
            {
                while (transmissionState == TransmissionState.Ok)
                {
                    if (num5 <= 0u)
                    {
                        break;
                    }
                    Thread.Sleep(50);

                    transmissionState = this.ReadFileBlock(num2, values, converterType);
                    if (num5 >= 128u)
                    {
                        FileData(values, num2, 128u, fileNumber);
                        num5 -= 128u;
                    }
                    else
                    {
                        FileData(values, num2, num5, fileNumber);
                        num5 = 0u;
                    }
                    num2 += 128u;
                }
            }

            return(transmissionState);
        }
Esempio n. 29
0
 /// <summary>
 ///Provides data for UploadFileChanged event 
 /// </summary>
 /// <param name="bytesSend">Bytes uploaded</param>
 /// <param name="totalBytesToSend">Total bytes uploaded</param>
 public UploadProgressChangedLibArgs(long bytesSend, long totalBytesToSend)
 {
     TransmissionState = TransmissionState.Uploading;
     BytesSent = bytesSend;
     TotalBytesToSend = totalBytesToSend;
     Procent = Net.Procent.Get(bytesSend, totalBytesToSend);
 }
Esempio n. 30
0
 public NodeCommandCompleted(byte[] payload) :
     base(FrameHeader.SOF, MessageType.Request, Channel.Function.SendData)
 {
     CallbackID        = payload[0];
     TransmissionState = (TransmissionState)payload[1];
 }
        public static bool transmitSample(int row, int col, string filepath, int mode, int loop, int stream)
        {
            try {
                initSampleTransmission(row, col, filepath, mode, loop);
                if (tState != TransmissionState.TRANSFER)
                    return false;

                UsbEndpointReader reader = Device.OpenEndpointReader(ReadEndpointID.Ep01);
                UsbEndpointWriter writer = Device.OpenEndpointWriter(WriteEndpointID.Ep01);

                /* reset the position to the start */
                Bass.BASS_ChannelSetPosition(stream, 0);

                long fileSize = new FileInfo(filepath).Length;
                long length = Bass.BASS_ChannelGetLength(stream);
                int offset = 0, TotalbytesWritten = 0;
                do {
                    long pos = Bass.BASS_ChannelGetPosition(stream);
                    int size = bufferSize, bytesWritten = 0, bytesRead = 0;
                    if (offset + size > fileSize) {
                        size = Convert.ToInt32(fileSize) - offset;
                    }
                    /* send & receive buffers */
                    byte[] data = new byte[size], receive = new byte[10];
                    Bass.BASS_ChannelGetData(stream, data, size);
                    /* write the data */
                    eCode = writer.Write(data, Int32.MaxValue, out bytesWritten);
                    if (eCode != ErrorCode.None) {
                        throw new Exception(UsbDevice.LastErrorString);
                    }
                    TotalbytesWritten += bytesWritten;
                    /* read and then check successful response */
                    eCode = reader.Read(receive, Int32.MaxValue, out bytesRead);
                    if (eCode != ErrorCode.None) {
                        throw new Exception(UsbDevice.LastErrorString);
                    }
                    offset += bytesWritten;
                    switch (receive[0]) {
                        case Constants.TRANSFER_OK:
                            break;
                        case Constants.TRANSFER_CMP:
                            if (offset != fileSize)
                                throw new Exception("Unexpected end of transmission");
                            break;
                        case Constants.TRANSFER_ERR:
                        default:
                            throw new Exception("error in transmission");
                    }
                } while (offset < length);
            } catch (Exception ex) {
                throw ex;
            } finally {
                if (Device != null) {
                    if (Device.IsOpen) {
                        Device.Close();
                    }
                }
                Device = null;
                // Free usb resources
                UsbDevice.Exit();
                tState = TransmissionState.NA;
            }

            return true;
        }
Esempio n. 32
0
        public Protocol()
        {
            log.Debug("Protocol:ctor");

            _state = TransmissionState.Idle;
            _state.InstallHandlers(this);
            _input = new BlockingCollection<string>();
            _output = new BlockingCollection<string>();
            _orders = new Dictionary<string, Message>();
            _commands = new BlockingCollection<ICommand>();
            _results = new BlockingCollection<Message>();
            _receiveHandlerMap = new Dictionary<string, Action<ProtocolReceiverEventArgs>>();
            _messageHandlerMap = new Dictionary<string, Action<MessageReceiveEventArgs>>();
            _timer = new System.Timers.Timer();
            _timer.AutoReset = false;
            Entity = Entity.Host;
            Mode = Mode.RealTime;

            InitReceiveEventMap();
            InitMessageEventMap();

            //_task = Task.Factory.StartNew(ReceiverTask);
            _task_cancel = new CancellationTokenSource();
            //_command_task = Task.Factory.StartNew(CommandTask);
            _command_task_cancel = new CancellationTokenSource();
            _waitHandle = new AutoResetEvent(false);
        }
Esempio n. 33
0
        public void Run()
        {
            ILogger <InverterTask>     logger      = ServiceFactory.CurrentServiceProvider.GetService <ILogger <InverterTask> >();
            ILogger <FimerR25Inverter> loggerFimer = ServiceFactory.CurrentServiceProvider.GetService <ILogger <FimerR25Inverter> >();

            IMQTTQueueService mqttService = ServiceFactory.CurrentServiceProvider.GetService <IMQTTQueueService>();

            using (IInverter currentInverter = new FimerR25Inverter(loggerFimer))
            {
                Hashtable ht = new Hashtable
                {
                    { InverterCommonProperties.NET_IP_ADDRESS, "192.168.0.99" },
                    { InverterCommonProperties.NET_IP_PORT, "33330" },
                    { InverterCommonProperties.SERIAL_NUMBER, "18344" }
                };

                logger.LogDebug($"Connect to: {ht[InverterCommonProperties.NET_IP_ADDRESS]} - Port: {ht[InverterCommonProperties.NET_IP_PORT]} - Serial : {ht[InverterCommonProperties.SERIAL_NUMBER]}");

                Ping p = new Ping();

                PingReply pr = p.Send(IPAddress.Parse((string)ht[InverterCommonProperties.NET_IP_ADDRESS]), 5000);
                if (pr.Status == IPStatus.Success)
                {
                    logger.LogDebug("initing...");
                    currentInverter.Init(ht);
                    logger.LogDebug("connecting...");
                    TransmissionState ts = currentInverter.Connect();
                    logger.LogDebug("connected");
                    if (ts == TransmissionState.Ok)
                    {
                        logger.LogDebug("start reading...");

                        ConverterStatus?cs = currentInverter.ReadData(31);

                        logger.LogDebug("Reading status:" + (cs != null).ToString());
                        if (cs == null)
                        {
                            logger.LogDebug("Nessun dato letto");
                            currentInverter.Dispose();
                        }
                        ServiceFactory.CurrentServiceProvider.GetService <IPersisterFactory>().Save(currentInverter, cs);

                        MessageBase mb = new MessageBase
                        {
                            Command = Constants.Power.Messages.ProductionDataAcquired,
                            Data    = new ProductionDataInfo
                            {
                                DailyValue   = cs.Value.CommonStatus.EnergieTag * 1000,
                                CurrentValue = (ushort)cs.Value.TypeStatus.GetProperty(CommonPropertyType.ProduzioneCorrente)
                            }
                        };
                        var jsonSerializerSettings = new JsonSerializerSettings()
                        {
                            TypeNameHandling = TypeNameHandling.All
                        };
                        mqttService.Publish(Constants.Power.Queues.Production, JsonConvert.SerializeObject(mb, jsonSerializerSettings));
                    }
                    else
                    {
                        logger.LogDebug($"reading error:{ts}");
                    }
                }
            }
        }