//this is implied to be run on the server and single player if you follow it public override void ReceiveCommand(CommandPacket packet) { base.ReceiveCommand(packet); if(packet.uuids.Length > 0) { foreach(var s in packet.uuids) { var unit = GameObject.Find(s).GetComponent<GameCommandHandler>(); unit.ReceiveCommand(packet); } } }
//make a packet merger function private void Update() { if(!NetworkClient.active || isLocalPlayer) { if(Input.GetMouseButtonDown(0) && uuids.Length > 0) { var click = Input.mousePosition; var pos = Camera.main.ScreenToWorldPoint(click); var hit = Physics2D.Raycast(pos, Vector2.zero); if(hit.collider == null) { var packet = new CommandPacket() { dataString = name, uuids = this.uuids, command = GameCommand.Move, dataVector = pos }; SendCommandPacket(packet); } } } }
private void doConnect(CommandPacket pData) { lock (socketList) { socketList.Add(pData.clientSocket); } if (OnConnect != null) { try { OnConnect(pData.clientSocket); } catch { } } }
// ------------------------------------------------------------------------ // private void ClientConnected(IAsyncResult aResult) { try { if (!listenSocket.Connected) { try { Socket wSocket = listenSocket.EndAccept(aResult); wSocket.DontFragment = false; CommandPacket pData = new CommandPacket(); pData.clientSocket = wSocket; doConnect(pData); wSocket.BeginReceive(pData.tmpbuf, 0, pData.tmpbuf.Length, SocketFlags.None, new AsyncCallback(DataReceived), pData); } catch (Exception ex) { Console.WriteLine("[CommandServer.ClientConnected] {0}", ex); } listenSocket.BeginAccept(new AsyncCallback(ClientConnected), null); } } catch (Exception ex) { Console.WriteLine("[CommandServer.ClientConnected] {0}", ex); } }
protected override void OnStart() { // send the first message to device... CommandPacket cmd = new CommandPacket(); cmd.CommandId = (uint)PACKET_TYPE.MESSAGE_PACKET; cmd.AddParameterDWORD((uint)MESSAGE_ID.AGENT_ACK_MSG); SendCommand(cmd); }
private void WatchDogTimerEvent(object source, ElapsedEventArgs e) { if (Connected) { // send to device... CommandPacket cmd = new CommandPacket(); cmd.CommandId = (uint)PACKET_TYPE.MESSAGE_PACKET; cmd.AddParameterDWORD((uint)MESSAGE_ID.AGENT_PING_MSG); SendCommand(cmd); } else { ctrlPanelData.CloseDevice(); } }
private void SendHCIEvent(byte[] bytes) { AddCommLog(GlobalData.EVENT_PACKET, bytes, bytes.Length, GlobalData.OK); // send to device... CommandPacket cmd = new CommandPacket(); cmd.CommandId = (uint)PACKET_TYPE.HCI_DATA_PACKET; cmd.AddParameterBytes(bytes); SendCommand(cmd); }
public void SendCommandPacket(CommandPacket packet) { if(NetworkClient.active) CmdReceiveCommand(packet); //handle as network else ReceiveCommand(packet); //or as single player }
public AsyncRedisSocket GetAsyncRedisSocket(CommandPacket cmd) { AsyncRedisSocket asyncRds = null; Interlocked.Increment(ref _asyncRedisSocketsConcurrentCounter); for (var limit = 0; limit < 1000; limit += 1) { if (_asyncRedisSocketsCount > 0) { lock (_asyncRedisSocketsLock) { if (_asyncRedisSockets.Count > 0) { asyncRds = _asyncRedisSockets[RedisClient.BaseAdapter._rnd.Value.Next(_asyncRedisSockets.Count)]; Interlocked.Increment(ref asyncRds._writeCounter); Interlocked.Decrement(ref _asyncRedisSocketsConcurrentCounter); return(asyncRds); } } } if (limit > 50 && _asyncRedisSocketsConcurrentCounter < 2) { break; } if (_asyncRedisSocketsCount > 1) { Thread.CurrentThread.Join(2); } } NewAsyncRedisSocket(); //AsyncRedisSocket.sb.AppendLine($"线程{Thread.CurrentThread.ManagedThreadId}:AsyncRedisSockets 数量 {_asyncRedisSocketsCount} {_asyncRedisSocketsConcurrentCounter}"); Interlocked.Decrement(ref _asyncRedisSocketsConcurrentCounter); return(asyncRds); void NewAsyncRedisSocket() { var rds = _adapter.GetRedisSocket(cmd); var key = Guid.NewGuid(); asyncRds = new AsyncRedisSocket(rds, () => { if (_asyncRedisSocketsConcurrentCounter > 0 || _asyncRedisSocketsCount > 1) { Thread.CurrentThread.Join(8); } Interlocked.Decrement(ref _asyncRedisSocketsCount); lock (_asyncRedisSocketsLock) _asyncRedisSockets.Remove(asyncRds); }, (innerRds, ioex) => { if (ioex != null) { (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool.SetUnavailable(ioex); } innerRds.Dispose(); }, () => { lock (_asyncRedisSocketsLock) { if (asyncRds._writeCounter == 0) { return(true); } } return(false); }); lock (_asyncRedisSocketsLock) { Interlocked.Increment(ref asyncRds._writeCounter); _asyncRedisSockets.Add(asyncRds); } Interlocked.Increment(ref _asyncRedisSocketsCount); } }
WriteAsyncInfo WriteInQueue(CommandPacket cmd) { var ret = new WriteAsyncInfo { Command = cmd }; if (_rds.ClientReply == ClientReplyType.on) { ret.TaskCompletionSource = new TaskCompletionSource <RedisResult>(); } var isnew = false; lock (_writeAsyncLock) { _writeQueue.Enqueue(ret); if (_isfirst == false) { isnew = _isfirst = true; } if (_bufferStream == null) { _bufferStream = new MemoryStream(); } new RespHelper.Resp3Writer(_bufferStream, _rds.Encoding, _rds.Protocol).WriteCommand(cmd); } if (isnew) { //Thread.CurrentThread.Join(TimeSpan.FromTicks(1000)); try { if (_rds.IsConnected == false) { _rds.Connect(); } } catch (Exception ioex) { lock (_writeAsyncLock) { while (_writeQueue.TryDequeue(out var wq)) { wq.TaskCompletionSource?.TrySetException(ioex); } _bufferStream.Close(); _bufferStream.Dispose(); _bufferStream = null; } _rds.ReleaseSocket(); _end(_rds, ioex); throw ioex; } for (var a = 0; a < 100; a++) { var cou = _writeQueue.Count; if (cou > 100) { break; } } var localQueue = new Queue <WriteAsyncInfo>(); long localQueueThrowException(Exception exception) { long counter = 0; while (localQueue.Any()) { var witem = localQueue.Dequeue(); if (exception != null) { witem.TaskCompletionSource?.TrySetException(exception); } else { witem.TaskCompletionSource?.TrySetCanceled(); } counter = Interlocked.Decrement(ref _writeCounter); } return(counter); } var iswait = _writeCounter > 1; if (iswait) { Thread.CurrentThread.Join(10); } _begin(); while (true) { if (_writeQueue.Any() == false) { Thread.CurrentThread.Join(10); continue; } lock (_writeAsyncLock) { while (_writeQueue.TryDequeue(out var wq)) { localQueue.Enqueue(wq); } _bufferStream.Position = 0; try { _bufferStream.CopyTo(_rds.Stream); _bufferStream.Close(); _bufferStream.Dispose(); _bufferStream = null; } catch (Exception ioex) { localQueueThrowException(ioex); _bufferStream.Close(); _bufferStream.Dispose(); _bufferStream = null; _rds.ReleaseSocket(); _end(_rds, ioex); throw ioex; } } long counter = 0; RedisResult rt = null; //sb.AppendLine($"{name} 线程{Thread.CurrentThread.ManagedThreadId}:合并读取 {localQueue.Count} 个命令 total:{sw.ElapsedMilliseconds} ms"); while (localQueue.Any()) { var witem = localQueue.Dequeue(); try { rt = _rds.Read(witem.Command); } catch (Exception ioex) { localQueueThrowException(ioex); _rds.ReleaseSocket(); _end(_rds, ioex); throw ioex; } witem.TaskCompletionSource.TrySetResult(rt); counter = Interlocked.Decrement(ref _writeCounter); } if (counter == 0 && _finish()) { break; } Thread.CurrentThread.Join(1); //sb.AppendLine($"{name} 线程{Thread.CurrentThread.ManagedThreadId}:等待 1ms + {_writeQueue.Count} total:{sw.ElapsedMilliseconds} ms"); } //sb.AppendLine($"{name} 线程{Thread.CurrentThread.ManagedThreadId}:退出 total:{sw.ElapsedMilliseconds} ms"); _end(_rds, null); } return(ret); }
/// <summary> /// Admin ban user /// </summary> void AdminBan(OnlineUser user, CommandPacket command) { User backendUser = Users[user.Username]; var arguments = command.arguments; // Permission check if (backendUser.permissionLevel < 1) { PermissionDeniedMessage(user); return; } // Syntax check if (arguments.Count != 2) { ServerMessage( "server", user, langFile["command_arguments_error"] .Replace("$COUNT$", "2") ); return; } // Check if the user is exist if (!Users.ContainsKey(arguments[0])) { ServerMessage( "server", user, langFile["command_userNotExist"] .Replace("$NAME$", arguments[0]) ); return; } // Check permission level User target = Users[arguments[0]]; if (target.permissionLevel >= backendUser.permissionLevel) { ServerMessage( "server", user, langFile["command_higherPermission"] .Replace("$NICK$", target.nickname) .Replace("$NAME$", target.username) ); return; } // Convert time DateTime time; if (!TypeConvert.TryGetTime(arguments[1], out time)) { ServerMessage( "server", user, langFile["command_invalidTimeFormat"] ); return; } DateTime untilTime = DateTime.Now.AddTicks(time.Ticks); target.banTime = untilTime; Info( $"{backendUser.nickname}\\rr({backendUser.username}\\rr)" + $" banned {target.nickname}\\rr({target.username}\\rr)." ); Broadcast( "server", langFile["command_ban_broadcast"] .Replace("$NICK$", target.nickname) .Replace("$NAME$", target.username) .Replace("$TIME$", untilTime.ToString("yyyy/MM/dd HH:mm:ss")) ); if (OnlineUsers.ContainsKey(arguments[0])) { DisconnectMessage( OnlineUsers[arguments[0]], user.Username, langFile["command_ban_message"] .Replace("$TIME$", untilTime.ToString("yyyy/MM/dd HH:mm:ss")) ); Disconnect(arguments[0]); } }
void AdminUnban(OnlineUser user, CommandPacket command) { User backendUser = Users[user.Username]; var arguments = command.arguments; // Permission check if (backendUser.permissionLevel < 1) { PermissionDeniedMessage(user); return; } // Syntax check if (arguments.Count != 1) { ServerMessage( "server", user, langFile["command_arguments_error"] .Replace("$COUNT$", "1") ); return; } // Check if the user is exist if (!Users.ContainsKey(arguments[0])) { ServerMessage( "server", user, langFile["command_userNotExist"] .Replace("$NAME$", arguments[0]) ); return; } // Check permission level User target = Users[arguments[0]]; if (target.permissionLevel >= backendUser.permissionLevel) { ServerMessage( "server", user, langFile["command_higherPermission"] .Replace("$NICK$", target.nickname) .Replace("$NAME$", target.username) ); return; } // Check if is unmutable if (target.banTime < DateTime.Now) { ServerMessage( "server", user, langFile["command_unban_notBanned"] .Replace("$NICK$", target.nickname) .Replace("$NAME$", target.username) ); return; } target.banTime = DateTime.MinValue; Info( $"{backendUser.nickname}\\rr({backendUser.username}\\rr)" + $" unbanned {target.nickname}\\rr({target.username}\\rr)." ); Broadcast( "server", langFile["command_unban_broadcast"] .Replace("$NICK$", target.nickname) .Replace("$NAME$", target.username) ); }
public async Task HandleClient(ServerInfo info) { try { using (var stream = _client.GetStream()) { // Send hello packet var inHandshake = true; var hello = new GreetingPacket10(ThreadID, info.VersionString).ToByteArray(); await stream.WriteAsync(hello, 0, hello.Length).ConfigureAwait(false); while (true) { var rec = new byte[ushort.MaxValue << 2]; var i = await stream.ReadAsync(rec, 0, rec.Length).ConfigureAwait(false); if (i <= 0) { break; } try { var data = rec.Take(i).ToArray(); byte[] ret; if (inHandshake) { var login = new LoginPacket(data); ret = HandshakeResponse(login); inHandshake = false; } else { var timer = info.ReportTimings ? new Stopwatch() : null; timer?.Start(); var command = new CommandPacket(data, Database); ret = (await _commandFunc(command, timer)).ToByteArray(); } if (ret.Length > 0) { await stream.WriteAsync(ret, 0, ret.Length).ConfigureAwait(false); } } catch (Exception e) { Console.WriteLine($"Exception occurred on thread {ThreadID}: {e}"); } } } } finally { if (_client != null) { (_client as IDisposable).Dispose(); _client = null; } OnClose?.Invoke(this, new SqlConnectionClosedEventArgs(ThreadID)); } }
public static bool TryCreatePacket(string rawCommand, out CommandPacket packet) { packet = new CommandPacket(); rawCommand = rawCommand.ToUpper(); rawCommand = rawCommand.Replace(" ", ""); if (IsFunction(rawCommand)) { bool hasParameters = false; if (rawCommand.EndsWith(")")) { hasParameters = true; } if (hasParameters) { int parameterStartIndex = rawCommand.IndexOf('('); string function = rawCommand.Substring(0, parameterStartIndex); packet.Command = function; packet.InteractableFullId = "HACKER"; packet.ParameterList = ExtractParameters(rawCommand); } else { packet.Command = rawCommand; packet.InteractableFullId = "HACKER"; packet.ParameterList = new List <string>(); } } else { if (rawCommand.StartsWith(".") || !rawCommand.Contains(".")) { Debug.LogWarning("COMMAND ERROR: " + rawCommand); return(false); } string delimiter = "."; int delimiterIndex = rawCommand.IndexOf(delimiter); string interactableId = rawCommand.Substring(0, delimiterIndex); int parameterStartIndex = rawCommand.IndexOf('('); int lengthOfCommand = rawCommand.Length - delimiterIndex - 1; bool hasParams = parameterStartIndex != -1; if (hasParams) { lengthOfCommand = rawCommand.Length - delimiterIndex - (rawCommand.Length - parameterStartIndex) - 1; } string command = rawCommand.Substring(delimiterIndex + 1, lengthOfCommand); packet.InteractableFullId = interactableId; packet.Command = command; packet.ParameterList = ExtractParameters(rawCommand); } return(true); }
public virtual void ReceiveCommand(CommandPacket packet) { currentCommand = packet.command; dataString = packet.dataString; dataVector = packet.dataVector; }
private AchievementManager(Bot bot) { this.bot = bot; AccountManager.Instance.OnGlobalLevelUp += async(u, c, l) => { LevelPacket p = new LevelPacket() { discordUser = await c.Guild.GetUserAsync(u.Id.FromDbLong()), discordChannel = c, account = u, level = l, }; await OnLevelGained?.Invoke(p); }; AccountManager.Instance.OnTransactionMade += async(msg, u1, u2, amount) => { TransactionPacket p = new TransactionPacket() { discordUser = msg.Author, discordChannel = msg.Channel, giver = u1, receiver = u2, amount = amount }; await OnTransaction?.Invoke(p); }; bot.Client.MessageReceived += async(e) => { if (OnMessageReceived == null) { return; } MessageEventPacket p = new MessageEventPacket() { message = new RuntimeMessage(e), discordUser = new RuntimeUser(e.Author), discordChannel = new RuntimeMessageChannel(e.Channel) }; await OnMessageReceived?.Invoke(p); }; bot.Client.UserUpdated += async(ub, ua) => { UserUpdatePacket p = new UserUpdatePacket() { discordUser = new RuntimeUser(ub), userNew = new RuntimeUser(ua) }; await OnUserUpdate?.Invoke(p); }; bot.Events.AddCommandDoneEvent(x => { x.Name = "--achievement-manager-command"; x.processEvent = async(m, e, s) => { CommandPacket p = new CommandPacket() { discordUser = m.Author, discordChannel = m.Channel, message = m, command = e, success = s }; await OnCommandUsed?.Invoke(p); }; }); }
//private static void TestQueries() //{ // string expression; // var queries = new AppResources().GetQueries(); // var query = queries.Single(q => q.ServiceControllerMethodName == "GetPublisherForCurrentUser"); // var queryCode = query.QueryExpression.Replace(new Dictionary<string, string> { { "containerVariable", "entities" }, { "identityNameVariable", "userName" } }); // expression = "/Users[@Name=\"John\"]"; // Console.WriteLine("{0}Parsing: '{1}'", '\t'.Repeat(2), expression); // new QueryPathAttribute(expression, QueryKind.LoadParentReference); // expression = "/Users[last()]"; // Console.WriteLine("{0}Parsing: '{1}'", '\t'.Repeat(2), expression); // new QueryPathAttribute(expression); // expression = "/Users[@UserName=identity_name()]/UserToPublishers/Publisher"; // Console.WriteLine("{0}Parsing: '{1}'", '\t'.Repeat(2), expression); // new QueryPathAttribute(expression); //} //private static void TestNavigationProperties() //{ // var entities = new Db.RipleyEntities(); // var id = Guid.Parse("6c507edc-8845-4591-80b6-34bf1dc6045a"); // if (entities.LessonAuthorizedForUser(id)) // { // var lesson = entities.Lessons.Single(l => l.LessonId == id); // var user = lesson.Course.Publisher.UserToPublishers.Single().User; // } //} //private static bool LessonAuthorizedForUser(this Db.RipleyEntities entities, Guid id) //{ // if (entities.Database.SqlQuery<bool>("EXISTS()").Single()) // { // var lesson = entities.Lessons.Single(l => l.LessonId == id); // var user = lesson.Course.Publisher.UserToPublishers.Single().User; // } // return false; //} private static void TestFolderToJson() { var folder = new Folder(null, "/"); var packet = new CommandPacket("", DateTime.Now, folder); }
/// <summary> /// Sphero contains a powerful analysis function to filter accelerometer data in order to detect collisions. /// Because this is a great example of a high-level concept that humans excel and – but robots do not – a number of parameters control the behavior. /// When a collision is detected an asynchronous message is generated to the client . /// </summary> /// <param name="method">Detection method type to use</param> /// <param name="xThreshold">Threshold for the X (left/right) axe of Sphero. A value of 00h disables the contribution of that axis</param> /// <param name="xSpeed">Speed value for the X axe. This setting is ranged by the speed, then added to Xt to generate the final threshold value.</param> /// <param name="yThreshold">Threshold for the Y (front/back) axe of Sphero. A value of 00h disables the contribution of that axis</param> /// <param name="ySpeed">Speed value for the YX axe. This setting is ranged by the speed, then added to Yt to generate the final threshold value.</param> /// <param name="dead">Post-collision dead time to prevent retriggering; specified in 10ms increments.</param> public void ConfigureCollisionDetection(CollisionMethod method, byte xThreshold, byte xSpeed, byte yThreshold, byte ySpeed, byte dead) { CommandPacket command = new CommandPacket(0xFE, DeviceIDs.SPHERO, CommandIDs.Sphero.CONFIGURE_COLLISION_DETECTION, new byte[] { (byte)method, xThreshold, xSpeed, yThreshold, ySpeed, dead }); _connection.SendCommand(command); }
public void CmdReceiveCommand(CommandPacket packet) { ReceiveCommand(packet); }
public IObservable <AnswerPacket> CommandRequest(CommandPacket packet) { return(Observable.Start(() => SendCommand(packet))); }
private void SendDeviceLogging() { CommandPacket cmd = new CommandPacket(); cmd.CommandId = (uint)PACKET_TYPE.MESSAGE_PACKET; MESSAGE_ID cmdId = ctrlPanelData.DeviceLogging ? MESSAGE_ID.AGENT_LOGGING_ON_MSG : MESSAGE_ID.AGENT_LOGGING_OFF_MSG; cmd.AddParameterDWORD((uint)cmdId); SendCommand(cmd); }
public void SendCommand(CommandPacket comPacket) { comPacket.Write(this.socket); }
private bool SendCommand(CommandPacket cmd) { if (CommandTransport != null && CommandTransport.ConnectionState == CommandTransport.ConnectState.Connected && BthRuntime.INVALID_DEVICE_ID != devId) { // send to device... CommandTransport.ProcessCommand(cmd, ctrlPanelData); return true; } return false; }
/// <summary> /// 画像読み込みメイン処理 /// 同じスケジューラの上でシーケンシャルに動作 /// </summary> /// <param name="command"></param> /// <returns></returns> private async Task LoadImageAsync(CommandPacket command) { var key = command.Path; if (this.TryGetImage(key, command.Option.Quality, out var result)) { if (result != null) { command.Observer.OnNext(result); command.Observer.OnCompleted(); return; } } var token = command.CancellationToken; if (token.IsCancellationRequested) { command.Observer.OnCompleted(); return; } var image = new ImageSourceContainer(); bool failedFlag = false; var option = command.Option; var file = command.File; Size?frameSize = null; switch (option.Quality) { case ImageQuality.ThumbNail: case ImageQuality.Resized: //リサイズ if (option.FrameWidth > 1 && option.FrameHeight > 1) { frameSize = new Size(option.FrameWidth, option.FrameHeight); } else if (option.Quality == ImageQuality.ThumbNail) { frameSize = this.lowQualitySize; } break; case ImageQuality.LowQuality: //低画質読み込み frameSize = this.lowQualitySize; break; case ImageQuality.OriginalSize: //オリジナルサイズで読み込み frameSize = null; break; default: break; } var asThumbnail = option.Quality <= ImageQuality.LowQuality; try { if (file != null) { await image.LoadImageAsync (file, frameSize, asThumbnail, option.IsFill, option.CmsEnable); } else { await image.LoadImageAsync (key, frameSize, asThumbnail, option.IsFill, option.CmsEnable); } } catch (OutOfMemoryException e) { if (option.Quality == ImageQuality.ThumbNail) { ClearBuffer(); command.Observer.OnError(e); return; } else { failedFlag = true; } } catch (Exception e) { command.Observer.OnError(e); return; } if (failedFlag) { if (token.IsCancellationRequested) { command.Observer.OnCompleted(); return; } this.ClearBuffer(); GC.Collect(); GC.WaitForPendingFinalizers(); await Task.Delay(300); image = new ImageSourceContainer(); if (!frameSize.HasValue || frameSize.Value.Width > failedLoadingLength || frameSize.Value.Height > failedLoadingLength) { //サイズ小さめ frameSize = failedLoadingSize; } var reloadOption = command.Option.Clone(); try { if (file != null) { await image.LoadImageAsync (file, frameSize, asThumbnail, option.IsFill, option.CmsEnable); } else { await image.LoadImageAsync (key, frameSize, asThumbnail, option.IsFill, option.CmsEnable); } } catch (Exception e) { command.Observer.OnError(e); return; } } if (image.HasImage()) { if (option.Quality == ImageQuality.ThumbNail || image.Quality <= ImageQuality.LowQuality) { thumbNailImages.AddOrExtrude (key, new ImageBufferItem(image, ++this.count), thumbNailbufferSize); } else { images.AddOrExtrude (key, new ImageBufferItem(image, ++this.count), bufferSize); } this.UpdatedSubject.OnNext(key); command.Observer.OnNext(image); } command.Observer.OnCompleted(); }
private bool OnDeviceDataReceived(byte[] bytes) { int length = bytes.Length; if (length > 0) { HCI_TYPE hciType = (HCI_TYPE)bytes[0]; // send command/data to bluetooth device... int lastError = 0; int ret = BthRuntime.SendHCICommand(devId, bytes, (uint)bytes.Length); string result = GlobalData.OK; if (ret == 0) { lastError = Marshal.GetLastWin32Error(); string errMsg = new System.ComponentModel.Win32Exception(lastError).Message; result = string.Format("Fail: {0} ({1})", lastError, errMsg); } // send error code to device... CommandPacket cmd = new CommandPacket(); cmd.CommandId = (uint)PACKET_TYPE.HCI_DATA_ERROR_PACKET; cmd.AddParameterDWORD((uint)lastError); SendCommand(cmd); // add log entry. AddCommLog(hciType.ToString(), bytes, bytes.Length, result); } return false; }
public virtual Message Hack(CommandPacket commandPacket) { Debug.Log("HACKED: " + Id.FullId); return(new Message(true, Id, MessageType.WARNING, "INTERACTED WITH BASE.INTERACTABLE")); }
/// <summary> /// Received a command packet /// </summary> /// <param name="commandPacket">Command packet received</param> protected override void OnCommandPacketReceived(CommandPacket commandPacket) { if (commandPacket == null) return; PACKET_TYPE packetType = (PACKET_TYPE)commandPacket.CommandId; switch (packetType) { case PACKET_TYPE.MESSAGE_PACKET: { MESSAGE_ID msgId = (MESSAGE_ID)commandPacket.GetParameterDWORD(); CommandPacket cmd = new CommandPacket(); cmd.CommandId = (uint)PACKET_TYPE.MESSAGE_PACKET; AddCommLog(msgId.ToString()); switch (msgId) { case MESSAGE_ID.AGENT_ACK_MSG: cmd.AddParameterDWORD((uint)MESSAGE_ID.AGENT_INITIALIZE_MSG); SendCommand(cmd); break; case MESSAGE_ID.AGENT_INITIALIZE_MSG: SendDeviceLogging(); break; case MESSAGE_ID.AGENT_UNINITIALIZE_MSG: cmd.AddParameterDWORD((uint)MESSAGE_ID.AGENT_INITIALIZE_MSG); SendCommand(cmd); break; case MESSAGE_ID.AGENT_LOGGING_ON_MSG: break; case MESSAGE_ID.AGENT_LOGGING_OFF_MSG: break; case MESSAGE_ID.COM_OPEN_MSG: break; case MESSAGE_ID.AGENT_PING_MSG: break; case MESSAGE_ID.COM_CLOSE_MSG: cmd.AddParameterDWORD((uint)MESSAGE_ID.AGENT_UNINITIALIZE_MSG); SendCommand(cmd); break; } } break; case PACKET_TYPE.HCI_DATA_PACKET: { CommandPacketParameter cpp; while ((cpp = commandPacket.GetNextParameter()) != null) { switch (cpp.Type) { case CommandPacketParameterType.Bytes: OnDeviceDataReceived(cpp.BytesParameter); break; default: break; } } } break; } }
public override void ReceiveCommand(CommandPacket packet) { base.ReceiveCommand(packet); destinationTarget = Location.GetLocation(packet.dataString); }
private void doCommandReceived(CommandPacket pData) { if (OnCommandReceived != null) { try { OnCommandReceived(pData.command, pData.clientSocket); } catch { } } }
/// <summary> /// Shifts out an array of packets in parallel, one packet for each pin. /// </summary> /// <param name="commandPackets">An array of packets to be shifted out in parallel on the data pins.</param> public void SendPacketArray(CommandPacket[] commandPackets) { // DDL, this is only ever 1 //if(commandPackets.Length != _portLayout.DataPorts.Length) //{ // throw new ArgumentOutOfRangeException("commandPackets", "The length of the command packet array does not equal the length of the data port array."); //} var values = new uint[commandPackets.Length]; for(int i = 0; i<commandPackets.Length; i++) { values[i] = commandPackets[i].GetCommand(); } // Lower Clock _portLayout.ClockPort.Write(false); string s = ""; UInt32 mask = 0x80000000; for (int i = 0; i < 32; i++) { //UInt32 mask = (UInt32)(1 << i); bool bWriteVal; //for (int portNumber = 0; portNumber < _portLayout.DataPorts.Length; portNumber++) for (int portNumber = 0; portNumber < _iNumBanks; portNumber++) { bWriteVal = (values[portNumber] & mask) != 0; /* if ((values[portNumber] & mask) != 0) { //s += "1"; bWriteVal = true; } else { //s += "0"; bWriteVal = false; } */ _portLayout.DataPorts[portNumber].Write(bWriteVal); } // Raise Clock _portLayout.ClockPort.Write(true); //wait(1); //Thread.Sleep(1); // set Data to prevent IO conflict /* DDL I took this out because it shaved 600 uS off the clock function (750 uS down to 160 uS) foreach (IOutputPort t in _portLayout.DataPorts) { t.Write(false); } */ // Lower Clock _portLayout.ClockPort.Write(false); mask = mask >> 1; // shift mask over one bit } }
private void doDisconnect(ref CommandPacket pData) { lock (socketList) { try { socketList.Remove(pData.clientSocket); } catch { } } if (OnDisconnect != null) { try { OnDisconnect(pData.clientSocket); } catch { } } try { pData.clientSocket.Close(); } catch { } try { pData.Dispose(); pData = null; } catch { } }
private void OnPacketReceived(CommandPacket packet) { _onCommandReceived.OnNext(packet.CommandType); }