//public int Publish(string topic, MqttPayload payload, QoS qos, bool retained) //{ // return 0; //} public int Publish(MqttParcel parcel) { ushort messageId = MessageId; int index = 0; int tmp = 0; int fixedHeader = 0; int varHeader = 0; int payload = 0; int remainingLength = 0; int returnCode = 0; byte[] buffer = null; // Setup a UTF8 encoder UTF8Encoding encoder = new UTF8Encoding(); // Encode the topic byte[] utf8Topic = Encoding.UTF8.GetBytes(parcel.Topic); // Some error checking // Topic contains wildcards if ((parcel.Topic.IndexOf('#') != -1) || (parcel.Topic.IndexOf('+') != -1)) { //return Constants.TOPIC_WILDCARD_ERROR; } // Topic is too long or short if ((utf8Topic.Length > Constants.MAX_TOPIC_LENGTH) || (utf8Topic.Length < Constants.MIN_TOPIC_LENGTH)) { //return Constants.TOPIC_LENGTH_ERROR; } // Calculate the size of the var header varHeader += 2; // Topic Name Length (MSB, LSB) varHeader += utf8Topic.Length; // Length of the topic // Calculate the size of the fixed header fixedHeader++; // byte 1 // Calculate the payload payload = parcel.Payload.ToString().Length; // Calculate the remaining size remainingLength = varHeader + payload; // Check that remaining length will fit into 4 encoded bytes if (remainingLength > Constants.MAXLENGTH) { //return Constants.MESSAGE_LENGTH_ERROR; } // Add space for each byte we need in the fixed header to store the length tmp = remainingLength; while (tmp > 0) { fixedHeader++; tmp = tmp / 128; }; // End of Fixed Header // Build buffer for message buffer = new byte[fixedHeader + varHeader + payload]; // Start of Fixed header // Publish (3.3) buffer[index++] = Constants.MQTT_PUBLISH_TYPE; // Encode the fixed header remaining length // Add remaining length index = doRemainingLength(remainingLength, index, buffer); // End Fixed Header // Start of Variable header // Length of topic name buffer[index++] = (byte)(utf8Topic.Length / 256); // Length MSB buffer[index++] = (byte)(utf8Topic.Length % 256); // Length LSB // Topic for (var i = 0; i < utf8Topic.Length; i++) { buffer[index++] = utf8Topic[i]; } // End of variable header // Start of Payload // Message (Length is accounted for in the fixed header) for (var i = 0; i < parcel.Payload.TrimmedBuffer.Length; i++) { buffer[index++] = (byte)parcel.Payload.TrimmedBuffer[i]; } // End of Payload try { returnCode = _socket.Send(buffer, buffer.Length, 0); } catch (Exception ex) { _logger.Error("Error on publish " + ex.Message); } if (returnCode < buffer.Length) { //return Constants.CONNECTION_ERROR; } return messageId; }
private static void StayAlive(Object state) { var topic = String.Concat("SA", _settings.Key); var parcel = new MqttParcel(topic, new MqttPayload(topic), QoS.BestEfforts, false); _mqtt.Publish(parcel); }