コード例 #1
0
ファイル: MQTTClient.cs プロジェクト: winnubstj/Gimbl
        public void Connect(bool verbose)
        {
            // Connect to broker.
            IPAddress ipAdress = IPAddress.Parse(ip);

            // disable weird obsolote constructor warning.
            #pragma warning disable 618
            client = new MqttClient(ipAdress, port, false, null, null, MqttSslProtocols.None);
            // Run connect as task so we can wait for timeout (cant be programatically changed otherwise and is really long...).
            Task t = Task.Run(() =>
            {
                byte msg = client.Connect(Guid.NewGuid().ToString());
                MqttMsgConnack connack = new MqttMsgConnack(); //for debugging.
                connack.GetBytes(msg);
                // Set callback on message.
                client.MqttMsgPublishReceived += ReceivedMessage;
                if (verbose)
                {
                    UnityEngine.Debug.Log(String.Format("Succesfully connected to MQTT Broker at: {0}:{1}", ip, port));
                }
            });
            TimeSpan ts = TimeSpan.FromMilliseconds(1000);
            if (!t.Wait(ts))
            {
                UnityEngine.Debug.LogError(String.Format("Could not connect to MQTT broker at {0}:{1}", ip, port));
            }
        }
コード例 #2
0
ファイル: MqttClient.cs プロジェクト: refap3/refAP3repo
        /// <summary>
        /// Connect to broker
        /// </summary>
        /// <param name="clientId">Client identifier</param>
        /// <param name="username">Username</param>
        /// <param name="password">Password</param>
        /// <param name="willRetain">Will retain flag</param>
        /// <param name="willQosLevel">Will QOS level</param>
        /// <param name="willFlag">Will flag</param>
        /// <param name="willTopic">Will topic</param>
        /// <param name="willMessage">Will message</param>
        /// <param name="cleanSession">Clean sessione flag</param>
        /// <param name="keepAlivePeriod">Keep alive period</param>
        /// <returns>Return code of CONNACK message from broker</returns>
        public byte Connect(string clientId,
                            string username        = null,
                            string password        = null,
                            bool willRetain        = false,
                            byte willQosLevel      = MqttMsgConnect.QOS_LEVEL_AT_LEAST_ONCE,
                            bool willFlag          = false,
                            string willTopic       = null,
                            string willMessage     = null,
                            bool cleanSession      = true,
                            ushort keepAlivePeriod = MqttMsgConnect.KEEP_ALIVE_PERIOD_DEFAULT)
        {
            // create CONNECT message
            MqttMsgConnect connect = new MqttMsgConnect(clientId,
                                                        username,
                                                        password,
                                                        willRetain,
                                                        willQosLevel,
                                                        willFlag,
                                                        willTopic,
                                                        willMessage,
                                                        cleanSession,
                                                        keepAlivePeriod);

            try
            {
                this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // try connection to the broker
                this.socket.Connect(new IPEndPoint(this.brokerIpAddress, this.brokerPort));
            }
            catch
            {
                throw new MqttConnectionException();
            }

            this.lastSend  = 0;
            this.isRunning = true;
            // start thread for receiving messages from broker
            this.receiveThread = new Thread(this.ReceiveThread);
            this.receiveThread.Start();

            MqttMsgConnack connack = (MqttMsgConnack)this.SendReceive(connect.GetBytes());

            // if connection accepted, start keep alive timer
            if (connack.ReturnCode == MqttMsgConnack.CONN_ACCEPTED)
            {
                this.IsConnected = true;

                this.keepAlivePeriod = keepAlivePeriod * 1000; // convert in ms

                // start thread for sending keep alive message to the broker
                this.keepAliveThread = new Thread(this.KeepAliveThread);
                this.keepAliveThread.Start();
            }
            return(connack.ReturnCode);
        }
コード例 #3
0
        public void ConnackBasicDecodeTest5()
        {
            // Arrange
            byte[]     correctEncoded = new byte[] { 3, 1, 138, 0 };
            MokChannel mokChannel     = new MokChannel(correctEncoded);
            // Act
            MqttMsgConnack connack = MqttMsgConnack.Parse((byte)(MqttMessageType.ConnectAck) << 4, MqttProtocolVersion.Version_5, mokChannel);

            // Assert
            Assert.Equal(true, connack.SessionPresent);
            Assert.Equal((byte)MqttReasonCode.Banned, (byte)connack.ReturnCode);
        }
