123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using FunnyCommon.Shared;
- namespace FunnyCommon.Remoting.Protocol
- {
- public class Command
- {
- public CommandType Type { get; set; }
- public byte Value { get; set; }
- public override string ToString()
- {
- return $"{Type} {Value}";
- }
- public byte[] ToBytes()
- {
- var buf = new byte[2];
- buf[0] = (byte)Type;
- buf[1] = Value;
- return buf;
- }
- private static readonly HashSet<byte> CommandTypeValues =
- new HashSet<byte>(Enum.GetValues(typeof(CommandType)).Cast<byte>());
- public static Command ReadFromStream(Stream stream)
- {
- using (var br = new BinaryReader(stream, Encoding.UTF8, true))
- {
- var read = br.ReadByte();
- if (!CommandTypeValues.Contains(read)) throw new InvalidDataException(nameof(CommandType) + $"<{read}>");
- var type = (CommandType)read;
- var obj = new Command
- {
- Type = type,
- Value = br.ReadByte(),
- };
- return obj;
- }
- }
- public Response Execute(IPiGpoutManager manager)
- {
- string mesg = null;
- switch (Type)
- {
- case CommandType.AllocateGpio:
- switch (manager.Allocate(Value))
- {
- case true:
- mesg = $"Rob pin_{Value}";
- break;
- case false:
- mesg = $"Norm Allocated pin_{Value}";
- break;
- case null:
- mesg = $"Already Allocated pin_{Value}";
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(Nullable<bool>));
- }
- break;
- case CommandType.FreeGpio:
- manager.Free(Value);
- mesg = $"Norm Free gpio{Value}";
- break;
- case CommandType.SetHeight:
- manager.WritePin(Value, true);
- mesg = $"Norm SetHeight gpio{Value}";
- break;
- case CommandType.SetLow:
- manager.WritePin(Value, false);
- mesg = $"Norm SetLow gpio{Value}";
- break;
- case CommandType.Sleep:
- Thread.Sleep(Value);
- mesg = $"Norm Sleeped {Value}ms";
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(Type));
- }
- return new Response { Success = true, Message = mesg };
- }
- }
- }
|