private void Endpoint_OnCFXMessageReceived(AmqpChannelAddress source, CFXEnvelope message) { if (evt != null) { evt.Set(); } }
private void btnSend_Click(object sender, EventArgs e) { CFXEnvelope msg; if (currentState == ResourceState.Off) { msg = new CFXEnvelope(new StationStateChanged() { NewState = ResourceState.On, OldState = currentState, OldStateDuration = DateTime.Now - lastStateChange, }); } else { msg = new CFXEnvelope(new StationStateChanged() { NewState = ResourceState.Off, OldState = currentState, OldStateDuration = DateTime.Now - lastStateChange, }); } lastStateChange = msg.TimeStamp; currentState = (msg.MessageBody as StationStateChanged).NewState; theEndpoint.Publish(msg); }
public static Message MessageFromEnvelope(CFXEnvelope env, bool compressed = false) { byte[] msgData = env.ToBytes(); if (compressed) { msgData = Compress(msgData); } Message msg = new Message(msgData); msg.Properties = new Amqp.Framing.Properties { MessageId = env.UniqueID.ToString(), CreationTime = env.TimeStamp }; msg.Header = new Amqp.Framing.Header() { Durable = AmqpCFXEndpoint.DurableMessages.Value }; if (compressed) { msg.Properties.ContentEncoding = "CFX-COMPRESSED"; } return(msg); }
private void FillSource(CFXEnvelope env) { if (env.Source == null) { env.Source = this.CFXHandle; } }
public bool Enqueue(CFXEnvelope obj) { bool result = false; lock (syncObject) { try { obj.Transmitted = false; if (dataWriter != null) { obj.WriteRecord(dataWriter); dataWriter.BaseStream.Seek(8, SeekOrigin.Begin); int cacheSize = dataReader.ReadInt32(); int curCount = cacheSize + 1; dataWriter.BaseStream.Seek(8, SeekOrigin.Begin); dataWriter.Write(curCount); dataWriter.BaseStream.Seek(0, SeekOrigin.End); dataWriter.Flush(); } queue.Add(obj); result = true; } catch (Exception e) { AppLog.Error(e); } } return(result); }
private void Listener_OnCFXMessageReceived(AmqpChannelAddress source, CFXEnvelope message) { if (testEnv != null && testEnv.UniqueID == message.UniqueID && evt != null) { evt.Set(); } }
protected void Fire_OnMessageReceivedFromListener(string TargetAddress, CFXEnvelope message) { if (OnMessageReceivedFromListener != null) { OnMessageReceivedFromListener(TargetAddress, message); } }
void IRequestProcessor.Process(RequestContext requestContext) { var task = Task.Run(() => { CFXEnvelope request = AmqpUtilities.EnvelopeFromMessage(requestContext.Message); CFXEnvelope response = processor.Fire_OnRequestReceived(request); if (response != null) { response.Source = processor.CFXHandle; response.Target = request.Source; response.RequestID = request.RequestID; requestContext.Complete(AmqpUtilities.MessageFromEnvelope(response)); } else { requestContext.Complete(AmqpUtilities.MessageFromEnvelope(new CFXEnvelope(new CFX.NotSupportedResponse()) { Source = processor.CFXHandle, Target = request.Source, RequestID = request.RequestID })); } }); Task.WaitAll(new Task[] { task }); }
public static List <CFXEnvelope> EnvelopesFromMessage(Message msg) { if (msg.Body is byte[]) { byte[] msgData = msg.Body as byte[]; if (msg.Properties?.ContentEncoding == "CFX-COMPRESSED") { msgData = Decompress(msgData); } List <CFXEnvelope> results; string jsonData = Encoding.UTF8.GetString(msgData); if (IsMessageList(jsonData)) { results = CFXEnvelope.FromJsonList(jsonData); } else { results = new List <CFXEnvelope>(new CFXEnvelope [] { CFXEnvelope.FromJson(jsonData) }); } return(results); } throw new ArgumentException("AMQP Message Body does not contain a valid CFX Envelope"); }
private async Task DoTests(bool auth, bool sec) { InitializeTest(auth, sec); // Publish basic EndpointConnected message and ensure receipt by listener EndpointConnected msg = new EndpointConnected() { CFXHandle = TestSettings.ClientHandle }; FireAndWait(msg); // Send Request/Reponse pattern command, and ensure response CFXEnvelope req = new CFXEnvelope(new AreYouThereRequest() { CFXHandle = listener.CFXHandle }); req.Source = endpoint.CFXHandle; req.Target = listener.CFXHandle; CFXEnvelope resp = endpoint.ExecuteRequest(listener.RequestUri.ToString(), req); Assert.IsTrue(resp != null, "Response is null"); Assert.IsTrue(resp.MessageBody is AreYouThereResponse, "Response is not AreYouThereReponse"); Assert.IsTrue(resp.Source == listener.CFXHandle, "Bad response Source handle"); Assert.IsTrue(resp.Target == endpoint.CFXHandle, "Bad response Target handle"); await RunAsyncRequest(); }
private void btnRequest_Click(object sender, EventArgs e) { CFXEnvelope request = new CFXEnvelope("CFX.Sensor.Identification.IdentifyUnitsRequest"); request.Source = CFXHandle; request.Target = reqHandle.Text; string target = reqUri.Text; CFXEnvelope response = null; try { response = theEndpoint.ExecuteRequest(target, request); } catch (Exception ex) { lstResults.Items.Insert(0, "Exception during request process: " + ex.Message); } if (response != null) { response.ToJson().Split(new string[] { "\r\n" }, StringSplitOptions.None).Reverse().ToList().ForEach(s => lstResults.Items.Insert(0, s)); } }
/// <summary> /// Performs a direct, point-to-point request/response transaction with another CFX Endpoint. /// </summary> /// <param name="targetUri">The network address of the Endpoint to which the request will be sent. /// May use amqp:// or amqps:// topic (amqps for secure communications). /// May also include user information (for authentication), as well as a custom TCP port. /// </param> /// <param name="request">A CFX envelope containing the request.</param> /// <returns>A CFX envelope containing the response from the Endpoint.</returns> public CFXEnvelope ExecuteRequest(string targetUri, CFXEnvelope request) { return(ExecuteRequestAsync(targetUri, request) .ConfigureAwait(false) .GetAwaiter() .GetResult()); }
private void Listener_OnCFXMessageReceivedFromListener(string targetAddress, CFXEnvelope message) { if (evt != null) { evt.Set(); } }
private void MakeRequest(CFXEnvelope env) { CFXEnvelope response = null; try { response = MyEndpoint.ExecuteRequest(FactoryLogixMESEndpointUri, env); } catch (Exception ex) { AddToResults($"ERROR OCCURRED MAKING REQUEST TO {FactoryLogixMESEndpointUri}, handle {FactoryLogixMESEndpointHandle}.\nERROR MESSAGE: {ex.Message} \n{ex.StackTrace}"); } if (response.MessageBody is NotSupportedResponse) { NotSupportedResponse r = response.MessageBody as NotSupportedResponse; AddToResults($"NOT SUPPORTED RESPONSE: {r.RequestResult.ResultCode.ToString()}.\n{r.RequestResult.Message}"); } else if (response.MessageBody is ValidateUnitsResponse) { ValidateUnitsResponse r = response.MessageBody as ValidateUnitsResponse; if (r.Result.Result != StatusResult.Success) { AddToResults($"ERROR OCCURRED PROCESSING VALIDATATION REQUEST: {r.PrimaryResult.Result.ToString()}.\n{r.PrimaryResult.Message}"); } else { AddToResults($"VALIDATATION RESULT RECEIVED: {r.PrimaryResult.Result.ToString()}.\n{r.PrimaryResult.Message}"); } } else { AddToResults($"UNEXPLAINED RESPONSE: {response.MessageName}\n{response.ToJson(true)}"); } }
private void SendValidationRequest() { if (!IsOpen) { return; } // Create a request to ask the MES system (FactoryLogix) to validate a production unit (given its barcode) // Specify UnitRouteValidation (unit is at the correct step in the overall process) // and UnitStatusValidation (unit has not been failed, and is ok to be processed). // Unit with barcode TESTUNIT1000 has been initialized in FactoryLogix at the laser marker, but has not // yet been processed at stencil printer, etc. So, it will fail if validated at any station other than // the stencil printer (the next step is stencil printing). CFXEnvelope env = new CFXEnvelope() { Source = MyEndpoint.CFXHandle, Target = FactoryLogixMESEndpointHandle, MessageBody = new ValidateUnitsRequest() { PrimaryIdentifier = "TESTUNIT1000", Validations = new List <ValidationType>(new ValidationType [] { ValidationType.UnitRouteValidation, ValidationType.UnitStatusValidation }) } }; // BE SURE to specify yourself as the Source, and also // to specify the FactoryLogix CFX handle as the Target. env.Source = MyCFXHandle; env.Target = FactoryLogixMESEndpointHandle; MakeRequest(env); // Create a second request to ask the MES system (FactoryLogix) to validate // a different barcode. This barcode has already been successfully processed // through the whole SMT line, so it will pass validation as any station in SMT. env = new CFXEnvelope() { Source = MyEndpoint.CFXHandle, Target = FactoryLogixMESEndpointHandle, MessageBody = new ValidateUnitsRequest() { PrimaryIdentifier = "TESTUNIT1001", Validations = new List <ValidationType>(new ValidationType[] { ValidationType.UnitRouteValidation, ValidationType.UnitStatusValidation }) } }; // BE SURE to specify yourself as the Source, and also // to specify the FactoryLogix CFX handle as the Target. env.Source = MyCFXHandle; env.Target = FactoryLogixMESEndpointHandle; MakeRequest(env); }
/// <summary> /// Converts multiple CFXEnvelope(s) into a single AMQP message /// </summary> /// <param name="envelopes">An array of CFX envelopes containing CFX messages</param> /// <param name="codec">The CODEC to be used</param> /// <param name="subjectFormat">The subject format to be applied. If null, default is used.</param> /// <returns>An AMQP message</returns> public static Message MessageFromEnvelopes(CFXEnvelope [] envelopes, CFXCodec codec = CFXCodec.raw, string subjectFormat = null) { if (envelopes.Length < 1) { return(null); } else if (envelopes.Length == 1) { return(MessageFromEnvelope(envelopes.First(), codec, subjectFormat)); } CFXEnvelope env = envelopes.First(); List <CFXEnvelope> container = new List <CFXEnvelope>(envelopes); byte[] msgData = Encoding.UTF8.GetBytes(CFXJsonSerializer.SerializeObject(container)); msgData = Encode(msgData, codec); Message msg = new Message(); msg.BodySection = new Data() { Binary = msgData }; SetHeaders(msg, env, codec, subjectFormat); return(msg); }
public static Message MessageFromEnvelope(CFXEnvelope env, CFXCodec codec = CFXCodec.raw) { byte[] msgData = Encode(env.ToBytes(), codec); Message msg = new Message(msgData); msg.Properties = new Amqp.Framing.Properties { MessageId = env.UniqueID.ToString(), CreationTime = env.TimeStamp, ContentType = "application/json; charset=\"utf-8\"" }; if (codec == CFXCodec.gzip) { msg.Properties.ContentEncoding = "gzip"; } msg.Header = new Amqp.Framing.Header() { Durable = AmqpCFXEndpoint.DurableMessages.Value }; return(msg); }
public static List <CFXEnvelope> EnvelopesFromMessage(Message msg) { if (msg.Body is byte[]) { byte[] msgData = msg.Body as byte[]; CFXCodec codec = CFXCodec.raw; if (string.Compare(msg.Properties.ContentEncoding, "gzip", true) == 0) { codec = CFXCodec.gzip; } msgData = Decode(msgData, codec); List <CFXEnvelope> results; string jsonData = Encoding.UTF8.GetString(msgData); if (IsMessageList(jsonData)) { results = CFXEnvelope.FromJsonList(jsonData); } else { results = new List <CFXEnvelope>(new CFXEnvelope [] { CFXEnvelope.FromJson(jsonData) }); } return(results); } throw new ArgumentException("AMQP Message Body does not contain a valid CFX Envelope"); }
private CFXEnvelope RequestProcessor_OnRequestReceived(CFXEnvelope request) { if (OnRequestReceived != null) { return(OnRequestReceived(request)); } return(null); }
public void Publish(CFXEnvelope env) { FillSource(env); foreach (AmqpConnection channel in channels.Values) { channel.Publish(env); } }
public void Publish(CFXMessage msg) { CFXEnvelope env = new CFXEnvelope(); env.MessageBody = msg; FillSource(env); Publish(env); }
protected CFXEnvelope Fire_OnRequestReceived(CFXEnvelope request) { if (OnRequestReceived != null) { return(OnRequestReceived(request)); } return(null); }
public void Publish(CFXEnvelope env, string replyTo = null) { EnsureConnection(); foreach (AmqpSenderLink sender in links.OfType <AmqpSenderLink>()) { sender.Publish(new CFXEnvelope[] { env }); } }
private bool ReadData() { bool result = false; lock (syncObject) { try { queue.Clear(); if (dataReader == null) { return(false); } if (dataReader.BaseStream.Length < 1) { return(true); } dataReader.BaseStream.Seek(0, SeekOrigin.Begin); // Read the File Signature uint sig = dataReader.ReadUInt32(); if (sig == this.fileSignature) { // Read the Version Tag fileVersion = dataReader.ReadUInt32(); // Read the Cache Size int cacheSize = dataReader.ReadInt32(); for (int i = 0; i < cacheSize; i++) { CFXEnvelope rec = CFXEnvelope.ReadRecord(dataReader); if (rec != null && !rec.Transmitted) { if (!rec.Transmitted) { queue.Add(rec); } } } result = true; } } catch (Exception e) { AppLog.Error(e); } } if (!result) { queue.Clear(); } return(result); }
public static Message MessageFromEnvelope(CFXEnvelope env, CFXCodec codec = CFXCodec.raw, string subjectFormat = null) { byte[] msgData = Encode(env.ToBytes(), codec); Message msg = new Message(msgData); SetHeaders(msg, env, codec, subjectFormat); return(msg); }
public void PublishToChannel(CFXEnvelope env, string address) { EnsureConnection(); AmqpSenderLink link = links.OfType <AmqpSenderLink>().Where(l => l.Address == address).FirstOrDefault(); if (link == null) { throw new ArgumentException("There is no active publish channel that matches the specified channel address", "address"); } link.Publish(new CFXEnvelope[] { env }); }
private void FireAndWait(CFXMessage msg, int timeout = 60000) { using (evt = new System.Threading.AutoResetEvent(false)) { CFXEnvelope env = CFXEnvelope.FromCFXMessage(msg); testEnv = env; endpoint.Publish(env); if (!evt.WaitOne(timeout)) { throw new TimeoutException("The message was not received by listener. Timeout"); } } }
public void PublishMany(IEnumerable <CFXMessage> msgs) { List <CFXEnvelope> envelopes = new List <CFXEnvelope>(); foreach (CFXMessage msg in msgs) { CFXEnvelope env = new CFXEnvelope(); env.MessageBody = msg; FillSource(env); envelopes.Add(env); } PublishMany(envelopes); }
private void btnSendMsg_Click(object sender, EventArgs e) { if (!theEndpoint.IsOpen) { return; } List <CFXEnvelope> messages = new List <CFXEnvelope>(); //WorkStarted ws = new WorkStarted(); //ws.TransactionID = Guid.NewGuid(); //ws.Lane = "Lane1"; //ws.Units.Add(new UnitPosition() { UnitIdentifier = "11122456", PositionNumber = 1, PositionName = "1" }); //messages.Add(CFXEnvelope.FromCFXMessage(ws)); //WorkCompleted wc = new WorkCompleted(); //wc.TransactionID = ws.TransactionID; //wc.Result = WorkResult.Failed; //messages.Add(CFXEnvelope.FromCFXMessage(wc)); ResourceState[] states = new ResourceState [] { ResourceState.SDT_Setup, ResourceState.PRD_RegularWork, ResourceState.SBY_NoProduct }; ResourceState newState = lastState; Random r = new Random(); while (newState == lastState) { newState = states[r.Next(0, 2)]; } CFXEnvelope env = new CFXEnvelope(new StationStateChanged() { NewState = newState, OldState = lastState, OldStateDuration = DateTime.Now - lastStateChange }); messages.Add(env); lastState = (env.MessageBody as StationStateChanged).NewState; lastStateChange = DateTime.Now; //theEndpoint.Publish(ws); theEndpoint.PublishMany(messages); }
public static CFXEnvelope EnvelopeFromMessage(Message msg) { if (msg.Body is byte[]) { byte[] msgData = msg.Body as byte[]; if (msg.Properties?.ContentEncoding == "CFX-COMPRESSED") { msgData = Decompress(msgData); } return(CFXEnvelope.FromBytes(msgData)); } throw new ArgumentException("AMQP Message Body does not contain a valid CFX Envelope"); }