コード例 #4
0
        public MqttMsgConnack CreateConnack(MqttProtocolVersion proctocolVersion, byte returnCode, bool sessionPresent)
        {
            var connack = new MqttMsgConnack {
                ReturnCode = returnCode
            };

            if (proctocolVersion == MqttProtocolVersion.Version_3_1_1)
            {
                connack.SessionPresent = sessionPresent;
            }

            return(connack);
        }
コード例 #5
0
        private void SendConnack(uint clientIndex, bool cleanSession, byte returnCode, bool isWebSocketClient)
        {
            MqttMsgConnack connack = MsgBuilder.BuildConnack(cleanSession, returnCode);

            if (!isWebSocketClient)
            {
                tcpServer.Send(clientIndex, connack.GetBytes());
            }
            else
            {
                wsServer.Send(clientIndex, connack.GetBytes());
            }
            //Send(clientIndex, connack.GetBytes(), connack.GetBytes().Length);
        }
コード例 #6
0
        public static MqttMsgConnack BuildConnack(bool sp, byte returnCode)
        {
            MqttMsgConnack connack = new MqttMsgConnack();
            //Fixed header first byte
            byte fixedHeaderB1 = (byte)(MqttMsgBase.MQTT_MSG_CONNACK_TYPE << MqttMsgBase.MSG_TYPE_OFFSET);
            //Variable header bytes
            byte variableHeaderB1 = (sp) ? (byte)0x01 : (byte)0x00;
            byte variableHeaderB2 = returnCode;

            int remainingLenght = variableHeaderB1 + variableHeaderB2;

            byte[] data = new byte[fixedHeaderB1 + remainingLenght];
            data[0] = fixedHeaderB1;
            connack.encodeRemainingLength(remainingLenght, data, 1);
            return(connack);
        }
コード例 #7
0
        public void ConnackAdvanceDecodeTestv5()
        {
            //Arrange
            byte[] encodedCorrect = new byte[] { 124, 1, 138, 121, 17, 0, 0, 9, 164, 33, 0, 89, 36, 1, 37, 1, 39, 0, 0, 17, 215, 18, 0, 6, 84, 97, 103, 97,
                                                 100, 97, 34, 0, 148, 31, 0, 4, 110, 111, 110, 101, 38, 0, 3, 79, 110, 101, 0, 8, 80, 114, 111, 112, 101, 114,
                                                 116, 121, 38, 0, 3, 84, 119, 111, 0, 10, 80, 114, 111, 112, 101, 114, 116, 105, 101, 115, 40, 1, 41, 1, 42,
                                                 1, 19, 5, 77, 26, 0, 11, 105, 110, 102, 114, 111, 109, 97, 116, 105, 111, 110, 28, 0, 9, 114, 101, 102, 101,
                                                 114, 101, 110, 99, 101, 21, 0, 6, 109, 101, 116, 104, 111, 100, 22, 0, 4, 1, 2, 3, 4 };
            MokChannel mokChannel = new MokChannel(encodedCorrect);
            // Act
            MqttMsgConnack connack = MqttMsgConnack.Parse((byte)(MqttMessageType.ConnectAck) << 4, MqttProtocolVersion.Version_5, mokChannel);

            // Assert
            Assert.Equal(true, connack.SessionPresent);
            Assert.Equal((byte)MqttReasonCode.Banned, (byte)connack.ReturnCode);
            Assert.Equal(connack.AssignedClientIdentifier, "Tagada");
            Assert.Equal(connack.AuthenticationData, new byte[] { 1, 2, 3, 4 });
            Assert.Equal(connack.AuthenticationMethod, "method");
            Assert.Equal(connack.MaximumPacketSize, 4567);
            Assert.Equal(connack.MaximumQoS, true);
            Assert.Equal(connack.Reason, "none");
            Assert.Equal(connack.ReceiveMaximum, (ushort)89);
            Assert.Equal(connack.ResponseInformation, "infromation");
            Assert.Equal(connack.RetainAvailable, true);
            Assert.Equal(connack.ServerKeepAlive, (ushort)1357);
            Assert.Equal(connack.ServerReference, "reference");
            Assert.Equal(connack.SessionExpiryInterval, 2468);
            Assert.Equal(connack.SharedSubscriptionAvailable, true);
            Assert.Equal(connack.SubscriptionIdentifiersAvailable, true);
            Assert.Equal(connack.TopicAliasMaximum, (ushort)148);
            Assert.Equal(connack.UserProperties.Count, 2);
            var prop = new UserProperty("One", "Property");

            Assert.Equal(((UserProperty)connack.UserProperties[0]).Name, prop.Name);
            Assert.Equal(((UserProperty)connack.UserProperties[0]).Value, prop.Value);
            prop = new UserProperty("Two", "Properties");
            Assert.Equal(((UserProperty)connack.UserProperties[1]).Name, prop.Name);
            Assert.Equal(((UserProperty)connack.UserProperties[1]).Value, prop.Value);
            Assert.Equal(connack.WildcardSubscriptionAvailable, true);
        }
