Exemplo n.º 1
2
    static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher)
    {

        Byte[]  CipherCalculated;
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(Plain);
        Console.WriteLine("With the following Key:");
        PrintByteArray(Key);
        Console.WriteLine("and IV:");
        PrintByteArray(IV);
 		Console.WriteLine("Expecting this ciphertext:");
		PrintByteArray(Cipher);        
        
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        MemoryStream 	ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(Plain,0,Plain.Length);
        cs.FlushFinalBlock();
        CipherCalculated = ms.ToArray();
        cs.Close();

		Console.WriteLine("Computed this cyphertext:");
        PrintByteArray(CipherCalculated);
        

        if (!Compare(Cipher, CipherCalculated)) {
        	Console.WriteLine("ERROR: result is different from the expected");
        	return false;
        }
        
        Console.WriteLine("OK");
        return true;
    }
        public Byte[] SignHash (Byte[] rgbHash, string str) {
            Contract.Requires(rgbHash != null);
            Contract.Requires(rgbHash.Length == 20);
            Contract.Requires(rgbHash.Length == 16);

          return default(Byte[]);
        }
Exemplo n.º 3
1
        public static Byte[] bin2CArray(Byte[] inputData, UInt32 memberSizeInBytes)
        {
            StringBuilder cArraySB;
              UInt32 sizeSB = (((UInt32)inputData.Length)/memberSizeInBytes +1) * (memberSizeInBytes*2 + 4) + 30;

              cArraySB = new StringBuilder((Int32)sizeSB);

              switch(memberSizeInBytes)
              {
            case 1:
              bin2charArray(inputData,cArraySB);
              break;
            case 2:
              break;
            case 4:
              bin2uintArray(inputData,cArraySB);
              break;
            case 8:
              break;
            default:
              break;
              }

              return (new ASCIIEncoding()).GetBytes(cArraySB.ToString());
        }
Exemplo n.º 4
1
	public static bool SendFileToPrinter( string szPrinterName, string szFileName )
	{
		// Open the file.
		FileStream fs = new FileStream(szFileName, FileMode.Open);
		// Create a BinaryReader on the file.
		BinaryReader br = new BinaryReader(fs);
		// Dim an array of bytes big enough to hold the file's contents.
		Byte []bytes = new Byte[fs.Length];
		bool bSuccess = false;
		// Your unmanaged pointer.
		IntPtr pUnmanagedBytes = new IntPtr(0);
		int nLength;

		nLength = Convert.ToInt32(fs.Length);
		// Read the contents of the file into the array.
		bytes = br.ReadBytes( nLength );
		// Allocate some unmanaged memory for those bytes.
		pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
		// Copy the managed byte array into the unmanaged array.
		Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
		// Send the unmanaged bytes to the printer.
		bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
		// Free the unmanaged memory that you allocated earlier.
		Marshal.FreeCoTaskMem(pUnmanagedBytes);
		return bSuccess;
	}
Exemplo n.º 5
1
        private static void SendFile()
        {
            // Создаем файловый поток и переводим его в байты
            Byte[] bytes = new Byte[fs.Length];
            fs.Read(bytes, 0, bytes.Length);

            Console.WriteLine("Отправка файла размером " + fs.Length + " байт");
            try
            {
                // Отправляем файл
                sender.Send(bytes, bytes.Length, endPoint);
            }
            catch (Exception eR)
            {
                Console.WriteLine(eR.ToString());
            }
            finally
            {
                // Закрываем соединение и очищаем поток
                fs.Close();
                sender.Close();
            }
            Console.WriteLine("Файл успешно отправлен.");
            Console.Read();
        }
Exemplo n.º 6
1
        /// <summary>
        /// 客户端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="message"></param>
        static void Client(string ip, int port, string message)
        {
            try
            {
                //1.发送数据
                TcpClient client = new TcpClient(ip, port);
                IPEndPoint ipendpoint = client.Client.RemoteEndPoint as IPEndPoint;
                NetworkStream stream = client.GetStream();
                byte[] messages = Encoding.Default.GetBytes(message);
                stream.Write(messages, 0, messages.Length);
                Console.WriteLine("{0:HH:mm:ss}->发送数据(to {1}):{2}", DateTime.Now, ip, message);

                //2.接收状态,长度<1024字节
                byte[] bytes = new Byte[1024];
                string data = string.Empty;
                int length = stream.Read(bytes, 0, bytes.Length);
                if (length > 0)
                {
                    data = Encoding.Default.GetString(bytes, 0, length);
                    Console.WriteLine("{0:HH:mm:ss}->接收数据(from {1}:{2}):{3}", DateTime.Now, ipendpoint.Address, ipendpoint.Port, data);
                }

                //3.关闭对象
                stream.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
            }
            Console.ReadKey();
        }
Exemplo n.º 7
1
 static void Main(string[] args)
 {
     Log.Info("WorldServer", "Starting...");
     if (!EasyServer.InitLog("World", "Configs/WorldLog.conf") || !EasyServer.InitConfig("Configs/World.xml", "World")) return;
     Port = EasyServer.GetConfValue<int>("World", "Address", "Port");
     IP1 = EasyServer.GetConfValue<Byte>("World", "Address", "IP1");
     IP2 = EasyServer.GetConfValue<Byte>("World", "Address", "IP2");
     IP3 = EasyServer.GetConfValue<Byte>("World", "Address", "IP3");
     IP4 = EasyServer.GetConfValue<Byte>("World", "Address", "IP4");
     if (!EasyServer.Listen<TcpServer>(Port, "ClientServer")) return;
     Database.Connection.connectionString = EasyServer.GetConfValue<String>("World", "Database", "ConnectionString");
     FileMgr = new FileManager();
     Password = EasyServer.GetConfValue<string>("World", "Lobby", "Password");
     WorldName = EasyServer.GetConfValue<string>("World", "ClientServer", "Name");
     ID = EasyServer.GetConfValue<Byte>("World", "ClientServer", "Id");
     Lobby = new Lobby.Client(EasyServer.GetConfValue<String>("World", "Lobby", "Ip"), EasyServer.GetConfValue<int>("World", "Lobby", "Port"));
     districtsListener = new Districts.Listener(EasyServer.GetConfValue<String>("World", "Districts", "Ip"), EasyServer.GetConfValue<int>("World", "Districts", "Port"));
     clients.Clear();
     Log.Enter();
     Console.WriteLine("For available console commands, type /commands");
     Log.Enter();
     bool done = false;
     while (!done)
     {
         string command;
         command = Console.ReadLine();
         ProccessCommand(command);
     }
     EasyServer.StartConsole();
 }
Exemplo n.º 8
1
        protected StreamContent(Byte[] contentBytes)
        {
            Debug.Assert(contentBytes != null);

            ContentBytes = contentBytes;
            ContentLength = (UInt32)contentBytes.Length;
        }
Exemplo n.º 9
1
		public static int IntPtrCopy(IntPtr source, Stream dest, int length)
		{
			var buffer = new Byte[length];
			Marshal.Copy(source, buffer, 0, length);
			dest.Write(buffer, 0, length);
			return length;
		}
Exemplo n.º 10
1
        static void Main(string[] args)
        {
            //AsyncReadOneFile();

            //AsyncReadMultiplyFiles();

            FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open,
               FileAccess.Read, FileShare.Read, 1024,
               FileOptions.Asynchronous);

            Byte[] data = new Byte[100];

            IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);

            while (!ar.IsCompleted)
            {
                Console.WriteLine("Операция не завершена, ожидайте...");
                Thread.Sleep(10);
            }

            Int32 bytesRead = fs.EndRead(ar);

            fs.Close();

            Console.WriteLine("Количество считаных байт = {0}", bytesRead);
            Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1));
        }
