Example #1
0
		/// <summary>
		/// Start a new command of a speicifc type with a global and/or local buffer on the EV3 brick
		/// </summary>
		/// <param name="commandType">The type of the command to start</param>
		/// <param name="globalSize">The size of the global buffer in bytes (maximum of 1024 bytes)</param>
		/// <param name="localSize">The size of the local buffer in bytes (maximum of 64 bytes)</param>
		public void Initialize(CommandType commandType, ushort globalSize, int localSize)
		{
			if(globalSize > 1024)
				throw new ArgumentException("Global buffer must be less than 1024 bytes", "globalSize");
			if(localSize > 64)
				throw new ArgumentException("Local buffer must be less than 64 bytes", "localSize");

			_stream = new MemoryStream();
			_writer = new BinaryWriter(_stream);
			Response = ResponseManager.CreateResponse();

			CommandType = commandType;

			// 2 bytes (this gets filled in later when the user calls ToBytes())
			_writer.Write((ushort)0xffff);

			// 2 bytes
			_writer.Write(Response.Sequence);

			// 1 byte
			_writer.Write((byte)commandType);

			if(commandType == CommandType.DirectReply || commandType == CommandType.DirectNoReply)
			{
				// 2 bytes (llllllgg gggggggg)
				_writer.Write((byte)globalSize); // lower bits of globalSize
				_writer.Write((byte)((localSize << 2) | (globalSize >> 8) & 0x03)); // upper bits of globalSize + localSize
			}
		}
		internal static Response CreateResponse()
		{
			ushort sequence = GetSequenceNumber();

			Response r = new Response(sequence);
			Responses[sequence] = r;
			return r;
		}
		internal static async Task WaitForResponseAsync(Response r)
		{
			await Task.Run(() =>
			{
				if(r.Event.WaitOne(1000))
					Responses.Remove(r.Sequence);
				else
					r.ReplyType = ReplyType.DirectReplyError;
			});
		}