コード例 #8
0
        public static void Connack(MqttClientConnection clientConnection, MqttMsgConnect connect, byte returnCode, string clientId, bool sessionPresent)
        {
            clientConnection.LastCommunicationTime = Environment.TickCount;

            MqttMsgConnack connack = new MqttMsgConnack();

            connack.ReturnCode = returnCode;
            if (clientConnection.ProtocolVersion == MqttProtocolVersion.Version_3_1_1)
            {
                connack.SessionPresent = sessionPresent;
            }

            // ... send it to the client
            Send(clientConnection, connack);

            // connection accepted, start keep alive thread checking
            if (returnCode == MqttMsgConnack.CONN_ACCEPTED)
            {
                // [v3.1.1] if client id isn't null, the CONNECT message has a cliend id with zero bytes length
                //          and broker assigned a unique identifier to the client
                clientConnection.ClientId     = (clientId == null) ? connect.ClientId : clientId;
                clientConnection.CleanSession = connect.CleanSession;
                clientConnection.WillFlag     = connect.WillFlag;
                clientConnection.WillTopic    = connect.WillTopic;
                clientConnection.WillMessage  = connect.WillMessage;
                clientConnection.WillQosLevel = connect.WillQosLevel;

                clientConnection.KeepAlivePeriod = connect.KeepAlivePeriod * 1000; // convert in ms
                // broker has a tolerance of 1.5 specified keep alive period
                clientConnection.KeepAlivePeriod += (clientConnection.KeepAlivePeriod / 2);

                clientConnection.IsConnectionClosing = false;
                clientConnection.IsConnected         = true;
            }
            // connection refused, close TCP/IP channel
            else
            {
                clientConnection.OnConnectionClosed();
            }
        }