Exemplo n.º 11
1
        public Message Decode(Byte[] data)
        {
            Byte[] buffer = new Byte[14];
            if (data.Length >= 14)
                Buffer.BlockCopy(data, 0, buffer, 0, 14);
            else
                Buffer.BlockCopy(data, 0, buffer, 0, data.Length);
            MessageHeader header = analyseHead(buffer);
            Message msg = new Message();
            msg.header = header;

            Byte[] payload;
            if (header != null)
            {
                payload = new Byte[data.Length - header.PayloadDataStartIndex];
                Buffer.BlockCopy(data, header.PayloadDataStartIndex, payload, 0, payload.Length);
                if (header.MASK == charOne)
                {
                    for (int i = 0; i < payload.Length; i++)
                    {
                        payload[i] = (Byte)(payload[i] ^ header.Maskey[i % 4]);
                    }
                }
            }
            else
            {
                msg.Data = Encoding.UTF8.GetString(data);
                return msg;
            }

            if (header.Opcode == OperType.Text)
                msg.Data = Encoding.UTF8.GetString(payload);

            return msg;
        }
Exemplo n.º 12
1
 public GGuess()
 {
     _UserNum = (0);
     _AllJinbi = (0);
     _ResultUserNum = (0);
     _Status = (0);
 }
Exemplo n.º 13
1
 public static Byte[] Encrypt(Byte[] data, Byte[] Key)
 {
     if (data.Length == 0) {
         return data;
     }
     return ToByteArray(Encrypt(ToUInt32Array(data, true), ToUInt32Array(Key, false)), false);
 }
Exemplo n.º 14
1
        private void chatServer()
        {
            Boolean isListen = true;

            while (isListen)
            {
                Byte[] bytesFromClient = new Byte[2097152];
                int len = 0;
                try
                {
                    len = _userSocket.Receive(bytesFromClient);
                    byte[] receiveByte = new byte[len];
                    receiveByte = bytesFromClient;
                    Message.Message msg = Message.MessageHandle.deserialize(receiveByte);
                    _clientRoom.broadcast(msg);

                }
                catch (Exception e)
                {

                    isListen = false;
                    _clientRoom.removeUser(_userName);

                    _userSocket.Close();
                    _userSocket = null;
                    Debug.WriteLine(e);
                    Debug.WriteLine(_userName + "退出聊天");
                    LogService.LogError(e.ToString());

                }
            }
        }
        /// <summary>
        /// Print a nice visual of the Buffer starting at offset.
        /// </summary>
        /// <param name="buffer">Buffer.</param>
        /// <param name="Offset">Offset.</param>
        public static void PrintHEX(Byte[] buffer,
                                    int Offset = 0) {
            Console.WriteLine(" 0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F | Text    ");
            Console.WriteLine("------------------------------------------------|---------");
            int count = 0, cur = 0;
            String left = "", right = "";
            foreach (byte b in buffer) {
                if (cur >= Offset) {
                    if (count >= 16) {
                        Console.WriteLine("{0}| {1}", left, right);

                        left = "";
                        right = "";
                        count = 0;
                    }

                    left += String.Format("{0:x2} ", b);
                    if (b >= 32 && b <= 255)
                        right += (char)b;
                    else
                        right += ".";

                    count++;
                } else
                    cur++;
            }

            if (count > 0)
                Console.WriteLine("{0}| {1}", left.PadRight(48), right);
        }
Exemplo n.º 16
1
 public byte[] StreamToByte(System.IO.Stream Stream)
 {
     Int32 length = Stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(Stream.Length);
         Byte[] buffer = new Byte[length];
         Stream.Read(buffer, 0, length);
         return buffer;
 }
Exemplo n.º 17
1
 public District(DistrictTypes type, Byte id, LanguageCodes langCode = LanguageCodes.EN)
 {
     _type = type;
     _lang = langCode;
     Type = (Byte)((Byte)type + (Byte)langCode);
     Id = id;
 }
Exemplo n.º 18
1
 /// <summary>
 /// Checks if the bytes contains invalid UTF-8 bytes
 /// </summary>
 public static Boolean ContainsInvalidUTF8Bytes(Byte[] bytes)
 {
     Int32 bits = 0;
     Int32 i = 0, c = 0, b = 0;
     Int32 length = bytes.Length;
     for (i = 0; i < length; i++)
     {
         c = bytes[i];
         if (c > 128)
         {
             if ((c >= 254)) return true;
             else if (c >= 252) bits = 6;
             else if (c >= 248) bits = 5;
             else if (c >= 240) bits = 4;
             else if (c >= 224) bits = 3;
             else if (c >= 192) bits = 2;
             else return true;
             if ((i + bits) > length) return true;
             while (bits > 1)
             {
                 i++;
                 b = bytes[i];
                 if (b < 128 || b > 191) return true;
                 bits--;
             }
         }
     }
     return false;
 }
Exemplo n.º 19
1
        /// <summary>
        /// AES解密(无向量)
        /// </summary>
        /// <param name="encryptedBytes">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string AESDecryptWithoutVector(String Data, String Key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

            MemoryStream mStream = new MemoryStream(encryptedBytes);
            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
            //mStream.Seek( 0, SeekOrigin.Begin );
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
                byte[] tmp = new byte[encryptedBytes.Length + 32];
                int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                byte[] ret = new byte[len];
                Array.Copy(tmp, 0, ret, 0, len);
                return Encoding.UTF8.GetString(ret);
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
Exemplo n.º 20
1
        public static string[] Search(String[] token, String txt, out Byte distance)
        {
            if (txt.Length > 0)
            {
                Byte bestKey = 255;
                SortedDictionary<Byte, List<string>> matches = new SortedDictionary<byte, List<string>>();
                Docking.Tools.ITextMetric tm = new Docking.Tools.Levenshtein(50);
                foreach(string s in token)
                {
                    Byte d = tm.distance(txt, s);
                    if (d <= bestKey) // ignore worse matches as previously found
                    {
                        bestKey = d;
                        List<string> values;
                        if (!matches.TryGetValue(d, out values))
                        {
                            values = new List<string>();
                            matches.Add(d, values);
                        }
                        if (!values.Contains(s))
                            values.Add(s);
                    }
                }

                if (matches.Count > 0)
                {
                    List<string> result = matches[bestKey];
                    distance = bestKey;
                    return result.ToArray();
                }
            }
            distance = 0;
            return null;
        }
Exemplo n.º 21
0
 public UserLogonInstruction(string user, Byte connection) : base(3, true, user)
 { 
     this.user = user + '\0';
     this.connection = connection;
     userSent = true;
     length += clientName.Length + 1; 
 }
Exemplo n.º 22
0
		void BaseInit()
		{
			_state.Init();
			_previousByte = 0;
			for (UInt32 i = 0; i < Base.kNumRepDistances; i++)
				_repDistances[i] = 0;
		}
Exemplo n.º 23
0
 /// <summary>
 /// Takes in a byte array so it is possible to get the sequence number and packet data
 /// </summary>
 /// <param name="packetInfo"></param>
 public void convertToPacket(byte[] packetInfo)
 {
     Byte[] sequenceNumber = new Byte[4];
     sequenceNumber[0] = packetInfo[0];
     sequenceNumber[1] = packetInfo[1];
     sequenceNumber[2] = packetInfo[2];
     sequenceNumber[3] = packetInfo[3];
     // convert the sequence number to an int
     //string seqStr = BitConverter.ToString(sequenceNumber, 0);
     //packetNum = int.Parse(seqStr);
     packetNum = BitConverter.ToInt32(sequenceNumber, 0);
     // if start packet
     if (packetNum == 0)
     {
         isStartPacket = true;
         // the rest of the data is just the number of packets
         // the number is grabed and converted to int
         numOfPackets = BitConverter.ToInt32(packetInfo, 4);
         // array is resized to be the number of pieces of data
     }
     else
     {
         byte[] tempData = new byte[packetInfo.Length - 4];
         // convert the rest of the data to ascii text
         for (int i = 4; i < packetInfo.Length; i++)
         {
             tempData[i - 4] = packetInfo[i];
         }
         data = tempData;
     }
 }
