public static byte[] DirectCommand(ByteCodeBuffer bytecodes, int globalbytes, int localbytes) { try { lock (sync) { // if not already done, memorize the start time and fire up the communication MemorizeStartTime(); EstablishConnection(); // if requested to only queue the command, and the queue is not too full, and there is no expected response if (queue_active && globalbytes == 0 && queue.Length + bytecodes.Length < 900) // prevent to exceed 1024 bytes in single transmission { bytecodes.CopyTo(queue); queue_locals = Math.Max(queue_locals, localbytes); queue_active = false; return(new byte[0]); } else { queue_active = false; // remove queue-status in any case } // if there is data in the queue, try to merge it with the new command if (queue.Length > 0) { // when total length is not too big, can send together with new command if (queue.Length + bytecodes.Length < 900) { bytecodes.CopyTo(queue); byte[] response = con.DirectCommand(queue, globalbytes, Math.Max(localbytes, queue_locals)); queue.Clear(); queue_locals = 0; return(response); } // if can not be merged, send queued commands seperately con.DirectCommand(queue, 0, queue_locals); queue.Clear(); queue_locals = 0; } // finally execute the command return(con.DirectCommand(bytecodes, globalbytes, localbytes)); } } catch (Exception) { // no connection - must terminate immediately System.Environment.Exit(1); } return(null); }
public byte[] DirectCommand(ByteCodeBuffer bytecodes, int globalbytes, int localbytes) { // increase message counter (neccesary to check if request and respond match) messagecounter++; byte[] sendpacket = new byte[2 + 1 + 2 + bytecodes.Length]; sendpacket[0] = (byte)(messagecounter & 0xff); sendpacket[1] = (byte)((messagecounter >> 8) & 0xff); sendpacket[2] = 0x00; // DIRECT_COMMAND_REPLY sendpacket[3] = (byte)(globalbytes & 0xff); sendpacket[4] = (byte)(((globalbytes >> 8) & 0x3) + (localbytes << 2)); bytecodes.CopyTo(sendpacket, 5); SendPacket(sendpacket); for (; ;) { byte[] packet = ReceivePacket(); if (packet.Length < 3) { throw new Exception("Reply has no message counter"); } // wait until reply arrives that has a counter that matches the command ushort ctr = (ushort)(packet[0] + (packet[1] << 8)); // Console.WriteLine("Expected counter: "+messagecounter+ " received counter: " + ctr); if (ctr != messagecounter) { continue; } // check if the direct command caused an error if (packet[2] == 0x04) { return(null); } // check if problems with received packet if (packet[2] != 0x02) { throw new Exception("Reply is not of correct type"); } if (packet.Length != globalbytes + 3) { throw new Exception("Reply size unexpected: " + packet.Length + " instead of " + (globalbytes + 3)); } // extract data byte[] replydata = new byte[packet.Length - 3]; System.Array.Copy(packet, 3, replydata, 0, packet.Length - 3); return(replydata); } }