public async Task <byte[]> PostAsync(Stream inputStream) { var reader = new BinaryReader(inputStream); BinaryRequest request = BinaryRequest.Read(reader); var task = TryHandleAsync <GetManyRequest, GetManyResponse>(request, GetManyAsync) ?? TryHandleAsync <PostRequest, PostResponse>(request, PostAsync) ?? TryHandleAsync <InterruptRequest, InterruptResponse>(request, InterruptAsync) ?? TryHandleAsync <NotifyRequest, NotifyResponse>(request, NotifyAsync) ?? TryHandleAsync <WindowsPhoneSubscribeRequest, WindowsPhoneSubscribeResponse>(request, WindowsPhoneSubscribeAsync) ?? TryHandleAsync <WindowsPhoneUnsubscribeRequest, WindowsPhoneUnsubscribeResponse>(request, WindowsPhoneUnsubscribeAsync); if (task == null) { throw new CorrespondenceException(String.Format("Unknown request type {0}.", request)); } BinaryResponse response = await task; MemoryStream memory = new MemoryStream(); using (var writer = new BinaryWriter(memory)) { response.Write(writer); } return(memory.ToArray()); }
public BinaryResponse ProccessRequest(BinaryRequest request) { BinaryResponse response = new BinaryResponse(); response.originalString = request.stringToModify; string stringInProgress = request.stringToModify; byte[] btText; btText = System.Text.Encoding.UTF8.GetBytes(stringInProgress); Array.Reverse(btText); System.Collections.BitArray bit = new System.Collections.BitArray(btText); String responseString = ""; for (int i = bit.Length - 1; i >= 0; i--) { if (bit[i] == true) { //response.ModifiedString(1); responseString += "1"; } else { //response.ModifiedString(0); responseString += "0"; } } response.modifiedString = responseString; return(response); }
protected override BinaryRequest Build() { var request = new BinaryRequest(0x96) { Data = this.BuildBody() }; return(request); }
private Task <BinaryResponse> TryHandleAsync <TRequest, TResponse>(BinaryRequest request, Func <TRequest, Task <TResponse> > method) where TRequest : BinaryRequest where TResponse : BinaryResponse { TRequest specificRequest = request as TRequest; if (specificRequest != null) { return(method(specificRequest).ContinueWith(t => (BinaryResponse)t.Result)); } else { return(null); } }
protected override BinaryRequest Build() { var op = (byte)CouchbaseOpCode.Unlock; var request = new BinaryRequest(op); if (this.locator != null) { request.Reserved = (ushort)locator.GetIndex(this.Key); if (log.IsDebugEnabled) { log.DebugFormat("Key {0} was mapped to {1}", this.Key, request.Reserved); } } request.Key = Key; request.Cas = Cas; return(request); }
public IActionResult BinaryControl([FromBody] BinaryRequest request) { BinaryResponse binResonse; try { //_bin.ValidateRequest(request); string[] words = request.stringToModify.Split(' '); Thread thread1 = new Thread(() => ControllerHelperFunctions.databaseWordTransaction(words, _DB)); thread1.Start(); binResonse = _bin.ProccessRequest(request); } catch (Exception e) { return(StatusCode(500, e.Message)); } return(StatusCode(200, binResonse)); }
protected override BinaryRequest Build() { var retval = new BinaryRequest(0x1c); retval.Key = this.Key; if (this.locator != null) { retval.Reserved = (ushort)locator.GetIndex(this.Key); if (log.IsDebugEnabled) { log.DebugFormat("Key {0} was mapped to {1}", this.Key, retval.Reserved); } } var extra = new byte[4]; BinaryConverter.EncodeUInt32(this.expires, extra, 0); retval.Extra = new ArraySegment <byte>(extra); return(retval); }
private void SplitAndSendBinaryData(ReadWriteRequest binaryRequest, string parentID) { BinaryRequest binRequest = binaryRequest as BinaryRequest; PComB pComB = new PComB(); int offsetInBuffer = 0; int chunkSize = 0; int outgoingBufferSize = 0; int currentAddress = binRequest.Address; int messageKey = binRequest.MessageKey; const int MIN_TIME_BETWEEN_CHUNKS_WRITE = 20; GuidClass guid; PlcResponseMessage plcResponseMessage; byte[] outgoingChunk; if (binRequest.OutgoingBuffer != null) { outgoingBufferSize = binRequest.OutgoingBuffer.Length; } switch (binRequest.CommandCode) { case 0x1: case 0x41: case 75: case 5: if ((binRequest.OutgoingBuffer == null) || (outgoingBufferSize == 0)) { binRequest.RaiseProgressEvent(0, binRequest.ElementsCount, RequestProgress.en_NotificationType.SetMinMax, 0, ""); binRequest.RaiseProgressEvent(0, binRequest.ElementsCount, RequestProgress.en_NotificationType.ProgressChanged, 0, ""); if (this.BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } if (binRequest.WaitForIdle) { WaitForFlashIdle((byte)UnitId, parentID); } byte[] arrivedData = new byte[binRequest.ElementsCount]; while (offsetInBuffer < binRequest.ElementsCount) { int sizeOfDataToCopy; if (this.BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } chunkSize = binRequest.ElementsCount - offsetInBuffer; sizeOfDataToCopy = chunkSize; if (chunkSize > PLCVersion.PlcBuffer - Utils.Lengths.LENGTH_HEADER_AND_FOOTER) { chunkSize = PLCVersion.PlcBuffer - Utils.Lengths.LENGTH_HEADER_AND_FOOTER; } if (binRequest.ChunkSizeAlignment != 0) { // Chop the end of the chunk to fit into aligment chunkSize -= (chunkSize % binRequest.ChunkSizeAlignment); } if (binRequest.FlashBankSize != 0) { // Chop the end of the chunk so the burned data will not be written on 2 different flash banks if (((currentAddress + chunkSize) / binRequest.FlashBankSize) != (currentAddress / binRequest.FlashBankSize)) { chunkSize -= ((currentAddress + chunkSize) % binRequest.FlashBankSize); } } if (chunkSize == 0) { chunkSize = binRequest.ChunkSizeAlignment; } else { sizeOfDataToCopy = chunkSize; } pComB.BuildBinaryCommand((byte)UnitId, messageKey, binRequest.CommandCode, binRequest.SubCommand, currentAddress, chunkSize, 0, new byte[0]); guid = new GuidClass(); lock (guid) { Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID, "Binary Protocol - Binary Request (" + binRequest.CommandCode.ToString() + ")", PlcGuid); Monitor.Wait(guid); } if (this.BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } lock (_lockObj) { plcResponseMessage = m_responseMessageQueue[guid]; m_responseMessageQueue.Remove(guid); } if (plcResponseMessage.comException == CommunicationException.Timeout) { throw new ComDriveExceptions( "Cannot communicate with the PLC with the specified UnitID!", ComDriveExceptions.ComDriveException.CommunicationTimeout); } binRequest.IncomingBuffer = new byte[plcResponseMessage.responseBytesMessage.Length - Utils.Lengths.LENGTH_HEADER_AND_FOOTER]; if (binRequest.IncomingBuffer.Length > 0) { Array.Copy(plcResponseMessage.responseBytesMessage, Utils.Lengths.LENGTH_HEADER, binRequest.IncomingBuffer, 0, binRequest.IncomingBuffer.Length); } Array.Copy(binRequest.IncomingBuffer, 0, arrivedData, offsetInBuffer, sizeOfDataToCopy); if (plcResponseMessage.responseBytesMessage[12] == 0xFF) { binRequest.PlcReceiveResult = (BinaryRequest.ePlcReceiveResult)plcResponseMessage.responseBytesMessage[13]; } else if (plcResponseMessage.responseBytesMessage[12] == binRequest.CommandCode + 0x80) { binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Sucsess; } else { binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Unknown; } offsetInBuffer += sizeOfDataToCopy; currentAddress += sizeOfDataToCopy; messageKey++; // Message Key is % 256. The BuildBinaryCommand takes care of that binRequest.MessageKey = messageKey; binRequest.MessageKey = binRequest.MessageKey % 256; if (binRequest.MessageKey == 0) { messageKey = binRequest.CycledMessageKey; binRequest.MessageKey = messageKey; } if (binRequest.WaitForIdle) { WaitForFlashIdle((byte)UnitId, parentID); } binRequest.RaiseProgressEvent(0, binRequest.ElementsCount, RequestProgress.en_NotificationType.ProgressChanged, offsetInBuffer, ""); } binRequest.IncomingBuffer = arrivedData; binRequest.RaiseProgressEvent(0, binRequest.ElementsCount, RequestProgress.en_NotificationType.Completed, binRequest.ElementsCount, ""); } else { if (this.BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } if (binRequest.WaitForIdle) { WaitForFlashIdle((byte)UnitId, parentID); } binRequest.RaiseProgressEvent(0, outgoingBufferSize, RequestProgress.en_NotificationType.SetMinMax, 0, ""); binRequest.RaiseProgressEvent(0, outgoingBufferSize, RequestProgress.en_NotificationType.ProgressChanged, 0, ""); //if (binRequest.SubCommand == (int)MemoryType.InternalFlash && binRequest.CommandCode == 0x41) //{ // if ((binRequest.OutgoingBuffer.Length % 8) != 0) // { // byte[] binDataToBurn = new byte[binRequest.OutgoingBuffer.Length + 8 - binRequest.OutgoingBuffer.Length % 8]; // for (int i = binRequest.OutgoingBuffer.Length; i < binDataToBurn.Length; i++) // { // binDataToBurn[i] = 0xFF; // } // Array.Copy(binRequest.OutgoingBuffer, 0, binDataToBurn, 0, binRequest.OutgoingBuffer.Length); // binRequest.OutgoingBuffer = binDataToBurn; // outgoingBufferSize = binRequest.OutgoingBuffer.Length; // } //} Stopwatch sw = new Stopwatch(); sw.Start(); long lastTime = 0; while (offsetInBuffer < outgoingBufferSize) { if (this.BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } chunkSize = outgoingBufferSize - offsetInBuffer; if (chunkSize > PLCVersion.PlcBuffer - Utils.Lengths.LENGTH_HEADER_AND_FOOTER) { chunkSize = PLCVersion.PlcBuffer - Utils.Lengths.LENGTH_HEADER_AND_FOOTER; } if (binRequest.ChunkSizeAlignment != 0) { // Chop the end of the chunk to fit into aligment chunkSize -= (chunkSize % binRequest.ChunkSizeAlignment); } if (binRequest.FlashBankSize != 0) { // Chop the end of the chunk so the burned data will not be written on 2 different flash banks if (((currentAddress + chunkSize) / binRequest.FlashBankSize) != (currentAddress / binRequest.FlashBankSize)) { chunkSize -= ((currentAddress + chunkSize) % binRequest.FlashBankSize); } } //if (binRequest.SubCommand == (int)MemoryType.InternalFlash && binRequest.CommandCode == 0x41) //{ // if ((chunkSize % 8) != 0) // chunkSize -= chunkSize % 8; //} outgoingChunk = new byte[chunkSize]; Array.Copy(binRequest.OutgoingBuffer, offsetInBuffer, outgoingChunk, 0, chunkSize); // Programming command (0x41) // We want to put it on PLC even if the chunk is full with 0xff (Because it is not a flash memory) if ((binRequest.CommandCode == 0x41 && binRequest.SubCommand == (int)MemoryType.SRAM) || IsValidChunkBufferData(outgoingChunk, binRequest.DecodeValue)) { if (sw.ElapsedMilliseconds - lastTime < MIN_TIME_BETWEEN_CHUNKS_WRITE) { Thread.Sleep((int)(MIN_TIME_BETWEEN_CHUNKS_WRITE - (sw.ElapsedMilliseconds - lastTime))); } pComB.BuildBinaryCommand((byte)UnitId, messageKey, binRequest.CommandCode, binRequest.SubCommand, currentAddress, chunkSize, (ushort)chunkSize, outgoingChunk); lastTime = sw.ElapsedMilliseconds; messageKey++; // Message Key is % 256. The BuildBinaryCommand takes care of that binRequest.MessageKey = messageKey; binRequest.MessageKey = binRequest.MessageKey % 256; if (binRequest.MessageKey == 0) { messageKey = binRequest.CycledMessageKey; binRequest.MessageKey = messageKey; } guid = new GuidClass(); lock (guid) { Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID, "Binary Protocol - Binary Request (" + binRequest.CommandCode.ToString() + ")", PlcGuid); Monitor.Wait(guid); } if (this.BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } lock (_lockObj) { plcResponseMessage = m_responseMessageQueue[guid]; m_responseMessageQueue.Remove(guid); } if (plcResponseMessage.comException == CommunicationException.Timeout) { throw new ComDriveExceptions( "Cannot communicate with the PLC with the specified UnitID!", ComDriveExceptions.ComDriveException.CommunicationTimeout); } binRequest.IncomingBuffer = new byte[plcResponseMessage.responseBytesMessage.Length - Utils.Lengths.LENGTH_HEADER_AND_FOOTER]; if (binRequest.IncomingBuffer.Length > 0) { Array.Copy(plcResponseMessage.responseBytesMessage, Utils.Lengths.LENGTH_HEADER, binRequest.IncomingBuffer, 0, binRequest.IncomingBuffer.Length); } if (plcResponseMessage.responseBytesMessage[12] == 0xFF) { binRequest.PlcReceiveResult = (BinaryRequest.ePlcReceiveResult)plcResponseMessage.responseBytesMessage[13]; } else if (plcResponseMessage.responseBytesMessage[12] == binRequest.CommandCode + 0x80) { binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Sucsess; } else { binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Unknown; } if (binRequest.PlcReceiveResult != BinaryRequest.ePlcReceiveResult.Sucsess) { return; } if (binRequest.WaitForIdle) { WaitForFlashIdle((byte)UnitId, parentID); } else { if (binRequest.CommandCode == 0x41) { Thread.Sleep(25); } } } else { Debug.Print("Not Valid"); } offsetInBuffer += chunkSize; currentAddress += chunkSize; binRequest.RaiseProgressEvent(0, outgoingBufferSize, RequestProgress.en_NotificationType.ProgressChanged, offsetInBuffer, ""); } binRequest.RaiseProgressEvent(0, outgoingBufferSize, RequestProgress.en_NotificationType.Completed, outgoingBufferSize, ""); } break; default: binRequest.RaiseProgressEvent(0, 100, RequestProgress.en_NotificationType.SetMinMax, 0, ""); binRequest.RaiseProgressEvent(0, 100, RequestProgress.en_NotificationType.ProgressChanged, 0, ""); pComB.BuildBinaryCommand((byte)UnitId, messageKey, binRequest.CommandCode, binRequest.SubCommand, currentAddress, binRequest.ElementsCount, (ushort)outgoingBufferSize, binRequest.OutgoingBuffer); if (this.BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } if (binRequest.WaitForIdle) { WaitForFlashIdle((byte)UnitId, parentID); } guid = new GuidClass(); lock (guid) { Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID, "Binary Protocol - Binary Request (" + binRequest.CommandCode.ToString() + ")", PlcGuid); Monitor.Wait(guid); } if (this.BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } lock (_lockObj) { plcResponseMessage = m_responseMessageQueue[guid]; m_responseMessageQueue.Remove(guid); } if (plcResponseMessage.comException == CommunicationException.Timeout) { throw new ComDriveExceptions("Cannot communicate with the PLC with the specified UnitID!", ComDriveExceptions.ComDriveException.CommunicationTimeout); } binRequest.IncomingBuffer = new byte[plcResponseMessage.responseBytesMessage.Length - Utils.Lengths.LENGTH_HEADER_AND_FOOTER]; if (binRequest.IncomingBuffer.Length > 0) { Array.Copy(plcResponseMessage.responseBytesMessage, Utils.Lengths.LENGTH_HEADER, binRequest.IncomingBuffer, 0, binRequest.IncomingBuffer.Length); } if (plcResponseMessage.responseBytesMessage[12] == 0xFF) { binRequest.PlcReceiveResult = (BinaryRequest.ePlcReceiveResult)plcResponseMessage.responseBytesMessage[13]; } else if (plcResponseMessage.responseBytesMessage[12] == binRequest.CommandCode + 0x80) { binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Sucsess; } else { binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Unknown; } if (binRequest.WaitForIdle) { WaitForFlashIdle((byte)UnitId, parentID); } binRequest.RaiseProgressEvent(0, 100, RequestProgress.en_NotificationType.Completed, 100, ""); break; } }
internal void Write(BinaryRequest req) { req.Write(stream); stream.Flush(); }
internal void ReadWrite(ref ReadWriteRequest[] values, bool suppressEthernetHeader) { lock (objectLocker) { m_BreakFlagCount++; } System.Diagnostics.Debug.Print("Entering Read Write. Count: " + m_BreakFlagCount.ToString()); Guid parentID = Guid.NewGuid(); List <ReadWriteRequest> requestsList = new List <ReadWriteRequest>(); try { ComDriverLogger.LogReadWriteRequest(DateTime.Now, m_channel.GetLoggerChannelText(), values, MessageDirection.Sent, parentID.ToString()); CheckReadWriteRequests(values); for (int i = 0; i < values.Length; i++) { ReadWriteRequest rw = values[i]; if ((rw is ReadOperands) || (rw is WriteOperands)) { requestsList.Add(rw); if (i == values.Length - 1) { if (requestsList.Count > 0) { ReadWriteRequest[] requestsArray = requestsList.ToArray(); if (OperandsExecuter != null) { OperandsExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Read/Write Operands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } requestsList.Clear(); } } } else if ((rw is ReadDataTables) || (rw is WriteDataTables)) { ReadWriteRequest[] requestsArray; if (requestsList.Count > 0) { requestsArray = requestsList.ToArray(); if (OperandsExecuter != null) { OperandsExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Read/Write Operands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } requestsList.Clear(); } requestsArray = new ReadWriteRequest[] { rw }; if (DataTablesExecuter != null) { DataTablesExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Read/Write Data Tables", ComDriveExceptions.ComDriveException.UnsupportedCommand); } } else if (rw is BinaryRequest) { ReadWriteRequest[] requestsArray; if (requestsList.Count > 0) { requestsArray = requestsList.ToArray(); if (OperandsExecuter != null) { OperandsExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Read/Write Operands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } requestsList.Clear(); } requestsArray = new ReadWriteRequest[] { rw }; BinaryRequest br = rw as BinaryRequest; switch (br.CommandCode) { case 0x1: //Read Ram/Flash case 0x41: //Write Ram/Flash case 62: //Set Password case 0x2: //verify password case 0x9: //Download Start case 0x45: //Download End case 0xA: //Erase Flash case 0x7: //Wait for flash idle case 0xB: //Blind mode case 0x13: //UnBlind mode case 0xF: //Put PLC in state (Preebot, boot, OS Stop, OS Run) case 0xC: //Get PLC Name if (BasicBinaryExecuter != null) { BasicBinaryExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Basic Binary commands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } break; default: if (BinaryExecuter != null) { BinaryExecuter.PerformReadWrite(ref requestsArray, parentID.ToString(), suppressEthernetHeader); } else { throw new ComDriveExceptions( "The PLC or the state the PLC is in does not support Binary Commands", ComDriveExceptions.ComDriveException.UnsupportedCommand); } break; } } } } catch (Exception ex) { ComDriveExceptions comDriveException = ex as ComDriveExceptions; if (comDriveException != null) { if ((comDriveException.ErrorCode == ComDriveExceptions.ComDriveException.AbortedByUser) || m_BreakFlag) { throw; } else if (m_BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } else { throw; } } else if (m_BreakFlag) { throw new ComDriveExceptions("Request aborted by user", ComDriveExceptions.ComDriveException.AbortedByUser); } else { throw; } } finally { lock (objectLocker) { m_BreakFlagCount--; } System.Diagnostics.Debug.Print("Exiting Read Write. Count: " + m_BreakFlagCount.ToString()); ComDriverLogger.LogReadWriteRequest(DateTime.Now, m_channel.GetLoggerChannelText(), values, MessageDirection.Received, parentID.ToString()); } }