Exemplo n.º 24
0
 private void StartListen2()
 {
     //Create an instance of TcpListener to listen for TCP connection.
     var tcpListener = new TcpListener(SampleTcpPort);
     try
     {
         while (true)
         {
             tcpListener.Start();
             //Program blocks on Accept() until a client connects.
             Socket soTcp = tcpListener.AcceptSocket();
             Console.Message = ("SampleClient is connected through TCP.");
             OnChanged(EventArgs.Empty);
             var received = new Byte[512];
             soTcp.Receive(received, received.Length, 0);
             String dataReceived = System.Text.Encoding.ASCII.GetString(received);
             Console.Message=(dataReceived);
             String returningString = "The Server got your message through TCP: " +
                                      dataReceived; OnChanged(EventArgs.Empty);
             Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes
                 (returningString.ToCharArray());
             //Returning a confirmation string back to the client.
             soTcp.Send(returningByte, returningByte.Length, 0);
         }
     }
     catch (SocketException se)
     {
         Console.Message = ("A Socket Exception has occurred!" + se); OnChanged(EventArgs.Empty);
     }
 }
Exemplo n.º 25
0
 public void Recieve()
 {
     Byte[] data = new Byte[256];
     NetworkStream stream = client.GetStream();
     String responseData = String.Empty;
     Int32 bytes = stream.Read(data, 0, data.Length);
 }
Exemplo n.º 26
0
    protected void EnviaFicheiro_Click(object sender, EventArgs e)
    {
        int tamanho = 0;
        byte[] vector = null;
        if (!FileUploadImagem.HasFile)
        {
            lbStatus.Text = "Não existe nenhum ficheiro selecionado";
            return;
        }
        string nomeFicheiro = FileUploadImagem.PostedFile.FileName;
        string ext = nomeFicheiro.Substring(nomeFicheiro.LastIndexOf("."));
        ext.ToLower();

        string imgTipo = FileUploadImagem.PostedFile.ContentType;

        if (ext != ".jpg" &&
            ext != ".bmp" &&
            ext != ".gif" &&
            ext != ".jpeg" &&
            ext != ".png" &&
            ext != ".tiff")
            lbStatus.Text = "Só são suportados os formatos: jpg/jpeg, bmp, gif, png, tiff";
        tamanho = Int32.Parse(FileUploadImagem.PostedFile.ContentLength.ToString());

        vector = new Byte[tamanho];
        FileUploadImagem.PostedFile.InputStream.Read(vector, 0, tamanho);

        if (GuardaImagem2(TextBoxTitulo.Text.Trim(), vector, tamanho, imgTipo))
            lbStatus.Text = "Imagem enviada.";
        else
            lbStatus.Text = "Erro ao enviar a imagem...";
    }
Exemplo n.º 27
0
        private string GetResponse(string apiVerb)
        {
            TcpClient tcpClient = new TcpClient("127.0.0.1", port);
            NetworkStream tcpStream = tcpClient.GetStream();

            Byte[] request = Encoding.ASCII.GetBytes(apiVerb);
            tcpStream.Write(request, 0, request.Length);

            Byte[] responseBuffer = new Byte[4096];
            string response = string.Empty;
            do
            {
                int bytesRead = tcpStream.Read(responseBuffer, 0, responseBuffer.Length);
                response = response + Encoding.ASCII.GetString(responseBuffer, 0, bytesRead);
            } while (tcpStream.DataAvailable);

            if (LogEvent != null)
            {
                LogEventArgs args = new LogEventArgs();

                args.DateTime = DateTime.Now;
                args.Request = apiVerb;
                args.Response = response;

                LogEvent(this, args);
            }

            tcpClient.Close();

            return response;
        }
Exemplo n.º 28
0
		public GroupFoundEventArgs (Byte connection, UInt16 start, UInt16 end, Byte[] uuid)
		{
			this.connection = connection;
			this.start = start;
			this.end = end;
			this.uuid = uuid;
		}
Exemplo n.º 29
0
        public static ResponseBuilder Connect(RequestBuilder request)
        {
            ResponseBuilder response = new ResponseBuilder();
            try
            {
                Socket s = Connect(request.CurrentURL.Host, request.CurrentURL.Port);
                if (s == null) throw new Exception("Connection failed");

                Byte[] bytesSent = Encoding.UTF8.GetBytes(request.ToString());
                Byte[] bytesReceived = new Byte[request.ToString().Length];

                // Send request to the server.
                s.Send(bytesSent, bytesSent.Length, 0);
                int bytes = 0;
                do
                {
                    // Receive response to the server.
                    bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
                    response.Append(Encoding.UTF8.GetString(bytesReceived, 0, bytes));
                }
                while (bytes > 0);
            }
            catch (Exception ex)
            {
                response.Clear();
                response.AppendLine(ex.Message);
                response.AppendLine(ex.StackTrace);
            }
            return response;
        }
Exemplo n.º 30
0
        public static void SendFileInfo()
        {

            // Получаем тип и расширение файла
            fileDet.FILETYPE = fs.Name.Substring((int)fs.Name.Length - 3, 3);

            // Получаем длину файла
            fileDet.FILESIZE = fs.Length;

            XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails));
            MemoryStream stream = new MemoryStream();

            // Сериализуем объект
            fileSerializer.Serialize(stream, fileDet);

            // Считываем поток в байты
            stream.Position = 0;
            Byte[] bytes = new Byte[stream.Length];
            stream.Read(bytes, 0, Convert.ToInt32(stream.Length));

            Console.WriteLine("Отправка деталей файла...");

            // Отправляем информацию о файле
            sender.Send(bytes, bytes.Length, endPoint);
            stream.Close();

        }
