public static NamedPipeServerStream Create(String pipeName, PipeDirection direction, PipeSecurity security, Func <PipeInfo, int> OnClientConnect, int maxServerInstances = 1, int inBufferSize = DEFAULT_BUFFER_IN, int outBufferSize = DEFAULT_BUFFER_OUT) { NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipeName, direction, maxServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, inBufferSize, outBufferSize, security); if (pipeServer != null) { var pipeInfo = new PipeInfo(); pipeInfo.Name = pipeName; pipeInfo.Direction = direction; pipeInfo.Security = security; pipeInfo.Stream = pipeServer; pipeInfo.OnClientConnect = OnClientConnect; pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForClientConnection), pipeInfo); } return(pipeServer); }
public void ReleaseUnheldLock() { var redisTaskFunnel = CreateRedisTaskFunnel(); var msgValue = Guid.NewGuid().ToByteArray(); var pipeInfo = PipeInfo.Create("unheld", "a"); redisTaskFunnel.DestroyChildPipe(pipeInfo); var redisPipeValue = new RedisPipeValue(pipeInfo, msgValue, "asdf", true); //indicating a success does nothing if the hash doesn't exist redisTaskFunnel.AfterExecute(redisPipeValue, true); var readMessage = redisTaskFunnel.TryReadMessageBatch(false, pipeInfo, TimeSpan.FromMinutes(1), 1); readMessage.RedisValues.Should().BeEmpty(); //indicating a failure resubmits the message redisTaskFunnel.AfterExecute(redisPipeValue, false); readMessage = redisTaskFunnel.TryReadMessageBatch(false, pipeInfo, TimeSpan.FromMinutes(1), 1); readMessage.Should().NotBeNull(); var mesg = readMessage.RedisPipeValues.FirstOrDefault(); mesg?.Value.Should().BeEquivalentTo(msgValue); redisTaskFunnel.DestroyChildPipe(pipeInfo); redisTaskFunnel.AfterExecuteBatch(readMessage); }
private void ExecuteExisting(TimeSpan lockExpiry) { var sourcePipes = GetSourcePipes(); var tasks = new List <Task>(); foreach (var sourcePipe in sourcePipes) { foreach (var sourcePipeChild in sourcePipe.Value) { var pipeInfo = PipeInfo.Create(sourcePipe.Key, sourcePipeChild); //capture the number of reads write now to ignore: // - new events that arrive // - events that fail and are re-added. var maxReads = _taskFunnel.GetListLength(pipeInfo); var batchSize = 2; var messageBatch = _taskFunnel.TryReadMessageBatch(true, pipeInfo, lockExpiry, batchSize); //this is still an early implementation. The objectives are: // - speed (obviously) // - consistent number of active tasks. // - batches released as soon as the last one completes while (messageBatch?.HoldingList != null) { var taskExecutor = _taskExecutors[sourcePipe.Key]; ExecuteBatch(taskExecutor, pipeInfo, messageBatch); messageBatch = _taskFunnel.TryReadMessageBatch(true, pipeInfo, lockExpiry, batchSize); } } } }
private static void SendReadAndRelease(IRedisTaskFunnel redisTaskFunnel, string parentPipeName, string childPipeName) { var sent = redisTaskFunnel.TrySendMessage(parentPipeName, childPipeName, new byte[1] { (byte)'a' }, Int32.MaxValue, TimeSpan.FromMinutes(1)); sent.sent.Should().BeTrue(); sent.clients.Should().BeFalse(); var read = redisTaskFunnel.TryReadMessage <byte[]>(true, parentPipeName, childPipeName, TimeSpan.FromSeconds(1)); read.Should().NotBeNull(); read.LockValue.Should().NotBeNull(); read.Value.Should().NotBeNull(); //try to release the lock without the correct key var redisPipeValue = new RedisPipeValue <byte[]>(PipeInfo.Create(parentPipeName, childPipeName), "", Guid.NewGuid().ToString(), true); var badExtend = redisTaskFunnel.LockExtend(redisPipeValue, TimeSpan.FromSeconds(1)); badExtend.Should().BeFalse(); Action badRelease = () => redisTaskFunnel.LockRelease(redisPipeValue, true); badRelease.Should().Throw <ApplicationException>(); var extended = redisTaskFunnel.LockExtend(read, TimeSpan.FromSeconds(1)); extended.Should().BeTrue(); var released = redisTaskFunnel.LockRelease(read, true); released.Should().BeTrue(); }
public long GetListLength(PipeInfo pipeInfo) { var db = _redis.GetDatabase(); var length = db.ListLength(pipeInfo.PipePath); return(length); }
public void ReadFromNonExistantOrEmptyQueue() { var redisTaskFunnel = CreateRedisTaskFunnel(); var read = redisTaskFunnel.TryReadMessageBatch(true, PipeInfo.Create("emptyqueue", "emptypipe"), TimeSpan.FromSeconds(10), 1); read.HoldingList.Should().BeNull(); read.RedisValues.Should().BeEmpty(); }
public void ReleaseLockExtend() { var redisTaskFunnel = CreateRedisTaskFunnel(); var lockKey = Guid.NewGuid().ToString(); var redisPipeValue = new RedisPipeValue <byte[]>(PipeInfo.Create("lock", "a"), lockKey, "asdf", true); var extended = redisTaskFunnel.LockExtend(redisPipeValue, TimeSpan.FromMinutes(1)); extended.Should().BeFalse(); }
private void ShowContent(string name) { this.stackpanel.Children.Clear(); if (mPipeInfo == null) { mPipeInfo = new PipeInfo(name); } this.stackpanel.Children.Add(mPipeInfo); }
private void ShowContent(int id) { this.stackpanel.Children.Clear(); if (mPipeInfo == null) { mPipeInfo = new PipeInfo(id); } this.stackpanel.Children.Add(mPipeInfo); }
public StockInfo() { this.pinfo = new PipeInfo(); this.pipeName = new List <string>(); this.pipeSize = new List <string>(); this.quantity = new List <string>(); this.totalPrice = new List <string>(); this.pricePerunit = new List <string>(); }
public void ReleaseUnheldLock() { var redisTaskFunnel = CreateRedisTaskFunnel(); var lockKey = Guid.NewGuid().ToString(); var redisPipeValue = new RedisPipeValue <byte[]>(PipeInfo.Create("unheld", "a"), lockKey, "asdf", true); Action act = () => redisTaskFunnel.LockRelease(redisPipeValue, true); act.Should().Throw <ApplicationException>(); }
public void ReleaseLockExtend() { var redisTaskFunnel = CreateRedisTaskFunnel(); var lockKey = Guid.NewGuid().ToString(); var pipeInfo = PipeInfo.Create("lock", "a"); var redisPipeValue = new RedisPipeValue(pipeInfo, lockKey, "asdf", true); var extended = redisTaskFunnel.RetainHoldingList(redisPipeValue, TimeSpan.FromMinutes(1)); extended.Should().BeFalse(); redisTaskFunnel.DestroyChildPipe(pipeInfo); }
static void WaitForClientConnection(IAsyncResult result) { PipeInfo pipeInfo = (PipeInfo)result.AsyncState; NamedPipeServerStream pipeServer = (NamedPipeServerStream)pipeInfo.Stream; int ret = pipeInfo.OnClientConnect != null ? WAIT_FOR_NEXT_CONNECTION : CLOSE_PIPE; // End waiting for the connection try { pipeServer.EndWaitForConnection(result); //do delegate function here if (pipeInfo.OnClientConnect != null && pipeServer.IsConnected) { ret = pipeInfo.OnClientConnect(pipeInfo); } } catch (Exception) { ret = CLOSE_PIPE; } switch (ret) { case CLOSE_PIPE: pipeServer.Close(); pipeServer.Dispose(); pipeServer = null; break; case WAIT_FOR_NEXT_CONNECTION: if (pipeServer.IsConnected) { try { pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForClientConnection), pipeInfo); } catch (IOException) { pipeServer = Create(pipeInfo.Name, pipeInfo.Direction, pipeInfo.Security, pipeInfo.OnClientConnect); } } else { pipeServer.Close(); pipeServer.Dispose(); pipeServer = null; pipeServer = Create(pipeInfo.Name, pipeInfo.Direction, pipeInfo.Security, pipeInfo.OnClientConnect); } break; } //end switch }
public void SplitPipe(int pipe, long delay1, long delay2, out int mid, out int left, out int right) { var pi = _pipes[pipe]; Debug.Assert(pi.delay == delay1 + delay2); int mididx = _pipeInSignals.Count; mid = mididx; object initval = _pipeInSignals[pi.source].InitialValueObject; int icridx = _icrCurSignals.Count; var curSignal = _binder.GetSignal(EPortUsage.Default, "fifo" + icridx + "_in", null, initval); _pipeInSignals.Add(curSignal); _icrCurSignals.Add(mid); _preds.Add(new List <int>()); _succs.Add(new List <int>()); var piLeft = new PipeInfo() { source = pi.source, sink = mididx, delay = delay1 }; var piRight = new PipeInfo() { source = mididx, sink = pi.sink, delay = delay2 }; _pipes[pipe] = piLeft; left = pipe; int rightidx = _pipes.Count; right = rightidx; _pipes.Add(piRight); _preds[pi.sink].Remove(pipe); _preds[mididx].Add(pipe); _succs[mididx].Add(rightidx); _preds[pi.sink].Add(rightidx); var rmap = new Dictionary <long, ResInfo>(); _resTable.Add(rmap); foreach (var kvp in _resTable[pipe]) { rmap[kvp.Key + delay1] = kvp.Value; } }
public int AddPipe(int source, int sink, long delay) { // Basic check against cycles. "Obvious" cycles (1/2 edges) only! bool isCycle = source == sink || _preds[source].Select(p => _pipes[p].source).Contains(sink) || _succs[sink].Select(p => _pipes[p].sink).Contains(source); //Debug.Assert(source != sink); //Debug.Assert(!_preds[source].Select(p => _pipes[p].source).Contains(sink)); //Debug.Assert(!_succs[sink].Select(p => _pipes[p].sink).Contains(source)); if (isCycle) { string before = GetInterconnectGraphForDotty(); File.WriteAllText("SlimMuxBugReport_before.dotty", before); } // Disallow redundant pipes of delay 0 Debug.Assert(delay > 0 || _pipes.All(p => p.source != source || p.sink != sink || p.delay != delay)); var pi = new PipeInfo() { source = source, sink = sink, delay = delay }; int idx = _pipes.Count; _pipes.Add(pi); _preds[sink].Add(idx); _succs[source].Add(idx); _resTable.Add(new Dictionary <long, ResInfo>()); if (isCycle) { string after = GetInterconnectGraphForDotty(); File.WriteAllText("SlimMuxBugReport_after.dotty", after); // roll back _pipes.RemoveAt(_pipes.Count - 1); _preds[sink].RemoveAt(_preds[sink].Count - 1); _succs[source].RemoveAt(_succs[source].Count - 1); _resTable.RemoveAt(_resTable.Count - 1); Debug.Fail("Cycle detected"); } return(idx); }
private void BaseInfo(object sender, RoutedEventArgs e) //管道基本数据 { this.stackpanel.Children.Clear(); if (mPipeInfo == null) { if (mPipeName != null) { mPipeInfo = new PipeInfo(mPipeName); } else { mPipeInfo = new PipeInfo(mId); } } this.stackpanel.Children.Add(mPipeInfo); }
public void ListenForPipeEvents(/*IEnumerable<string> parentPipeNames,*/ BlockingCollection <PipeInfo> pipeInfos) { var sub = _redis.GetSubscriber(); //foreach (var parentPipeName in parentPipeNames){} sub.Subscribe(RedisTaskMultiplexorConstants.RedisTaskMultiplexorBroadcastPrefix, (channel, value) => { var eventObject = JObject.Parse(value); //$"{{\"type\":\"new\",\"parent\":\"{parentPipeName}\",\"child\":\"{childPipeName}\"}}"); var parent = eventObject["parent"].ToString(); var child = eventObject["child"].ToString(); var eventPipeInfo = PipeInfo.Create(parent, child); pipeInfos.Add(eventPipeInfo); }); }
public static void OutputProcessing() { ready_count++; // Wait for pipe to be created SystemCalls.SleepThread(SystemCalls.IndefiniteSleepThread); PipeInfo CurrentPipeInfo = ((PipeInfo)ConnectedPipes[CurrentPipeIdx]); while (!Terminating) { try { bool AltPressed = Keyboard.Default.AltPressed; uint Scancode; bool GotScancode = Keyboard.Default.GetScancode(out Scancode); if (GotScancode) { KeyboardKey Key; if (Keyboard.Default.GetKeyValue(Scancode, out Key)) { if (AltPressed && Key == KeyboardKey.Tab) { CurrentPipeIdx++; if (CurrentPipeIdx >= ConnectedPipes.Count) { CurrentPipeIdx = 0; } CurrentPipeInfo = ((PipeInfo)ConnectedPipes[CurrentPipeIdx]); CurrentPipeIndex_Changed = true; } else { SystemCalls.SendMessage(((PipeInfo)ConnectedPipes[CurrentPipeIdx]).StdOut.OutProcessId, Scancode, 0); } } } } catch { BasicConsole.WriteLine("WM > Error during output processing!"); BasicConsole.WriteLine(ExceptionMethods.CurrentException.Message); } } }
public void TestSendAndRecover() { var redisTaskFunnel = CreateRedisTaskFunnel(); var parentPipeName = "SendAndRecover"; var childPipeName = Guid.NewGuid().ToString(); //send 2 messages var messageBody1 = "body1"; var sent = redisTaskFunnel.TrySendMessage(parentPipeName, childPipeName, messageBody1, Int32.MaxValue, TimeSpan.FromMinutes(1)); sent.sent.Should().BeTrue(); var messageBody2 = "body2"; sent = redisTaskFunnel.TrySendMessage(parentPipeName, childPipeName, messageBody2, Int32.MaxValue, TimeSpan.FromMinutes(1)); sent.sent.Should().BeTrue(); //sent.clients.Should().BeFalse(); //read the batch var pipeInfo = PipeInfo.Create(parentPipeName, childPipeName); var read = redisTaskFunnel.TryReadMessageBatch(true, pipeInfo, TimeSpan.FromSeconds(1), 2); read.Should().NotBeNull(); read.HoldingList.Should().NotBeNull(); read.RedisValues.Count.Should().Be(2); read.RedisValues.First().HasValue.Should().BeTrue(); read.RedisValues.Skip(1).First().HasValue.Should().BeTrue(); read.RedisPipeValues.Any(a => a.ValueString == messageBody1).Should().BeTrue(); read.RedisPipeValues.Any(a => a.ValueString == messageBody2).Should().BeTrue(); //recover batch (redeliver its messages) redisTaskFunnel.RecoverBatch(read.HoldingList).Should().BeTrue(); read = redisTaskFunnel.TryReadMessageBatch(true, pipeInfo, TimeSpan.FromSeconds(1), 2); read.Should().NotBeNull(); read.HoldingList.Should().NotBeNull(); read.RedisValues.Count.Should().Be(2); read.RedisValues.First().HasValue.Should().BeTrue(); read.RedisValues.Skip(1).First().HasValue.Should().BeTrue(); var actualRedisPipeValue = read.RedisPipeValues.First(); read.RedisPipeValues.Any(a => a.ValueString == messageBody1).Should().BeTrue(); read.RedisPipeValues.Any(a => a.ValueString == messageBody2).Should().BeTrue(); }
private void ExecuteBatch(ITaskExecutor taskExecutor, PipeInfo pipeInfo, RedisPipeBatch messageBatch) { foreach (var redisMessage in messageBatch.RedisPipeValues) { try { taskExecutor.Execute(pipeInfo, redisMessage); _taskFunnel.AfterExecute(redisMessage, true); } catch (Exception e) { _logger.LogError(e, $"Error handling from {pipeInfo.ParentPipeName}/{pipeInfo.ChildPipeName}"); //this will resubmit the message _taskFunnel.AfterExecute(redisMessage, false); } } _taskFunnel.AfterExecuteBatch(messageBatch); }
private static void SendReadAndRelease(IRedisTaskFunnel redisTaskFunnel, string parentPipeName, string childPipeName) { //send a message var messageBody = "body"; var sent = redisTaskFunnel.TrySendMessage(parentPipeName, childPipeName, messageBody, Int32.MaxValue, TimeSpan.FromMinutes(1)); sent.sent.Should().BeTrue(); //sent.clients.Should().BeFalse(); //read the batch var read = redisTaskFunnel.TryReadMessageBatch(true, PipeInfo.Create(parentPipeName, childPipeName), TimeSpan.FromSeconds(1), 1); read.Should().NotBeNull(); read.HoldingList.Should().NotBeNull(); read.RedisValues.Should().NotBeEmpty(); read.RedisValues.First().HasValue.Should().BeTrue(); var actualRedisPipeValue = read.RedisPipeValues.First(); actualRedisPipeValue.ValueString.Should().Be(messageBody); //try to release the lock without the wrong holdingListName var redisPipeValue = new RedisPipeValue(PipeInfo.Create(parentPipeName, childPipeName), "body", Guid.NewGuid().ToString(), true); var badExtend = redisTaskFunnel.RetainHoldingList(redisPipeValue, TimeSpan.FromSeconds(1)); badExtend.Should().BeFalse(); redisTaskFunnel.AfterExecute(redisPipeValue, true); //retain with the correct name var extended = redisTaskFunnel.RetainHoldingList(read, TimeSpan.FromSeconds(1)); extended.Should().BeTrue(); //complete the message and the batch redisTaskFunnel.AfterExecute(actualRedisPipeValue, true); redisTaskFunnel.AfterExecuteBatch(read); //now check the holding list doesn't exist any more. extended = redisTaskFunnel.RetainHoldingList(read, TimeSpan.FromSeconds(1)); extended.Should().BeFalse(); }
public (bool sent, bool clients) TrySendMessage(string parentPipeName, string childPipeName, object body, int maxListLength = int.MaxValue, TimeSpan?expiry = null) { if (body == null) { throw new ArgumentNullException(nameof(body)); } //will throw ArgumentException is body is not a supported type var redisValue = RedisValue.Unbox(body); var db = _redis.GetDatabase(); var parentInfoPath = CreateParentChildSetPath(parentPipeName); var childPipePath = PipeInfo.Create(parentPipeName, childPipeName); var trans = db.CreateTransaction(); { if (maxListLength < int.MaxValue) { trans.AddCondition(Condition.ListLengthLessThan(childPipePath.PipePath, maxListLength)); } //ensure the name of the new pipe exists for the pipe monitor (before checking list length) db.SetAdd(RedisTaskMultiplexorConstants.PipeNameSetKey, parentPipeName); //add the child to the parents hash set (and update the expiry time on it) db.HashSet(parentInfoPath, childPipeName, DateConverters.ExpiryToTimeString(expiry ?? TimeSpan.FromDays(7))); //add the message to the left of the list, and is later popped from the right. db.ListLeftPush(childPipePath.PipePath, redisValue); } var executed = trans.Execute(); if (!executed) { return(false, false); } var sub = _redis.GetSubscriber(); var listeners = sub.Publish(childPipePath.BroadcastPath, $"{{\"type\":\"new\",\"parent\":\"{parentPipeName}\",\"child\":\"{childPipeName}\"}}"); return(true, listeners > 0); }
private bool IsConnectedToPreviousPipe(PipeInfo currentPipeInfo) { // Update the connection indicator IList<CPipeConnectionPointPair> connectionPointPairList = null; if (!CPipeConnetionUtility.CalcaulateConnection(currentPipeInfo, out connectionPointPairList)) return false; // Make sure each connection pair's distance is in our tolerance double dConnectedTolerance = ApplicationOptions.Instance().ConnectedPipeTolerance; // Unit is M foreach (CPipeConnectionPointPair pair in connectionPointPairList) { if (pair.Distance * IApp.theApp.DataModel.ModelingUnitToMeter > dConnectedTolerance) { return false; } } return true; }
public static void Main() { BasicConsole.WriteLine("Window Manager: Started."); // Initialise heap & GC Hardware.Processes.ProcessManager.CurrentProcess.InitHeap(); // Start thread for calling GC Cleanup method if (SystemCalls.StartThread(GCCleanupTask.Main, out GCThreadId) != SystemCallResults.OK) { BasicConsole.WriteLine("Window Manager: GC thread failed to create!"); } // Initialise connected pipes list ConnectedPipes = new List(); // Start thread for handling background input processing if (SystemCalls.StartThread(InputProcessing, out InputProcessingThreadId) != SystemCallResults.OK) { BasicConsole.WriteLine("Window Manager: InputProcessing thread failed to create!"); } BasicConsole.Write("WM > InputProcessing thread id: "); BasicConsole.WriteLine(InputProcessingThreadId); BasicConsole.Write("WM > Register RegisterPipeOutpoint syscall handler"); SystemCalls.RegisterSyscallHandler(SystemCallNumbers.RegisterPipeOutpoint, SyscallHandler); // Start thread for handling background output processing if (SystemCalls.StartThread(OutputProcessing, out OutputProcessingThreadId) != SystemCallResults.OK) { BasicConsole.WriteLine("Window Manager: OutputProcessing thread failed to create!"); } BasicConsole.WriteLine("WM > Init keyboard"); Keyboard.InitDefault(); BasicConsole.WriteLine("WM > Register IRQ 1 handler"); SystemCalls.RegisterIRQHandler(1, HandleIRQ); BasicConsole.WriteLine("WM > Wait for pipe to be created"); // Wait for pipe to be created ready_count++; SystemCalls.SleepThread(SystemCalls.IndefiniteSleepThread); PipeInfo CurrentPipeInfo = null; while (!Terminating) { try { if (CurrentPipeIdx > -1) { if (CurrentPipeIndex_Changed) { CurrentPipeInfo = ((PipeInfo)ConnectedPipes[CurrentPipeIdx]); CurrentPipeIndex_Changed = false; CurrentPipeInfo.TheConsole.Update(); } CurrentPipeInfo.TheConsole.Write(CurrentPipeInfo.StdOut.Read(false)); } } catch { if (ExceptionMethods.CurrentException is Pipes.Exceptions.RWFailedException) { SystemCalls.SleepThread(50); } else { BasicConsole.WriteLine("WM > Exception running window manager."); BasicConsole.WriteLine(ExceptionMethods.CurrentException.Message); } } } }
public static void InputProcessing() { ready_count++; while (!Terminating) { //BasicConsole.WriteLine("WM > IP : (0)"); if (!InputProcessingThreadAwake) { SystemCalls.SleepThread(SystemCalls.IndefiniteSleepThread); } InputProcessingThreadAwake = false; BasicConsole.WriteLine("WM > InputProcessing thread running..."); int numOutpoints; SystemCallResults SysCallResult; Pipes.BasicOutpoint.GetNumPipeOutpoints(out numOutpoints, out SysCallResult, Pipes.PipeClasses.Standard, Pipes.PipeSubclasses.Standard_Out); //BasicConsole.WriteLine("WM > IP : (1)"); if (SysCallResult == SystemCallResults.OK && numOutpoints > 0) { //BasicConsole.WriteLine("WM > IP : (2)"); Pipes.PipeOutpointDescriptor[] OutpointDescriptors; Pipes.BasicOutpoint.GetOutpointDescriptors(numOutpoints, out SysCallResult, out OutpointDescriptors, Pipes.PipeClasses.Standard, Pipes.PipeSubclasses.Standard_Out); //BasicConsole.WriteLine("WM > IP : (3)"); if (SysCallResult == SystemCallResults.OK) { //BasicConsole.WriteLine("WM > IP : (4)"); for (int i = 0; i < OutpointDescriptors.Length; i++) { //BasicConsole.WriteLine("WM > IP : (5)"); Pipes.PipeOutpointDescriptor Descriptor = OutpointDescriptors[i]; bool PipeExists = false; for (int j = 0; j < ConnectedPipes.Count; j++) { PipeInfo ExistingPipeInfo = (PipeInfo)ConnectedPipes[j]; if (ExistingPipeInfo.StdOut.OutProcessId == Descriptor.ProcessId) { PipeExists = true; break; } } if (!PipeExists) { try { //BasicConsole.WriteLine("WM > IP : (6)"); PipeInfo NewPipeInfo = new PipeInfo(); NewPipeInfo.StdOut = new Pipes.Standard.StandardInpoint(Descriptor.ProcessId, true); // 2000 ASCII characters = 2000 bytes //BasicConsole.WriteLine("WM > IP : (7)"); ConnectedPipes.Add(NewPipeInfo); if (CurrentPipeIdx == -1) { CurrentPipeIdx = 0; CurrentPipeIndex_Changed = true; SystemCalls.WakeThread(MainThreadId); SystemCalls.WakeThread(OutputProcessingThreadId); } //BasicConsole.WriteLine("WM > IP : (8)"); } catch { BasicConsole.WriteLine("WM > Error creating new pipe!"); BasicConsole.WriteLine(ExceptionMethods.CurrentException.Message); } } } } else { BasicConsole.WriteLine("WM > Couldn't get outpoint descriptors!"); } } else { BasicConsole.WriteLine("WM > Cannot get outpoints!"); } } }
public static extern bool WinUsb_QueryPipe(SafeWinUsbInterfaceHandle interfaceHandle, byte altInterfaceNum, byte pipeIndex, out PipeInfo pipeInfo);
public Task ExecuteAsync(PipeInfo pipeInfo, RedisPipeValue value) { Execute(pipeInfo, value); return(Task.CompletedTask); }
public static void InputProcessing() { ready_count++; while (!Terminating) { if (!InputProcessingThreadAwake) { SystemCalls.SleepThread(SystemCalls.IndefiniteSleepThread); } InputProcessingThreadAwake = false; BasicConsole.WriteLine("WM > InputProcessing thread running..."); int numOutpoints; SystemCallResults SysCallResult; Pipes.BasicOutpoint.GetNumPipeOutpoints(out numOutpoints, out SysCallResult, Pipes.PipeClasses.Standard, Pipes.PipeSubclasses.Standard_Out); if (SysCallResult == SystemCallResults.OK && numOutpoints > 0) { Pipes.PipeOutpointDescriptor[] OutpointDescriptors; Pipes.BasicOutpoint.GetOutpointDescriptors(numOutpoints, out SysCallResult, out OutpointDescriptors, Pipes.PipeClasses.Standard, Pipes.PipeSubclasses.Standard_Out); if (SysCallResult == SystemCallResults.OK) { for (int i = 0; i < OutpointDescriptors.Length; i++) { Pipes.PipeOutpointDescriptor Descriptor = OutpointDescriptors[i]; bool PipeExists = false; for (int j = 0; j < ConnectedPipes.Count; j++) { PipeInfo ExistingPipeInfo = (PipeInfo)ConnectedPipes[j]; if (ExistingPipeInfo.StdOut.OutProcessId == Descriptor.ProcessId) { PipeExists = true; break; } } if(!PipeExists) { try { PipeInfo NewPipeInfo = new PipeInfo(); NewPipeInfo.StdOut = new Pipes.Standard.StandardInpoint(Descriptor.ProcessId, true); // 2000 ASCII characters = 2000 bytes ConnectedPipes.Add(NewPipeInfo); if (CurrentPipeIdx == -1) { CurrentPipeIdx = 0; CurrentPipeIndex_Changed = true; SystemCalls.WakeThread(MainThreadId); SystemCalls.WakeThread(OutputProcessingThreadId); } } catch { BasicConsole.WriteLine("WM > Error creating new pipe!"); BasicConsole.WriteLine(ExceptionMethods.CurrentException.Message); } } } } else { BasicConsole.WriteLine("WM > Couldn't get outpoint descriptors!"); } } else { BasicConsole.WriteLine("WM > Cannot get outpoints!"); } } }
public static EndothelialCell.PipeInfo getGrowthDirection(Vector3 start, Vector3 end) { EndothelialCell.PipeOrientation orientation; Vector3 unitVector; Vector3 direction = end - start; float absX = Math.Abs(direction.X); float absY = Math.Abs(direction.Y); float absZ = Math.Abs(direction.Z); if (absX > absY) { if (absX > absZ) // if X is biggest { if (direction.X == absX) { unitVector = Vector3.Right; orientation = PipeOrientation.posX; } else { unitVector = Vector3.Left; orientation = PipeOrientation.negX; } } else // if Z is biggest { if (direction.Z == absZ) { unitVector = Vector3.Backward; orientation = PipeOrientation.posZ; } else { unitVector = Vector3.Forward; orientation = PipeOrientation.negZ; } } } else { if (absY > absZ) // if Y is biggest { if (direction.Y == absY) { unitVector = Vector3.Up; orientation = PipeOrientation.posY; } else { unitVector = Vector3.Down; orientation = PipeOrientation.negY; } } else // if Z is biggest { if (direction.Z == absZ) { unitVector = Vector3.Backward; orientation = PipeOrientation.posZ; } else { unitVector = Vector3.Forward; orientation = PipeOrientation.negZ; } } } PipeInfo newPipeInfo = new PipeInfo(unitVector, orientation); return newPipeInfo; }
public void DestroyChildPipe(PipeInfo pipeInfo) { var db = _redis.GetDatabase(); db.KeyDelete(pipeInfo.PipePath); }
public void DriveModel(PipeInfo queryResult) { // Assert Valid if (queryResult == null) return; // Save the current pipe info m_currentPipeInfo = queryResult; // The main logic to drive the model should be as below // Get the working in progress pipe id. // Drive previous pipe to its location and remove the other components // Drive the working in progress pipe to its location int iCurrentPipeIndex = m_currentPipeInfo.PipeId; for (int iPipeIndex = IApp.theApp.DataModel.PipeModels.Count; iPipeIndex >= 1; --iPipeIndex) { CPipeModel pipeModel = IApp.theApp.DataModel.PipeModels[iPipeIndex - 1]; if (pipeModel == null) continue; if (iPipeIndex > iCurrentPipeIndex) { pipeModel.Status = PipeStatus.eNotStartedYet; } else if (iPipeIndex == iCurrentPipeIndex) { pipeModel.Status = PipeStatus.eWorkingInProgess; // Here, we should pay more attention that if the m_currentPipeInfo is the last one for this pipe model // Also, the distance between the connection point should be taken into account if ((pipeModel.FinalPipeInfo != null && pipeModel.FinalPipeInfo.Time == m_currentPipeInfo.Time/*time is not enough*/) || IsConnectedToPreviousPipe(m_currentPipeInfo)) { // Cache the final pipe info for the finished pipe CacheFinalPipeInfoForFinishedPipe(pipeModel, iPipeIndex); bool bLastPipe = (iCurrentPipeIndex == IApp.theApp.DataModel.PipeModels.Count); if (bLastPipe) { pipeModel.Status = PipeStatus.eFill; } else { // Mark the status as fill and its previous model pipeModel.Status = PipeStatus.eDone; } //if (IApp.theApp.DataModel.PipeModels.Count > 1 && iPipeIndex > 2) //{ // CPipeModel previousModel = IApp.theApp.DataModel.PipeModels[iPipeIndex - 2]; // if (null != previousModel) // { // previousModel.Status = PipeStatus.eFill; // } //} pipeModel.DriveModel(pipeModel.FinalTransform); continue; } // Drive the model //pipeModel.DriveModel(m_currentPipeInfo.Matrix.ToVTKTransformation()); pipeModel.DriveModel(pipeModel.GetPipeTransformByPipeInfo(m_currentPipeInfo)); } else if (iPipeIndex < iCurrentPipeIndex) { // Conside the refill mode // Get the next pipe status CPipeModel previousModel = IApp.theApp.DataModel.PipeModels[iPipeIndex]; if (previousModel != null && (previousModel.Status == PipeStatus.eDone || previousModel.Status == PipeStatus.eFill)) { pipeModel.Status = PipeStatus.eFill; } else { pipeModel.Status = PipeStatus.eDone; } // Cache the final pipe info for the finished pipe CacheFinalPipeInfoForFinishedPipe(pipeModel, iPipeIndex); // Drive the model if (pipeModel.FinalTransform != null) { pipeModel.DriveModel(pipeModel.FinalTransform); } } } // Add special code to test if the first pipe should show plyon models try { if (iCurrentPipeIndex == 1) { CPipeModel firstPipeModel = IApp.theApp.DataModel.PipeModels[0]; if (firstPipeModel.GPSUCSs.Count == 2) { bool IsFirstPipeGPSSwitched = firstPipeModel.IsFirstPipeGPSSwitched(m_currentPipeInfo.Time); foreach (ISceneNode node in firstPipeModel.Children) { if (node is CPylonModel) { node.Visible = (firstPipeModel.Status == PipeStatus.eWorkingInProgess) && IsFirstPipeGPSSwitched; } } } } } catch (Exception ex) { string errMsg = ex.Message + "\n" + ex.StackTrace; vtk.vtkOutputWindow.GetInstance().DisplayErrorText(errMsg); } }
//public RedisPipeValue TryReadMessage(bool peak, PipeInfo pipeInfo, TimeSpan lockExpiry) //{ // var batch = TryReadMessageBatch(peak, pipeInfo, lockExpiry, 1); // return new RedisPipeValue(pipeInfo, batch.RedisValues.FirstOrDefault(), batch.HoldingList, batch.Peaked); //} public RedisPipeBatch TryReadMessageBatch(bool peak, PipeInfo pipeInfo, TimeSpan lockExpiry, int batchSize) { var db = _redis.GetDatabase(); if (peak) { var batchAddress = $"{Environment.MachineName}:{Guid.NewGuid()}"; //Add the batch to the global list of batches by creating a field on the key 'BatchesSetKey'. //The expiry time is the earliest time that the automated system can discard the message from the //'holding list' created next. db.HashSet(RedisTaskMultiplexorConstants.BatchesSetKey, batchAddress, BatchInfo.MakeBatchInfo(lockExpiry, pipeInfo.PipePath)); //move the batch of messages from the incoming queue to a holding list var message = db.ListRightPopLeftPush(pipeInfo.PipePath, batchAddress); if (!message.HasValue) { batchAddress = null; return(new RedisPipeBatch(pipeInfo, new RedisValue[0], null, true)); } var messages = new List <RedisValue>() { message }; for (int i = 1; i < batchSize; i++) { message = db.ListRightPopLeftPush(pipeInfo.PipePath, batchAddress); if (!message.HasValue) { break; } messages.Add(message); } return(new RedisPipeBatch(pipeInfo, messages, batchAddress, true)); } else { var message = db.ListRightPop(pipeInfo.PipePath); if (!message.HasValue) { return(new RedisPipeBatch(pipeInfo, new RedisValue[0], null, true)); } var messages = new List <RedisValue>() { message }; for (int i = 1; i < batchSize; i++) { message = db.ListRightPop(pipeInfo.PipePath); if (!message.HasValue) { break; } messages.Add(message); } return(new RedisPipeBatch(pipeInfo, messages, null, false)); } }
void makePipe(Color tubeCol, Color flangeCol, Vector3 pipePos, Quaternion pipeRot, Transform parent, float scale, int iterations) { Transform pipeParent = new GameObject().transform; pipeParent.parent = parent; pipeParent.name = "pipe"; pipeParent.transform.position = pipePos; for (int j = 0; j < iterations; j++) { GameObject pipe = GameObject.Instantiate(pipeSegment); pipe.GetComponent <MeshRenderer>().material = pipeMat; pipe.transform.parent = pipeParent; pipe.transform.position = pipePos; float len = Random.Range(1, pipeLength); if (generateColliders) { CapsuleCollider capsule = pipe.AddComponent <CapsuleCollider>(); capsule.radius = RADIUS; capsule.height = len; capsule.center = new Vector3(capsule.center.x, len / 2, capsule.center.z); } pipe.GetComponent <MeshFilter>().mesh = makePipe(len, tubeCol, flangeCol); pipe.transform.rotation = pipeRot; //info PipeInfo info = new PipeInfo(); info.pipeID = pipeIDCounter; info.flangeColor = flangeCol; info.bodyColor = tubeCol; info.scale = scale; info.length = len; pipe.AddComponent <PipeInfoHolder>().info = info; //don't generate a joint on the last segment if (j != iterations - 1) { //generate joint pipePos = pipePos + pipeRot * transform.up * (len + JOINTSIZE); pipeRot = pipeRot * Quaternion.Euler(90, 0, Random.Range(0, 360)); GameObject joint = GameObject.Instantiate(pipeSegment); joint.GetComponent <MeshRenderer>().material = pipeMat; joint.transform.parent = pipe.transform; joint.transform.position = pipePos + pipeRot * new Vector3(0, JOINTSIZE, JOINTSIZE); joint.GetComponent <MeshFilter>().mesh = makeJoint(tubeCol, tubeCol); joint.transform.rotation = pipeRot * Quaternion.Euler(180, 90, 0); pipePos = pipePos + pipeRot * transform.up * JOINTSIZE; if (generateColliders) { MeshCollider coll = joint.AddComponent <MeshCollider>(); coll.sharedMesh = joint.GetComponent <MeshFilter>().mesh; coll.convex = true; } //info PipeInfo jInfo = new PipeInfo(); jInfo.pipeID = pipeIDCounter; jInfo.flangeColor = flangeCol; jInfo.bodyColor = tubeCol; jInfo.scale = scale; jInfo.length = JOINTSIZE; joint.AddComponent <PipeInfoHolder>().info = jInfo; } } pipeParent.localScale = new Vector3(scale, scale, scale); pipeIDCounter++; }
public void Execute(PipeInfo pipeInfo, RedisPipeValue value) { var valueAsString = value.ValueString; System.Diagnostics.Debug.WriteLine($"{pipeInfo.ParentPipeName}/{pipeInfo.ChildPipeName} : {valueAsString}"); }