コード例 #9
0
        public static MqttMsgBase DecodeControlPacket(byte[] data)
        {
            byte fixedHeaderFirstByte = (byte)(data[0] >> MqttMsgBase.MSG_TYPE_OFFSET);

            switch (fixedHeaderFirstByte)
            {
            case MqttMsgBase.MQTT_MSG_CONNECT_TYPE:
            {
                return(MqttMsgConnect.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_CONNACK_TYPE:
            {
                return(MqttMsgConnack.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBLISH_TYPE:
            {
                return(MqttMsgPublish.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBACK_TYPE:
            {
                return(MqttMsgPuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBREC_TYPE:
            {
                return(MqttMsgPubrec.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBREL_TYPE:
            {
                return(MqttMsgPubrel.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE:
            {
                return(MqttMsgPubcomp.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE:
            {
                return(MqttMsgSubscribe.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_SUBACK_TYPE:
            {
                return(MqttMsgSuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE:
            {
                return(MqttMsgUnsubscribe.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE:
            {
                return(MqttMsgUnsuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PINGREQ_TYPE:
            {
                return(MqttMsgPingReq.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PINGRESP_TYPE:
            {
                return(MqttMsgPingResp.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_DISCONNECT_TYPE:
            {
                CrestronLogger.WriteToLog("PACKETDECODER - Riconosciuto DISCONNNECT: ", 1);
                return(MqttMsgDisconnect.Parse(data));
            }

            default:
            {
                throw new FormatException();
            }
            }
        }
コード例 #10
0
ファイル: MqttClient.cs プロジェクト: refap3/refAP3repo
        /// <summary>
        /// Thread for receiving messages from broker
        /// </summary>
        private void ReceiveThread()
        {
            int readBytes;

            byte[] fixedHeaderFirstByte = new byte[1];
            byte   msgType;

            while (this.isRunning)
            {
                try
                {
                    // read first byte (fixed header)
                    readBytes = this.socket.Receive(fixedHeaderFirstByte);

                    if (readBytes > 0)
                    {
                        // extract message type from received byte
                        msgType = (byte)((fixedHeaderFirstByte[0] & MqttMsgBase.MSG_TYPE_MASK) >> MqttMsgBase.MSG_TYPE_OFFSET);

                        switch (msgType)
                        {
                        // impossible, broker can't send CONNECT message
                        case MqttMsgBase.MQTT_MSG_CONNECT_TYPE:

                            throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);

                        // CONNACK message received from broker
                        case MqttMsgBase.MQTT_MSG_CONNACK_TYPE:

                            this.msgReceived = MqttMsgConnack.Parse(fixedHeaderFirstByte[0], this.socket);
                            this.endReceiving.Set();
                            break;

                        // impossible, broker can't send PINGREQ message
                        case MqttMsgBase.MQTT_MSG_PINGREQ_TYPE:

                            throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);

                        // CONNACK message received from broker
                        case MqttMsgBase.MQTT_MSG_PINGRESP_TYPE:

                            this.msgReceived = MqttMsgPingResp.Parse(fixedHeaderFirstByte[0], this.socket);
                            this.endReceiving.Set();
                            break;

                        // impossible, broker can't send SUBSCRIBE message
                        case MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE:

                            throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);

                        // SUBACK message received from broker
                        case MqttMsgBase.MQTT_MSG_SUBACK_TYPE:

                            this.msgReceived = MqttMsgSuback.Parse(fixedHeaderFirstByte[0], this.socket);
                            this.endReceiving.Set();

                            // raise subscribed topic event (SUBACK message received)
                            this.OnMqttMsgSubscribed((MqttMsgSuback)this.msgReceived);

                            break;

                        // PUBLISH message received from broker
                        case MqttMsgBase.MQTT_MSG_PUBLISH_TYPE:

                            MqttMsgPublish msgReceived = MqttMsgPublish.Parse(fixedHeaderFirstByte[0], this.socket);

                            // for QoS Level 1 and 2, client sends PUBACK message to broker
                            if ((this.msgReceived.QosLevel == MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE) ||
                                (this.msgReceived.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE))
                            {
                                MqttMsgPuback puback = new MqttMsgPuback();
                                puback.MessageId = (msgReceived).MessageId;
                                this.Send(puback.GetBytes());
                            }

                            // raise PUBLISH message received event
                            this.OnMqttMsgPublishReceived(msgReceived);

                            break;

                        // PUBACK message received from broker
                        case MqttMsgBase.MQTT_MSG_PUBACK_TYPE:

                            this.msgReceived = MqttMsgPuback.Parse(fixedHeaderFirstByte[0], this.socket);
                            this.endReceiving.Set();

                            // raise published message event
                            // (PUBACK received for QoS Level 1)
                            this.OnMqttMsgPublished(((MqttMsgPuback)this.msgReceived).MessageId);

                            break;

                        // PUBREC message received from broker
                        case MqttMsgBase.MQTT_MSG_PUBREC_TYPE:

                            this.msgReceived = MqttMsgPubrec.Parse(fixedHeaderFirstByte[0], this.socket);
                            this.endReceiving.Set();
                            break;

                        // impossible, broker can't send PUBREL message
                        case MqttMsgBase.MQTT_MSG_PUBREL_TYPE:

                            throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);

                        // PUBCOMP message received from broker
                        case MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE:

                            this.msgReceived = MqttMsgPubcomp.Parse(fixedHeaderFirstByte[0], this.socket);
                            this.endReceiving.Set();

                            // raise published message event
                            // (PUBCOMP received for QoS Level 2)
                            this.OnMqttMsgPublished(((MqttMsgPuback)this.msgReceived).MessageId);

                            break;

                        // impossible, broker can't send UNSUBSCRIBE message
                        case MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE:

                            throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);

                        // UNSUBACK message received from broker
                        case MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE:

                            this.msgReceived = MqttMsgUnsuback.Parse(fixedHeaderFirstByte[0], this.socket);
                            this.endReceiving.Set();

                            // raise unsubscribed topic event
                            this.OnMqttMsgUnsubscribed(((MqttMsgUnsuback)this.msgReceived).MessageId);

                            break;

                        default:

                            throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage);
                        }

                        this.exReceiving = null;
                    }
                }
                catch (Exception)
                {
                    this.exReceiving = new MqttCommunicationException();
                }
            }
        }
コード例 #11
0
        public MqttMsgBase DecodeControlPacket(byte[] data)
        {
            byte fixedHeaderFirstByte = (byte)(data[0] >> MSG_TYPE_OFFSET);

            switch (fixedHeaderFirstByte)
            {
            case MqttMsgBase.MQTT_MSG_CONNECT_TYPE:
            {
                return(MqttMsgConnect.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_CONNACK_TYPE:
            {
                return(MqttMsgConnack.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBLISH_TYPE:
            {
                return(MqttMsgPublish.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBACK_TYPE:
            {
                return(MqttMsgPuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBREC_TYPE:
            {
                return(MqttMsgPubrec.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBREL_TYPE:
            {
                return(MqttMsgPubrel.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE:
            {
                return(MqttMsgPubcomp.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE:
            {
                return(MqttMsgSubscribe.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_SUBACK_TYPE:
            {
                return(MqttMsgSuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE:
            {
                return(MqttMsgUnsubscribe.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE:
            {
                return(MqttMsgUnsuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PINGREQ_TYPE:
            {
                return(MqttMsgPingReq.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PINGRESP_TYPE:
            {
                return(MqttMsgPingResp.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_DISCONNECT_TYPE:
            {
                return(MqttMsgDisconnect.Parse(data));
            }

            default:
            {
                throw new FormatException(" First byte shifted : " + fixedHeaderFirstByte);
            }
            }
        }
コード例 #12
0
        static void Main(string[] args)
        {
            // Pre-amble
            Console.WriteLine("Please ensure the scaling is set to 1 for calibration\n");
            msgBuffer = new List <Data>();

            // Read settings file.
            DirectoryInfo mainDir   = new DirectoryInfo(Directory.GetCurrentDirectory());
            var           yamlFiles = mainDir.GetFiles("settings.yml");

            if (yamlFiles.Length == 0)
            {
                Exit("Could not find settings.yml");
            }
            FileInfo yamlFile = yamlFiles[0];

            var dse = new Deserializer();

            //Console.WriteLine("Reading YAML: {0}", yamlFile.FullName);
            using (var yamlStream = yamlFile.Open(FileMode.Open))
            {
                using (var yamlReader = new StreamReader(yamlStream, Encoding.UTF8, true))
                {
                    settings = dse.Deserialize <Settings>(yamlReader);
                }
            }

            // Connect to broker.
            #region Connect to Broker.
            IPAddress ipAdress = IPAddress.Parse("127.0.0.1");
            Console.WriteLine(String.Format("Connecting to: 127.0.0.1:1883"));
            client = new MqttClient(settings.brokerIp, 1883, false, null, null, MqttSslProtocols.None);
            try
            {
                byte           msg     = client.Connect(Guid.NewGuid().ToString());
                MqttMsgConnack connack = new MqttMsgConnack();
                connack.GetBytes(msg);
                if (!client.IsConnected)
                {
                    Exit("Failed to connect");
                }
            }
            catch { Exit("Failed to connect"); }
            #endregion

            // Subscribe to topic.
            #region Subscribe to topic
            client.MqttMsgPublishReceived += receiveMessage;

            string topic = string.Format("{0}/Data", settings.deviceName);
            Console.WriteLine(String.Format("Subscribing to topic: {0}\n", topic));
            try { client.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); }
            catch { Exit("Failed to subscribe to topic"); }
            #endregion

            // Ask radius.
            float circumference = 2f * (float)Math.PI * settings.radius;
            float arcLength     = circumference / 2;

            // Request axis to calibrate.
            ConsoleKeyInfo axisString = new ConsoleKeyInfo();
            while (axisString.Key != ConsoleKey.E)
            {
                Console.Write("Calibrate: (P)itch, (R)oll, (Y)aw (E)xit\n");
                axisString = Console.ReadKey();
                int axis = 0;
                switch (axisString.Key)
                {
                case ConsoleKey.P:
                {
                    axis = 1;
                    break;
                }

                case ConsoleKey.R:
                {
                    axis = 2;
                    break;
                }

                case ConsoleKey.Y:
                {
                    axis = 3;
                    break;
                }

                case ConsoleKey.E:
                {
                    continue;
                }

                default: { Exit("Not recognized"); break; }
                }

                // Ask average.
                int averageNum = int.Parse(QuestionString("Average over how many measurements?:"));

                // Start measurement.
                string[] axisNames    = { "Pitch", "Roll", "Yaw" };
                float[]  measurements = new float[averageNum];

                for (int i = 0; i < averageNum; i++)
                {
                    // clean buffer.
                    msgBuffer.Clear();
                    Console.WriteLine(string.Format(
                                          "Rotate treadmill +180 degrees in {0} direction (Left-hand rule)\nand press any key.",
                                          axisNames[axis - 1]));
                    Console.ReadKey();

                    // collect data
                    Data result = new Data();
                    lock (msgBuffer)
                    {
                        result.pitch = msgBuffer.Sum(x => x.pitch);
                        result.roll  = msgBuffer.Sum(x => x.roll);
                        result.yaw   = msgBuffer.Sum(x => x.yaw);
                    }

                    // read buffer.
                    switch (axis)
                    {
                    case 1:
                        measurements[i] = result.pitch;
                        break;

                    case 2:
                        measurements[i] = result.roll;
                        break;

                    case 3:
                        measurements[i] = result.yaw;
                        break;
                    }

                    // Output.
                    Console.WriteLine(string.Format("\nPitch: {0:0.00},\tRoll: {1:0.00},\tYaw: {2:0.00}",
                                                    result.pitch, result.roll, result.yaw));
                    // Yaw: degrees.
                    if (axis == 3)
                    {
                        Console.WriteLine(string.Format("Calibration value: {0:0.0000000}",
                                                        Math.Abs(180 / measurements[i])));
                    }
                    // Pitch/Roll: arc length.
                    else
                    {
                        Console.WriteLine(string.Format("Calibration value: {0:0.0000000}",
                                                        Math.Abs(arcLength / measurements[i])));
                    }
                }
                // Averaged result.
                Console.WriteLine("\nResult:");

                // Yaw: degrees.
                if (axis == 3)
                {
                    Console.WriteLine(string.Format("Averaged calibration value: {0:0.0000000}",
                                                    Math.Abs(180 / measurements.Average())));
                }
                // Pitch/Roll: arc length.
                else
                {
                    Console.WriteLine(string.Format("Averaged calibration value: {0:0.0000000}",
                                                    Math.Abs(arcLength / measurements.Average())));
                }
            }
            Exit("\nDone!");
        }
コード例 #13
0
 private void HandleCONNACKType(MqttMsgConnack mqttMsgConnack)
 {
     SubscribeToTopics();
     //StartKeepAlive();
     tcpClient.ReceiveDataAsync(ReceiveCallback);
 }
コード例 #14
0
        public MqttMsgBase DecodeControlPacket(byte[] data)
        {
            #if PACKET_DEBUG
            CrestronLogger.WriteToLog("MQTTCLIENT - RECEIVE - " + BitConverter.ToString(data), 2);
            #endif

            byte fixedHeaderFirstByte = (byte)(data[0] >> MSG_TYPE_OFFSET);

            switch (fixedHeaderFirstByte)
            {
            case MqttMsgBase.MQTT_MSG_CONNECT_TYPE:
            {
                return(MqttMsgConnect.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_CONNACK_TYPE:
            {
                return(MqttMsgConnack.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBLISH_TYPE:
            {
                return(MqttMsgPublish.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBACK_TYPE:
            {
                return(MqttMsgPuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBREC_TYPE:
            {
                return(MqttMsgPubrec.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBREL_TYPE:
            {
                return(MqttMsgPubrel.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE:
            {
                return(MqttMsgPubcomp.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE:
            {
                return(MqttMsgSubscribe.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_SUBACK_TYPE:
            {
                return(MqttMsgSuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE:
            {
                return(MqttMsgUnsubscribe.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE:
            {
                return(MqttMsgUnsuback.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PINGREQ_TYPE:
            {
                return(MqttMsgPingReq.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_PINGRESP_TYPE:
            {
                return(MqttMsgPingResp.Parse(data));
            }

            case MqttMsgBase.MQTT_MSG_DISCONNECT_TYPE:
            {
                return(MqttMsgDisconnect.Parse(data));
            }

            default:
            {
                throw new FormatException(" First byte shifted : " + fixedHeaderFirstByte);
            }
            }
        }
コード例 #15
0
ファイル: MqttClient.cs プロジェクト: fasteddy516/SimplMQTT
 private void HandleCONNACKType(MqttMsgConnack mqttMsgConnack)
 {
     SubscribeToTopics();
     ClientReceiveDataAsync();
     OnConnectionStateChanged(1); // SIMPL+ doesn't need to think we're connected until the login process is complete
 }