Exemplo n.º 31
0
/*
 *
 * static uavcan_message_descriptor_s uavcan_equipment_hardpoint_Status_descriptor = {
 *  UAVCAN_EQUIPMENT_HARDPOINT_STATUS_DT_SIG,
 *  UAVCAN_EQUIPMENT_HARDPOINT_STATUS_DT_ID,
 *  CanardTransferTypeBroadcast,
 *  sizeof(uavcan_equipment_hardpoint_Status),
 *  UAVCAN_EQUIPMENT_HARDPOINT_STATUS_MAX_PACK_SIZE,
 *  encode_func,
 *  decode_func,
 *  null
 * };
 */

        static void encode_uavcan_equipment_hardpoint_Status(uavcan_equipment_hardpoint_Status msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
        {
            uint8_t[] buffer = new uint8_t[8];
            _encode_uavcan_equipment_hardpoint_Status(buffer, msg, chunk_cb, ctx, true);
        }
Exemplo n.º 32
0
 //WRITE8_MEMBER( namco_53xx_device::P_w )
 public void P_w(address_space space, offs_t offset, u8 data, u8 mem_mask = 0xff)
 {
     m_p.op(space, 0, data);
 }
Exemplo n.º 33
0
 private static float ToSignedDistance(TLeafData value)
 {
     return((value / (float)TLeafData.MaxValue) * 2f - 1f);
 }
Exemplo n.º 34
0
 private void OnOwnerChanged(UInt8 owner)
 {
     controlPointAreaRenderer.material.color = controlPointAreaColors[owner];
 }
Exemplo n.º 35
0
 public void SetOwner(UInt8 owner)
 {
     Owner = owner;
     onOwnerChanged?.Invoke(Owner);
 }
Exemplo n.º 36
0
 protected abstract bool Read_Byte(ref SerializedType ioData);
Exemplo n.º 37
0
        /*
        ** This function returns a pointer to a nul-terminated string in memory
        ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
        ** string contains a copy of zRawSql but with host parameters expanded to
        ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
        ** then the returned string holds a copy of zRawSql with "-- " prepended
        ** to each line of text.
        **
        ** The calling function is responsible for making sure the memory returned
        ** is eventually freed.
        **
        ** ALGORITHM:  Scan the input string looking for host parameters in any of
        ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
        ** string literals, quoted identifier names, and comments.  For text forms,
        ** the host parameter index is found by scanning the perpared
        ** statement for the corresponding OP_Variable opcode.  Once the host
        ** parameter index is known, locate the value in p->aVar[].  Then render
        ** the value as a literal in place of the host parameter name.
        */
        static string sqlite3VdbeExpandSql(
            Vdbe p,          /* The prepared statement being evaluated */
            string zRawSql   /* Raw text of the SQL statement */
            )
        {
            sqlite3  db;                        /* The database connection */
            int      idx       = 0;             /* Index of a host parameter */
            int      nextIndex = 1;             /* Index of next ? host parameter */
            int      n;                         /* Length of a token prefix */
            int      nToken = 0;                /* Length of the parameter token */
            int      i;                         /* Loop counter */
            Mem      pVar;                      /* Value of a host parameter */
            StrAccum _out = new StrAccum(1000); /* Accumulate the _output here */
            //StringBuilder zBase = new StringBuilder( 100 ); /* Initial working space */
            int izRawSql = 0;

            db = p.db;
            sqlite3StrAccumInit(_out, null, 100,
                                db.aLimit[SQLITE_LIMIT_LENGTH]);
            _out.db = db;
            if (db.vdbeExecCnt > 1)
            {
                while (izRawSql < zRawSql.Length)
                {
                    //string zStart = zRawSql;
                    while (zRawSql[izRawSql++] != '\n' && izRawSql < zRawSql.Length)
                    {
                        ;
                    }
                    sqlite3StrAccumAppend(_out, "-- ", 3);
                    sqlite3StrAccumAppend(_out, zRawSql, (int)izRawSql);//zRawSql - zStart );
                }
            }
            else
            {
                while (izRawSql < zRawSql.Length)
                {
                    n = findNextHostParameter(zRawSql, izRawSql, ref nToken);
                    Debug.Assert(n > 0);
                    sqlite3StrAccumAppend(_out, zRawSql.Substring(izRawSql, n), n);
                    izRawSql += n;
                    Debug.Assert(izRawSql < zRawSql.Length || nToken == 0);
                    if (nToken == 0)
                    {
                        break;
                    }
                    if (zRawSql[izRawSql] == '?')
                    {
                        if (nToken > 1)
                        {
                            Debug.Assert(sqlite3Isdigit(zRawSql[izRawSql + 1]));
                            sqlite3GetInt32(zRawSql, izRawSql + 1, ref idx);
                        }
                        else
                        {
                            idx = nextIndex;
                        }
                    }
                    else
                    {
                        Debug.Assert(zRawSql[izRawSql] == ':' || zRawSql[izRawSql] == '$' || zRawSql[izRawSql] == '@');
                        testcase(zRawSql[izRawSql] == ':');
                        testcase(zRawSql[izRawSql] == '$');
                        testcase(zRawSql[izRawSql] == '@');
                        idx = sqlite3VdbeParameterIndex(p, zRawSql.Substring(izRawSql, nToken), nToken);
                        Debug.Assert(idx > 0);
                    }
                    izRawSql += nToken;
                    nextIndex = idx + 1;
                    Debug.Assert(idx > 0 && idx <= p.nVar);
                    pVar = p.aVar[idx - 1];
                    if ((pVar.flags & MEM_Null) != 0)
                    {
                        sqlite3StrAccumAppend(_out, "NULL", 4);
                    }
                    else if ((pVar.flags & MEM_Int) != 0)
                    {
                        sqlite3XPrintf(_out, "%lld", pVar.u.i);
                    }
                    else if ((pVar.flags & MEM_Real) != 0)
                    {
                        sqlite3XPrintf(_out, "%!.15g", pVar.r);
                    }
                    else if ((pVar.flags & MEM_Str) != 0)
                    {
#if !SQLITE_OMIT_UTF16
                        u8 enc = ENC(db);
                        if (enc != SQLITE_UTF8)
                        {
                            Mem utf8;
                            memset(&utf8, 0, sizeof(utf8));
                            utf8.db = db;
                            sqlite3VdbeMemSetStr(&utf8, pVar.z, pVar.n, enc, SQLITE_STATIC);
                            sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
                            sqlite3XPrintf(_out, "'%.*q'", utf8.n, utf8.z);
                            sqlite3VdbeMemRelease(&utf8);
                        }
                        else
#endif
                        {
                            sqlite3XPrintf(_out, "'%.*q'", pVar.n, pVar.z);
                        }
                    }

                    /*else if ( ( pVar.flags & MEM_Zero ) != 0 )
                     * {
                     * sqlite3XPrintf( _out, "zeroblob(%d)", pVar.u.nZero );
                     * } */
                    else
                    {
                        Debug.Assert((pVar.flags & MEM_Blob) != 0);
                        sqlite3StrAccumAppend(_out, "x'", 2);
                        for (i = 0; i < pVar.n; i++)
                        {
                            sqlite3XPrintf(_out, "%02x", pVar.zBLOB[i] & 0xff);
                        }
                        sqlite3StrAccumAppend(_out, "'", 1);
                    }
                }
            }
            return(sqlite3StrAccumFinish(_out));
        }
Exemplo n.º 38
0
 partial void OnShiftIdChanging(System.Byte value);
Exemplo n.º 39
0
 public virtual void Begin(bool invert = false, uint8_t contrast = 128, uint8_t Vpp = 0)
 {
 }
/*
 *
 * static uavcan_message_descriptor_s uavcan_protocol_AccessCommandShell_req_descriptor = {
 *  UAVCAN_PROTOCOL_ACCESSCOMMANDSHELL_REQ_DT_SIG,
 *  UAVCAN_PROTOCOL_ACCESSCOMMANDSHELL_REQ_DT_ID,
 *
 *  CanardTransferTypeRequest,
 *
 *  sizeof(uavcan_protocol_AccessCommandShell_req),
 *  UAVCAN_PROTOCOL_ACCESSCOMMANDSHELL_REQ_MAX_PACK_SIZE,
 *  encode_func,
 *  decode_func,
 *
 *  &uavcan_protocol_AccessCommandShell_res_descriptor
 *
 * };
 */


        static void encode_uavcan_protocol_AccessCommandShell_req(uavcan_protocol_AccessCommandShell_req msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
        {
            uint8_t[] buffer = new uint8_t[8];
            _encode_uavcan_protocol_AccessCommandShell_req(buffer, msg, chunk_cb, ctx, true);
        }
Exemplo n.º 41
0
 internal static string InvalidByteLengthDetected(System.Byte length)
 {
     return(Keys.GetString(Keys.InvalidByteLengthDetected, new object[] {
         length
     }));
 }
Exemplo n.º 42
0
 public ColorRGB(QuantumType red, QuantumType green, QuantumType blue)
     : base(new MagickColor(red, green, blue))
 {
 }
Exemplo n.º 43
0
        //! telegraph method : Decode
        public override Int32 Decode(ref Queue <System.Byte> InputQueue, ref Boolean tRequestDrop)
        {
            //! check input queue
            if ((null == InputQueue) || (null == m_Command) || (0 == InputQueue.Count))
            {
                return(0);
            }

            //! frame address
            System.Byte Command    = 0;
            System.Byte Address    = 0;
            UInt16      CheckSUM   = 0xFFFF;
            UInt16      DataLength = 0;

            System.Byte[] Datas = null;

            tRequestDrop = false;

            //! check the frame
            using (Queue <Byte> .Enumerator qEnumerator = InputQueue.GetEnumerator())
            {
                if (!qEnumerator.MoveNext())
                {
                    qEnumerator.Dispose();
                    return(0);
                }

                //! check frame head
                if (0xA5 != qEnumerator.Current)
                {
                    tRequestDrop = true;
                    qEnumerator.Dispose();
                    return(0);
                }


                Byte[] tLength = new Byte[2];
                //! get frame destination address
                if (!qEnumerator.MoveNext())
                {
                    qEnumerator.Dispose();
                    return(0);
                }
                else
                {
                    tLength[0] = qEnumerator.Current;
                    Get_CRC(ref CheckSUM, qEnumerator.Current);
                }


                //! get data length
                if (!qEnumerator.MoveNext())
                {
                    qEnumerator.Dispose();
                    return(0);
                }
                else
                {
                    tLength[1] = qEnumerator.Current;
                    Get_CRC(ref CheckSUM, qEnumerator.Current);

                    DataLength = BitConverter.ToUInt16(tLength, 0);
                    if (0 == DataLength)
                    {
                        qEnumerator.Dispose();
                        return(0);
                    }
                    DataLength--;
                    Datas = new Byte[DataLength];
                }

                //! get frame command
                if (!qEnumerator.MoveNext())
                {
                    qEnumerator.Dispose();
                    return(0);
                }
                else
                {
                    Address = qEnumerator.Current;
                    Get_CRC(ref CheckSUM, qEnumerator.Current);

                    if (m_Command.AddressValue != Address)
                    {
                        //! this frame not belong to this telegraph
                        tRequestDrop = true;
                        qEnumerator.Dispose();
                        return(0);
                    }
                }

                //! get frame command
                if (!qEnumerator.MoveNext())
                {
                    qEnumerator.Dispose();
                    return(0);
                }
                else
                {
                    Command = qEnumerator.Current;
                    Get_CRC(ref CheckSUM, qEnumerator.Current);

                    if ((m_Command.Command != Command) && (0xAC != Command))
                    {
                        //! this frame not belong to this telegraph
                        tRequestDrop = true;
                        qEnumerator.Dispose();
                        return(0);
                    }
                }


                //! get data
                for (System.Int32 n = 0; n < DataLength; n++)
                {
                    //! get frame data length
                    if (!qEnumerator.MoveNext())
                    {
                        qEnumerator.Dispose();
                        return(0);
                    }
                    else
                    {
                        Datas[n] = qEnumerator.Current;
                        Get_CRC(ref CheckSUM, qEnumerator.Current);
                    }
                }

                Byte[] tCheckSumBuffer = new Byte[2];
                //! get check sum Low Byte
                if (!qEnumerator.MoveNext())
                {
                    qEnumerator.Dispose();
                    return(0);
                }
                else
                {
                    tCheckSumBuffer[0] = qEnumerator.Current;
                }

                //! get check sum High Byte
                if (!qEnumerator.MoveNext())
                {
                    qEnumerator.Dispose();
                    return(0);
                }
                else
                {
                    tCheckSumBuffer[1] = qEnumerator.Current;
                    if (CheckSUM != BitConverter.ToUInt16(tCheckSumBuffer, 0))
                    {
                        tRequestDrop = true;
                        qEnumerator.Dispose();
                        return(0);
                    }
                }

                /*
                 * //! check frame tail
                 * if ((!qEnumerator.MoveNext()) || (0x55 != qEnumerator.Current))
                 * {
                 *  qEnumerator.Dispose();
                 *  return 0;
                 * }
                 */
                if (null != m_Timer)
                {
                    lock (m_Timer)
                    {
                        try
                        {
                            if (null != m_Timer)
                            {
                                //! start timer
                                m_Timer.Stop();
                                m_Timer.Enabled = false;
                                m_Timer.Dispose();
                                m_Timer = null;
                            }
                        }
                        catch (Exception) { }
                    }
                }
            }

            //! decoding success! now, we get all data from queue and create a report
            ESCommand tempCommand = new ESCommandReadBlock(Datas);   //!< create a command

            //! copy command properies from source command m_Command
            tempCommand.AddressValue = m_Command.AddressValue;
            tempCommand.Command      = Command;
            tempCommand.AddressValue = Address;
            tempCommand.Description  = m_Command.Description;
            tempCommand.ID           = m_Command.ID;
            tempCommand.ResponseMode = m_Command.ResponseMode;
            tempCommand.TimeOut      = m_Command.TimeOut;

            m_Command = tempCommand;

            //! raising event
            OnDecoderSuccess(tempCommand);

            //! return decode size
            return(7 + DataLength);
        }
Exemplo n.º 44
0
 protected abstract void Write_Byte(ref SerializedType ioData);
Exemplo n.º 45
0
 static void encode_org_cubepilot_uwb_Node(org_cubepilot_uwb_Node msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
 {
     uint8_t[] buffer = new uint8_t[8];
     _encode_org_cubepilot_uwb_Node(buffer, msg, chunk_cb, ctx, true);
 }
Exemplo n.º 46
0
 static void encode_uavcan_protocol_debug_LogLevel(uavcan_protocol_debug_LogLevel msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
 {
     uint8_t[] buffer = new uint8_t[8];
     _encode_uavcan_protocol_debug_LogLevel(buffer, msg, chunk_cb, ctx, true);
 }
Exemplo n.º 47
0
 public void Serialize(string inKey, ref SerializedType ioData, SerializedType inDefault, FieldOptions inOptions = FieldOptions.None)
 {
     DoSerialize <SerializedType>(inKey, ref ioData, inDefault, inOptions, Read_Byte, Write_Byte);
 }
 static void encode_uavcan_protocol_file_Error(uavcan_protocol_file_Error msg, dronecan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
 {
     uint8_t[] buffer = new uint8_t[8];
     _encode_uavcan_protocol_file_Error(buffer, msg, chunk_cb, ctx, true);
 }
Exemplo n.º 49
0
        private bool process_message()
        {
            Console.WriteLine("packet: " + gsof_msg.packettype.ToString("X") + " len: " + gsof_msg.length + " status: " +
                              gsof_msg.status);

            if (gsof_msg.packettype == 0x57) // RAWDATA
            {
                uint8_t record_type    = gsof_msg.data[0];
                uint8_t page_total     = (byte)(gsof_msg.data[1] & 0xf);
                uint8_t page_number    = (byte)((gsof_msg.data[1] >> 4) & 0xf);
                uint8_t reply_number   = (byte)gsof_msg.data[2];
                uint8_t recordintflags = gsof_msg.data[3];

                bool consise = (recordintflags & 0x1) > 0;

                Console.WriteLine(DateTime.Now.Second + " record type: " + record_type + " page_no " + page_number + "/" + page_total + " consise " + consise);

                if (record_type == 7)
                {
                    double p40 = Math.Pow(2, 40);
                    double p39 = Math.Pow(2, 39);
                    double p11 = Math.Pow(2, 11);
                    double p12 = Math.Pow(2, 12);
                    double p14 = Math.Pow(2, 14);
                    double p21 = Math.Pow(2, 21);
                    double p26 = Math.Pow(2, 26);
                    double p17 = Math.Pow(2, 17);
                    double p4  = Math.Pow(2, 4);

                    var test2 = (rt27_7_29)gsof_msg.data.ByteArrayToStructureBigEndian <rt27_7_29>(4);

                    long lat = byte2long(test2.Lat);
                    long lng = byte2long(test2.Lng);

                    Console.WriteLine("{0} {1} {2} {3} {4} {5} ", lat / p40, lng / p39, test2.Alt / p12,
                                      (test2.veln / p21), (test2.vele / p21), (test2.velu / p21),
                                      test2.rx_clock_offset / p26, test2.rx_clock_drift / p17, test2.hdop / p4);
                }
                else if (record_type == 1)
                {
                    var test2 = (rt27_1_11)gsof_msg.data.ByteArrayToStructureBigEndian <rt27_1_11>(4);

                    Console.WriteLine("{0} {1} {2}", ToDeg(test2.Latitude * Math.PI), ToDeg(test2.Longitude * Math.PI), test2.Altitude);
                }
                else if (record_type == 2)
                {
                    var test2 = (rt27_2_19)gsof_msg.data.ByteArrayToStructureBigEndian <rt27_2_19>(4);

                    Console.WriteLine("Event {0} {1} {2} {3}", test2.Source, test2.Port, test2.Number, test2.TOW);
                }
                else if (record_type == 6) // there is no documentation on this
                {
                    if (page_number == 1)
                    {
                        obsdata.Initialize();
                        Array.ConstrainedCopy(gsof_msg.data, 0, obsdata, 0, gsof_msg.length);
                    }
                    else
                    {
                        Array.ConstrainedCopy(gsof_msg.data, 4, obsdata, 248 + (page_number - 2) * 244, gsof_msg.length - 4);
                    }


                    if (page_number == page_total)
                    {
                        var m_epochHeader =
                            (rt27_6_27_epochHeader)
                            obsdata.ByteArrayToStructureBigEndian <rt27_6_27_epochHeader>(4);

                        var head_len = m_epochHeader.blockLength;

                        var m_sysOffsets = new rt27_6_27_sysOffsets();
                        var obj          = m_sysOffsets as object;
                        MavlinkUtil.ByteArrayToStructureEndian(obsdata, ref obj, (4 + head_len));
                        m_sysOffsets = (rt27_6_27_sysOffsets)obj;

                        var sysoffset_lemn = m_sysOffsets.blockLength;

                        var m_measurement = new List <rt27_6_27_measurement>();
                        var SVs           = m_epochHeader.nSVs;

                        var offset = 4 + head_len + sysoffset_lemn;

                        for (int index = 0; index < SVs; ++index)
                        {
                            var measheader = new rt27_6_27_measurementHeader();
                            obj = measheader as object;
                            MavlinkUtil.ByteArrayToStructureEndian(obsdata, ref obj, offset);
                            measheader = (rt27_6_27_measurementHeader)obj;
                            var meashead_len = measheader.blockLength;
                            offset += meashead_len;

                            string type = "";
                            switch (measheader.svType)
                            {
                            case 0:
                                type = "Gps";
                                break;

                            case 1:
                                type = "Sbas";
                                break;

                            case 2:
                                type = "Glonass";
                                break;

                            case 3:
                                type = "Galileo";
                                break;

                            case 4:
                                type = "QZSS";
                                break;

                            case 7:
                                type = "beidou";
                                break;
                            }

                            Console.WriteLine("prn {0} type {1} el {2} az {3} blocks {4}", measheader.prn, type, (double)(sbyte)measheader.elevation, (double)measheader.azimuth / Math.Pow(2.0, -1.0), measheader.nBlocks);

                            for (int a = 0; a < measheader.nBlocks; a++)
                            {
                                var measblock = new rt27_6_27_measurementBlock();
                                obj = measblock as object;
                                MavlinkUtil.ByteArrayToStructureEndian(obsdata, ref obj, offset);
                                measblock = (rt27_6_27_measurementBlock)obj;

                                if (a == 0)
                                {
                                    Console.WriteLine("{0} {1}", measblock.pseudorange / Math.Pow(2.0, 7.0), byte2long(measblock.phase) / Math.Pow(2.0, 15.0));
                                }
                                else
                                {
                                }

                                var measblock_len = measblock.blockLength;
                                offset += measblock_len;

                                m_measurement.Add(new rt27_6_27_measurement()
                                {
                                    block = measblock, header = measheader
                                });
                            }
                        }
                    }
                }
            }

            if (gsof_msg.packettype == 0x40) // GSOF
            {
                uint8_t trans_number = gsof_msg.data[0];
                uint8_t pageidx      = gsof_msg.data[1];
                uint8_t maxpageidx   = gsof_msg.data[2];

                //http://www.trimble.com/OEM_ReceiverHelp/V4.81/en/default.html
                //http://www.trimble.com/EC_ReceiverHelp/V4.19/en/GSOFmessages_Overview.htm
                Console.WriteLine("GSOF page: " + pageidx + " of " + maxpageidx);

                // want 2 8 9 38

                for (uint a = 3; a < gsof_msg.length; a++)
                {
                    uint8_t output_type = gsof_msg.data[a];
                    a++;
                    uint8_t output_length = gsof_msg.data[a];
                    a++;
                    Console.WriteLine("GSOF type: " + output_type + " len: " + output_length);

                    if (output_type == 2) // position
                    {
                        state.location.lat = (int32_t)(ToDeg(SwapDouble(gsof_msg.data, a)) * 1e7);
                        state.location.lng = (int32_t)(ToDeg(SwapDouble(gsof_msg.data, a + 8)) * 1e7);
                        state.location.alt = (int32_t)(SwapDouble(gsof_msg.data, a + 16) * 1e2);

                        state.last_gps_time_ms = state.time_week_ms;
                    }
                    else if (output_type == 8) // velocity
                    {
                        uint8_t vflag = gsof_msg.data[a];
                        if ((vflag & 1) == 1)
                        {
                            state.ground_speed  = SwapFloat(gsof_msg.data, a + 1);
                            state.ground_course = (float)(ToDeg(SwapFloat(gsof_msg.data, a + 5)));
                            fill_3d_velocity();
                            state.velocity.Z             = -SwapFloat(gsof_msg.data, a + 9);
                            state.have_vertical_velocity = true;
                        }
                    }
                    else if (output_type == 9) //dop
                    {
                        state.hdop = (uint16_t)(SwapFloat(gsof_msg.data, a + 4) * 100);
                    }
                    else if (output_type == 12) // position sigma
                    {
                        state.horizontal_accuracy = (SwapFloat(gsof_msg.data, a + 4) + SwapFloat(gsof_msg.data, a + 8)) /
                                                    2;
                        state.vertical_accuracy        = SwapFloat(gsof_msg.data, a + 16);
                        state.have_horizontal_accuracy = true;
                        state.have_vertical_accuracy   = true;
                    }
                    else if (output_type == 1) // pos time
                    {
                        state.time_week_ms = SwapUint32(gsof_msg.data, a);
                        state.time_week    = SwapUint16(gsof_msg.data, a + 4);
                        state.num_sats     = gsof_msg.data[a + 6];
                        uint8_t posf1 = gsof_msg.data[a + 7];
                        uint8_t posf2 = gsof_msg.data[a + 8];

                        Console.WriteLine("POSTIME: " + posf1 + " " + posf2);

                        if ((posf1 & 1) == 1)
                        {
                            state.status = AP_GPS.GPS_OK_FIX_3D;
                            if ((posf2 & 1) == 1)
                            {
                                state.status = AP_GPS.GPS_OK_FIX_3D_DGPS;
                                if ((posf2 & 4) == 4)
                                {
                                    state.status = AP_GPS.GPS_OK_FIX_3D_RTK;
                                }
                            }
                        }
                        else
                        {
                            state.status = AP_GPS.NO_FIX;
                        }
                    }

                    a += output_length - 1u;
                }


                Type        t  = state.GetType(); //where obj is object whose properties you need.
                FieldInfo[] pi = t.GetFields();
                foreach (var p in pi)
                {
                    System.Console.WriteLine(p.Name + "    " + p.GetValue(state).ToString());
                }

                return(true);
            }

            return(false);
        }
Exemplo n.º 50
0
        }                                                                   //auto k_port_callback() { return m_k.bind(); }

        //auto p_port_callback() { return m_p.bind(); }


        //READ8_MEMBER( namco_53xx_device::K_r )
        public u8 K_r(address_space space, offs_t offset, u8 mem_mask = 0xff)
        {
            return(m_k.op(0));
        }
/*
 *
 * static uavcan_message_descriptor_s uavcan_protocol_file_Delete_res_descriptor = {
 *  UAVCAN_PROTOCOL_FILE_DELETE_RES_DT_SIG,
 *  UAVCAN_PROTOCOL_FILE_DELETE_RES_DT_ID,
 *  CanardTransferTypeResponse,
 *  sizeof(uavcan_protocol_file_Delete_res),
 *  UAVCAN_PROTOCOL_FILE_DELETE_RES_MAX_PACK_SIZE,
 *  encode_func,
 *  decode_func,
 *  null
 * };
 */

        static void encode_uavcan_protocol_file_Delete_res(uavcan_protocol_file_Delete_res msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
        {
            uint8_t[] buffer = new uint8_t[8];
            _encode_uavcan_protocol_file_Delete_res(buffer, msg, chunk_cb, ctx, true);
        }
Exemplo n.º 52
0
        private bool parse(uint8_t temp)
        {
            switch (sbf_state)
            {
            case readstate.PREAMBLE1:
                if (temp == SBF_PREAMBLE1)
                {
                    sbf_state++;
                }
                else if (temp == '$')
                {
                    sbf_state++;
                }
                else
                {
                    Console.Write(".");
                }
                sbf_msg.read = 0;
                break;

            case readstate.PREAMBLE2:
                if (temp == SBF_PREAMBLE2)
                {
                    sbf_state++;
                }
                else if (temp == 'R')
                {
                    validcommand = true;
                }
                else
                {
                    Console.WriteLine("Bad Sync " + temp);
                    sbf_state = readstate.PREAMBLE1;
                }
                break;

            case readstate.CRC1:
                sbf_msg.crc = temp;
                sbf_state++;
                break;

            case readstate.CRC2:
                sbf_msg.crc += (uint16_t)(temp << 8);
                sbf_state++;
                break;

            case readstate.BLOCKID1:
                sbf_msg.blockid = temp;
                sbf_state++;
                break;

            case readstate.BLOCKID2:
                sbf_msg.blockid += (uint16_t)(temp << 8);
                sbf_state++;
                break;

            case readstate.LENGTH1:
                sbf_msg.length = temp;
                sbf_state++;
                break;

            case readstate.LENGTH2:
                sbf_msg.length += (uint16_t)(temp << 8);
                sbf_state++;
                sbf_msg.data = new uint8_t[sbf_msg.length];

                //Console.WriteLine((sbf_msg.blockid & 4095u) + " len " + sbf_msg.length);

                if (sbf_msg.length % 4 != 0)
                {
                    sbf_state = readstate.PREAMBLE1;
                }
                break;

            case readstate.DATA:
                sbf_msg.data[sbf_msg.read] = temp;
                sbf_msg.read++;
                if (sbf_msg.read >= (sbf_msg.length - 8))
                {
                    uint16_t crc = crc16.ccitt(sbf_msg.blockid, 2, 0);
                    crc = crc16.ccitt(sbf_msg.length, 2, crc);
                    crc = crc16.ccitt(sbf_msg.data, sbf_msg.length - 8, crc);

                    sbf_state = readstate.PREAMBLE1;

                    if (sbf_msg.crc == crc)
                    {
                        return(process_message());
                    }
                    else
                    {
                        crc_error_counter++;
                    }
                }
                break;
            }

            return(false);
        }
Exemplo n.º 53
0
 public MyOctreeNode(TLeafData allContent)
 {
     ChildMask = 0;
     SetAllData(allContent);
 }
Exemplo n.º 54
0
 protected override void device_reset()
 {
     m_value = 0;
 }
Exemplo n.º 55
0
            public Mem(sqlite3 db, string z, double r, int i, int n, u16 flags, u8 type, u8 enc
#if SQLITE_DEBUG
                       , Mem pScopyFrom, object pFiller /* pScopyFrom, pFiller */
#endif
                       )
            {
                this.db    = db;
                this.z     = z;
                this.r     = r;
                this.u.i   = i;
                this.n     = n;
                this.flags = flags;
#if SQLITE_DEBUG
                this.pScopyFrom = pScopyFrom;
                this.pFiller    = pFiller;
#endif
                this.type = type;
                this.enc  = enc;
            }
/*
 *
 * static uavcan_message_descriptor_s uavcan_equipment_air_data_StaticPressure_descriptor = {
 *  UAVCAN_EQUIPMENT_AIR_DATA_STATICPRESSURE_DT_SIG,
 *  UAVCAN_EQUIPMENT_AIR_DATA_STATICPRESSURE_DT_ID,
 *
 *  CanardTransferTypeBroadcast,
 *
 *  sizeof(uavcan_equipment_air_data_StaticPressure),
 *  UAVCAN_EQUIPMENT_AIR_DATA_STATICPRESSURE_MAX_PACK_SIZE,
 *  encode_func,
 *  decode_func,
 *
 *  null
 *
 * };
 */


        static void encode_uavcan_equipment_air_data_StaticPressure(uavcan_equipment_air_data_StaticPressure msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
        {
            uint8_t[] buffer = new uint8_t[8];
            _encode_uavcan_equipment_air_data_StaticPressure(buffer, msg, chunk_cb, ctx, true);
        }
Exemplo n.º 57
0
        static void Main(string[] args)
        {
            System.SByte   sb   = SByte.MaxValue;
            System.Byte    b    = Byte.MaxValue;
            System.Int16   i16  = Int16.MaxValue;
            System.Int32   i32  = Int32.MaxValue;
            System.Int64   i64  = Int64.MaxValue;
            System.UInt16  ui16 = UInt16.MaxValue;
            System.UInt32  ui32 = UInt32.MaxValue;
            System.UInt64  ui64 = UInt64.MaxValue;
            System.Char    ch   = 'C';
            System.Boolean bol  = true;
            System.Single  fl   = Single.MaxValue;
            System.Double  db   = Double.MaxValue;
            System.Decimal dc   = Decimal.MaxValue;
            System.String  st   = "Hello, world!";
            System.Object  obj  = null;

            /*
             * Console.WriteLine(
             * $"sb={sb}\n" +
             * $"b={b}\n" +
             * $"i16={i16}\n" +
             * $"i32={i32}\n" +
             * $"i64={i64}\n" +
             * $"ui16={ui16}\n" +
             * $"ui32={ui32}\n" +
             * $"ui64={ui64}\n" +
             * $"ch={ch}\n" +
             * $"bol={bol}\n" +
             * $"fl={fl}\n" +
             * $"db={db}\n" +
             * $"dc={dc}\n" +
             * $"st={st}\n" +
             * $"obj={obj}\n");*/

            byte   b1 = 1;
            short  b2 = b1;
            int    b3 = b2;
            long   b4 = b3;
            double b5 = b4;
            //Console.WriteLine(b5);

            double d1 = 1.543;
            long   d2 = (long)d1;

            Console.WriteLine("d2={0}", d2);
            int   i1 = Int32.MaxValue;
            short i2 = (short)i1;

            Console.WriteLine("i2={0}", i2);
            short s1 = 5545;
            byte  s2 = (byte)s1;

            Console.WriteLine("s2={0}", s2);
            int  I1 = -123;
            uint I2 = (uint)I1;

            Console.WriteLine("I2={0}", I2);

            double D1 = 4.123031777776333;
            float  D2 = (float)D1;

            Console.WriteLine("D2={0}", D2);


            int    X = 10;
            object Obj;

            Obj = X;
            int Y = (int)Obj;

            Console.WriteLine("Y={0}", Y);



            var Str = "Hello, world!";

            Console.WriteLine(Str.GetType());


            int?null1 = null;
            int null2 = null1 ?? 5;

            Console.WriteLine("null2={0}", null2);

            char[] a  = { 'f', 'f', 'f', 'f' };
            string a1 = new string(a);
            string a2 = new string('f', 4);

            Console.WriteLine(a1 == a2);



            string Str1 = "Hello";
            string Str2 = ", ";
            string Str3 = "world!";

            Console.WriteLine(String.Concat(Str1, Str2, Str3));

            Console.WriteLine();

            Console.WriteLine("--------------------------------------------");

            string text = "Thisstring";

            text = text.Insert(4, " is");
            text = text.Insert(7, " a ");
            text = text.Insert(10, "My ");

            text = text.Remove(10, 3);

            string[] words = text.Split(' ');
            foreach (string s in words)
            {
                Console.WriteLine(s);
            }


            Console.WriteLine("--------------------------------------------");

            string NullSt = "";

            Console.WriteLine($"Length={NullSt.Length}");



            Console.WriteLine("--------------------------------------------");


            StringBuilder StrB = new StringBuilder("world");

            StrB.Append("!!!!!");

            StrB.Insert(0, "Beautiful ");
            Console.WriteLine(StrB);


            Console.WriteLine("--------------------------------------------");



            int[][] Mas = new int[3][];

            Mas[0] = new int[5] {
                1, 2, 3, 4, 5
            };
            Mas[1] = new int[4] {
                1, 2, 3, 4
            };
            Mas[2] = new int[4] {
                1, 2, 3, 4
            };

            for (int i = 0; i < Mas.Length; i++)
            {
                for (int j = 0; j < Mas[i].Length; j++)
                {
                    Console.Write($"  {Mas[i][j]}   ");
                }
                Console.WriteLine();
            }

            Console.WriteLine();


            Console.WriteLine("--------------------------------------------");


            string[] MasStr = { "aaaaaaaaa", "11111111", "44444444444" };


            Console.WriteLine($"Size MasStr={MasStr.Length}");
            Console.WriteLine("Enter number and value\n");
            int num = Int32.Parse(Console.ReadLine());


            MasStr[num] = Console.ReadLine();



            Console.WriteLine("--------------------------------------------");

            Console.WriteLine();


            for (int i = 0; i < MasStr.Length; i++)
            {
                Console.WriteLine(MasStr[i]);
            }
            Console.WriteLine();



            Console.WriteLine("--------------------------------------------");



            double[][] MasD = new double[3][];

            for (int i = 0; i < MasD.Length; i++)
            {
                MasD[i] = new double[i + 1];
                for (int j = 0; j < i + 1; j++)
                {
                    MasD[i][j] = Double.Parse(Console.ReadLine());
                }
            }



            for (int i = 0; i < MasD.Length; i++)
            {
                for (int j = 0; j < MasD[i].Length; j++)
                {
                    Console.Write($"  { MasD[i][j]}   ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();


            Console.WriteLine("--------------------------------------------");


            var MasInt    = new[] { 12.23, 323.2, 322 };
            var MasString = new[] { "ABC", null };



            ValueTuple <int, string, char, string, ulong> cortage = (1, "22", 'f', "rrr", UInt64.MaxValue);


            Console.WriteLine($"{cortage.Item1} {cortage.Item3} { cortage.Item4}");
            int    CorInt  = cortage.Item1;
            string CorStr1 = cortage.Item2;
            string CorStr2 = cortage.Item4;
            char   CorCh   = cortage.Item3;
            ulong  CorUl   = cortage.Item5;



            int[] arr = new int[4] {
                1, 2, 3, 4
            };

            var Typle = CreateCortage(arr, text);

            Console.WriteLine(Typle);
            Console.WriteLine("--------------------------------------------");



            Console.ReadKey();
        }
Exemplo n.º 58
0
        }                                                      //DECLARE_READ_LINE_MEMBER( bit5_q_r ) { return BIT(m_value, 5) ^ 1; }

        //DECLARE_READ_LINE_MEMBER( bit6_q_r ) { return BIT(m_value, 6) ^ 1; }
        //DECLARE_READ_LINE_MEMBER( bit7_q_r ) { return BIT(m_value, 7) ^ 1; }

        /* write bit x from data into bit determined by offset */
        /* latch = (latch & ~(1<<offset)) | (((data >> x) & 0x01) << offset) */

        public void bit0_w(address_space space, offs_t offset, u8 data, u8 mem_mask = 0xff)
        {
            bitx_w(0, offset, data);
        }                                                                                                                 //WRITE8_MEMBER( latch8_device::bit0_w ) { bitx_w(0, offset, data); }
Exemplo n.º 59
0
/*
 *
 * static uavcan_message_descriptor_s uavcan_equipment_esc_RawCommand_descriptor = {
 *  UAVCAN_EQUIPMENT_ESC_RAWCOMMAND_DT_SIG,
 *  UAVCAN_EQUIPMENT_ESC_RAWCOMMAND_DT_ID,
 *
 *  CanardTransferTypeBroadcast,
 *
 *  sizeof(uavcan_equipment_esc_RawCommand),
 *  UAVCAN_EQUIPMENT_ESC_RAWCOMMAND_MAX_PACK_SIZE,
 *  encode_func,
 *  decode_func,
 *
 *  null
 *
 * };
 */


        static void encode_uavcan_equipment_esc_RawCommand(uavcan_equipment_esc_RawCommand msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
        {
            uint8_t[] buffer = new uint8_t[8];
            _encode_uavcan_equipment_esc_RawCommand(buffer, msg, chunk_cb, ctx, true);
        }
/*
 *
 * static uavcan_message_descriptor_s uavcan_protocol_param_GetSet_req_descriptor = {
 *  UAVCAN_PROTOCOL_PARAM_GETSET_REQ_DT_SIG,
 *  UAVCAN_PROTOCOL_PARAM_GETSET_REQ_DT_ID,
 *  CanardTransferTypeRequest,
 *  sizeof(uavcan_protocol_param_GetSet_req),
 *  UAVCAN_PROTOCOL_PARAM_GETSET_REQ_MAX_PACK_SIZE,
 *  encode_func,
 *  decode_func,
 *  &uavcan_protocol_param_GetSet_res_descriptor
 * };
 */

        static void encode_uavcan_protocol_param_GetSet_req(uavcan_protocol_param_GetSet_req msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx)
        {
            uint8_t[] buffer = new uint8_t[8];
            _encode_uavcan_protocol_param_GetSet_req(buffer, msg, chunk_cb, ctx, true);
        }