Skip to content

Putty custom protocol

Uffe Björklund edited this page Jun 16, 2015 · 6 revisions

There is a custom protocol for testing with Putty included in XSockets. That protocol is really stupid and expects the client to pass in data in the form controller|topic|data. We would like to mimic the IR-temp data that we will get from the sensor, so to achieve this we can create another stupid custom protocol.

####Custom NdcProtocol

Just inherit the PuttyProtocol like below and we have almost everything in place...

    using XSockets.Core.Common.Protocol;
using XSockets.Plugin.Framework;
using XSockets.Plugin.Framework.Attributes;
using XSockets.Protocol.Putty;

/// <summary>
/// A really simple/stupid protocol for Putty.
/// </summary>
[Export(typeof(IXSocketProtocol), Rewritable = Rewritable.No)]
public class NdcProtocol : PuttyProtocol
{
    public NdcProtocol()
    {
        this.ProtocolProxy = new NdcProtocolProxy();
    }

    /// <summary>
    /// The string to return after handshake
    /// </summary>
    public override string HostResponse
    {
        get { return "Welcome to NdcProtocol"; }
    }

    public override IXSocketProtocol NewInstance()
    {
        return new NdcProtocol();
    }
}

####Custom NdcProtocolProxy The IProtocolProxy module will allow you to have custom formatting of data before it is sent into the server. So in this case we want our stupid "extended" NdcProtocol to assume that we pass in temperatures when we send the "irtempchange" topic.

    using System.Collections.Generic;
using System.Linq;
using System.Text;
using XSockets.Core.Common.Protocol;
using XSockets.Core.Common.Socket.Event.Arguments;
using XSockets.Core.Common.Socket.Event.Interface;
using XSockets.Core.Common.Utility.Serialization;
using XSockets.Core.XSocket.Model;
using XSockets.Plugin.Framework;

/// <summary>
/// Special proxy for sensor demo... We will expect double,double if the topic is "irtempchange"
/// Just to make things easier in the demo...
/// </summary>
public class NdcProtocolProxy : IProtocolProxy
{
    private IXSocketJsonSerializer JsonSerializer { get; set; }

    public NdcProtocolProxy()
    {
        JsonSerializer = Composable.GetExport<IXSocketJsonSerializer>();
    }
    public IMessage In(IEnumerable<byte> payload, MessageType messageType)
    {
        var data = Encoding.UTF8.GetString(payload.ToArray());
        if (data.Length == 0) return null;
        var d = data.Split('|');
        switch (d[1])
        {
            case "irtempchange":
                var v = d[2].Split(',');
                return new Message(new { obj = v[0], amb = v[1] }, d[1], d[0], JsonSerializer);
            default:
                return new Message(d[2], d[1], d[0], JsonSerializer);

        }
    }

    public byte[] Out(IMessage message)
    {
        return Encoding.UTF8.GetBytes(string.Format("{0}|{1}|{2}\r\n", message.Controller, message.Topic, message.Data));
    }
}

next

Clone this wiki locally